diff --git a/.npmignore b/.npmignore deleted file mode 100644 index 4d6551e3c32e46db18b1ea4766782397428aad6f..0000000000000000000000000000000000000000 --- a/.npmignore +++ /dev/null @@ -1,25 +0,0 @@ -/.git/ -/.vscode/ -/dist/test/ -/dist/types/ -/config/ -/node_modules/ -/pages/ -/config/ -/core/ -/test/ -/upload/ -.editorconfig -.gitignore -.npmignore -.prettierrc -笔记 -log.out -package-lock.json -package.json -tsconfig.json -tslint.json -Gruntfile.js -dump.rdb -.DS_Store -index.d.ts \ No newline at end of file diff --git a/.vscode/launch.json b/.vscode/launch.json deleted file mode 100644 index 647c0bc77bca0d6b47e2e0e9d80147fdb10f10aa..0000000000000000000000000000000000000000 --- a/.vscode/launch.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - // Use IntelliSense to learn about possible attributes. - // Hover to view descriptions of existing attributes. - // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 - "version": "0.2.0", - "configurations": [ - { - "type": "node", - "request": "launch", - "name": "Launch Program", - "program":"${file}", - "preLaunchTask": "tsc: build - tsconfig.json", - "sourceMaps": true, - - "outFiles": [ - "${workspaceFolder}/**/*.js" - ], - "cwd": "${workspaceRoot}" - } - ] -} \ No newline at end of file diff --git a/app.js b/app.js index 3ddd1cf3f87807bffd9fb14361ddcea4f5607d6d..f1dd48e6d577dbfa51965e2ff00908948cb5677a 100644 --- a/app.js +++ b/app.js @@ -2,4 +2,14 @@ Object.defineProperty(exports, "__esModule", { value: true }); const noomi_1 = require("./dist/core/main/noomi"); noomi_1.noomi(3000); +// setImmediate(()=>{ +// console.log(RouteFactory.routeMap); +// // console.log(RouteFactory.dynaRouteArr); +// console.log(InstanceFactory.factory); +// }) +// setTimeout(()=>{ +// console.log(RouteFactory.routeMap); +// // console.log(RouteFactory.dynaRouteArr); +// console.log(InstanceFactory.factory); +// },1000) //# sourceMappingURL=app.js.map \ No newline at end of file diff --git a/app.ts b/app.ts index aa6e641ebca7f0a639cd65e8e836c55b938fe7f6..ba99801853a4dd95b53cb601fa57abfe989eb4b0 100644 --- a/app.ts +++ b/app.ts @@ -1,2 +1,46 @@ +import { TranslatorFactory } from "relaen"; +import { AopFactory } from "./core/main/aopfactory"; +import { InstanceFactory } from "./core/main/instancefactory"; import { noomi } from "./core/main/noomi"; -noomi(3000); \ No newline at end of file +import { RouteFactory } from "./core/main/route/routefactory"; +import { FilterFactory } from "./core/web/filterfactory"; +noomi(3000); +// NoomiSecurity.init('./config/security.json') +// setImmediate(()=>{ +// console.log(RouteFactory.routeMap); +// // console.log(RouteFactory.dynaRouteArr); +// console.log(InstanceFactory.factory); + +// }) +// console.log(RouteFactory.routeMap); + +setTimeout(()=>{ + console.log(RouteFactory.routeMap); + // console.log(AopFa); + + // console.log(RouteFactory); + // console.log(AopFactory.get); + + // console.log(InstanceFactory.factory); + +},1000) +function compareMap(srcM:Map,tag:Map):boolean{ + + if(srcM.size !== tag.size){ + return false; + } + for(let tmp of srcM.keys()){ + if(tag.has(tmp)){ + let a = srcM.get(tmp); + let b = tag.get(tmp); + + for(let k of Object.keys(a)){ + if(a[k] !== b[k]){ + return false; + } + } + + } + } + return true; +} \ No newline at end of file diff --git a/config/database/mysql.json b/config/database/mysql.json index 86c1c6549edde43a8b7066357cf0759a77dcea53..644d4c4011778abb686c3781b407b2f79df5f8d4 100644 --- a/config/database/mysql.json +++ b/config/database/mysql.json @@ -1,31 +1,15 @@ { - //数据库产品,字符串,可选值:mysql,oracle,mssql,sequelize,默认mysql "product":"mysql", - //连接管理器实例名,字符串,如果不设置,则根据product自动生成,如product为mysql, - //则connection_manager为mysqlConnectionManager, - //可以使用自定义connection_mananger,需实现ConnectionManager接口 - "connection_manager":"mssqlConnectionManager", - //是否使用数据库连接池,如果设置为true,则options选项需按照数据库产品的连接规则设置连接池相关属性, - //此设置对mssql和sequelize无效,mssql仅支持连接池的连接方式。sequelzie由配置文件内部设置 "use_pool":true, - //数据库连接属性,请参考各数据库产品的连接设置方式 "options":{ "host":"localhost", "port":3306, "user":"root", - "password":"field", - "database":"codement", + "password":"root123", + "database":"noomisecuritytest", "connectionLimit":10 }, - //事务设置,当存在该项时,noomi开启事务嵌套能力 "transaction":{ - //事务实例名,如果不设置,则根据product自动生成,如果自定义事务,请继承Transaction接口 - // "transaction":"mssqlTransaction", - //隔离级, 针对sequelzie,如果为数据库,则执行数据库的隔离级 - //取值: 1 read uncommited, 2 read commited, 3 repeatable read, 4 serializable - // "isolation_level":2, - //方法表达式,符合表达式条件的方法会被设置为事务方法,调用时该方法涉及的数据库操作会加入事务执行,当出现异常时,会进行事务回滚 - //如下所示,如果实例名以service开头,其下所有方法都将作为事务方法 - // "expressions":["service*.*"] + "expressions":[] } } \ No newline at end of file diff --git a/config/database/relaen.json b/config/database/relaen.json index 8c1c685cc9e95985d4e52e2d5594b9c4b11f5dd0..68ed48c6be8dac6a17fd670df2808870497106b5 100644 --- a/config/database/relaen.json +++ b/config/database/relaen.json @@ -6,14 +6,14 @@ "host":"localhost", "port":3306, "username":"root", - "password":"field", - "database":"test", + "password":"root123", + "database":"work", "pool":{ "min":0, "max":10 }, "entities": [ - "/dist/test/app/module/dao/entity/**/*.js" + "/dist/module/dao/entity/**/*.js" ], "cache":true, "debug":true diff --git a/config/logger.json b/config/logger.json new file mode 100644 index 0000000000000000000000000000000000000000..882fc28a360e66fea0d88babdbe879b785e6fd6e --- /dev/null +++ b/config/logger.json @@ -0,0 +1,4 @@ +{ + "debug":false, + "fileLog":true +} \ No newline at end of file diff --git a/config/noomi.json b/config/noomi.json index ba53db59d7e5c2b04bc6be6da88adf31a34eaadd..32eb15e1d1f66073357cf65ab5752f7e29b2c4a8 100644 --- a/config/noomi.json +++ b/config/noomi.json @@ -2,17 +2,18 @@ { "app_name":"App", //应用名,当一个服务器运行多个应用时,需要配置 "language":"zh", //框架提示语言(可选配置),zh中文,en英文,默认zh - "open_watcher":true, //打开file watcher + "open_watcher":false, //打开file watcher "cluster":false, //集群设置,如果设置为true,则表示运行于集群环境,所有NCaceh的save_type都设置为1 "web":"web.json", - "instance":["/dist/test/app/module/**/*.js"], - // "launchhook":"launchhook.json", + "instance":["/dist/module/**/*.js"], + "launchhook":"launchhook.json", // "aop":"aop.json", - // "database":"database/relaen.json", + "database":"database/mysql.json", // "route":"route.json" // "filter":"filter.json", // "redis":"redis.json" // "security":"security.json" + "logger":"logger.json" } \ No newline at end of file diff --git a/config/security.json b/config/security.json index fb579db9a32520d66b2c35c144dbd7c31a0f5f30..bfbbcc14e3e1d66ae5893480d0d8b4be3c483a2d 100644 --- a/config/security.json +++ b/config/security.json @@ -8,13 +8,13 @@ "dboption":{ "product":"mysql", //数据库连接设置,如果没有配置database,则此项必填,否则使用数据库配置中的数据库connection manager - "conn_cfg":{ + // "conn_cfg":{ - "user":"root", - "password":"field", - "host":"localhost", - "database":"codement" - }, + // "user":"root", + // "password":"field", + // "host":"localhost", + // "database":"codement" + // }, //鉴权相关数据表名字映射,如果与默认值相同,则不用配置,数据表结构详情请参考安全管理器节 /*"tables":{ "groupAuthority":"t_group_authority", //组权限表名,默认t_group_authority diff --git a/config/web.json b/config/web.json index ecd38b669c83c9a2988ad4e27b648b554779d8e0..aed002c1b64955ebe837f0488bb8784d8c0c6e3c 100644 --- a/config/web.json +++ b/config/web.json @@ -2,7 +2,7 @@ "web_config":{ "upload_tmp_dir":"/upload/tmp", //上传临时目录,相对于项目根目录,以/开始 "upload_max_size":0, //上传内容最大字节数 - "static_path":["/test/pages","/upload"], //静态资源路径 + "static_path":["/test/pages","/upload","/zjstest.html"], //静态资源路径 "welcome":"/test/pages/index.html", //welcome 页面 //跨域设置 "cors":{ diff --git a/core/database/dbmanager.ts b/core/database/dbmanager.ts index a0adba912e35102ad54d769a806118b3f0f86c4d..36d77c79c39633c62e8371d0157763b4852bc6f8 100644 --- a/core/database/dbmanager.ts +++ b/core/database/dbmanager.ts @@ -8,6 +8,7 @@ import { MssqlConnectionManager } from "./mssqlconnectionmanager"; import { TypeormConnectionManager } from "./typeormconnectionmanager"; import { IConnectionManager } from "./connectionmanager"; import { RelaenConnectionManager } from "./relaenconnectionmanager"; +import { Util } from "../tools/util"; /** * 数据库管理器 @@ -16,9 +17,9 @@ import { RelaenConnectionManager } from "./relaenconnectionmanager"; */ class DBManager{ /** - * 连接管理器实例名 + * 连接管理器类的引用 */ - static connectionManagerName:string; + static connectionManager:any; /** * 事务类名 */ @@ -37,13 +38,32 @@ class DBManager{ let product:string = cfg.product||'mysql'; this.product = product; //connection manager配置 - let cm:any; - let cmName:string = cfg.connection_manager || 'noomi_connection_manager'; + let cm:any;//连接实例 + let clazz:any;//连接类 //先查询是否有自定义的connection manager if(cfg.connection_manager){ - cm = InstanceFactory.getInstance(cmName); + let path = Util.getAbsPath([process.cwd(),...cfg.connection_manager.split('/')]) + try{ + const tmp = require(path); + for(let i of Object.keys(tmp)){ + if(typeof tmp[i] === 'function' && tmp[i].name){ + clazz = tmp[i]; + break; + } + } + cm = Reflect.construct(clazz,[]); + InstanceFactory.addInstance({ + instance:cm, + class:clazz, + }); + }catch(e){ + new NoomiError("2801"); + } + }else{ + cm = undefined; } //新建connection manager + //connection manager 类 if(!cm && product){ let opt = cfg.options; opt.usePool = cfg.use_pool; @@ -51,8 +71,7 @@ class DBManager{ opt.useTransaction = cfg.transaction?true:false; // connection manager let cm:IConnectionManager; - //connection manager 类 - let clazz:any; + switch(product){ case "mysql": cm = new MysqlConnectionManager(opt); @@ -78,12 +97,11 @@ class DBManager{ } //添加到实例工厂 InstanceFactory.addInstance({ - name:cmName, instance:cm, - class:clazz + class:clazz, }); } - this.connectionManagerName = cmName; + this.connectionManager = clazz; //事务配置 if(cfg.transaction){ let opt = cfg.transaction; @@ -97,7 +115,7 @@ class DBManager{ * @returns connection manager */ static getConnectionManager():IConnectionManager{ - return InstanceFactory.getInstance(this.connectionManagerName); + return InstanceFactory.getInstance(this.connectionManager); } /** diff --git a/core/database/mysqlconnectionmanager.ts b/core/database/mysqlconnectionmanager.ts index 4ba3597ab4df0b0f69bee81b6b7e07e0a4b7bdb8..e656c4c434a834b90581a8ab4fb3631bf1e7cf3e 100644 --- a/core/database/mysqlconnectionmanager.ts +++ b/core/database/mysqlconnectionmanager.ts @@ -56,7 +56,7 @@ class MysqlConnectionManager implements IConnectionManager{ * @returns connection 对象 */ async getConnection():Promise{ - let conn = await TransactionManager.getConnection(); + let conn = await TransactionManager.getConnection();//当前线程Id存在事务的连接 if(conn){ return conn; } diff --git a/core/database/transactionmanager.ts b/core/database/transactionmanager.ts index 5e24fae1926898ccfb0d07c88705591bc748634d..5aea5a512fd1c7af3eb1be60b8e0ca21bd96e33b 100644 --- a/core/database/transactionmanager.ts +++ b/core/database/transactionmanager.ts @@ -12,6 +12,7 @@ import { MssqlTransaction } from "./mssqltransaction"; import { TypeormTransaction } from "./typeormtransaction"; import { RelaenTransaction } from "./relaentransaction"; import { NoomiThreadLocal } from "../tools/threadlocal"; +import { Util } from "../tools/util"; class TransactionManager{ /** @@ -21,7 +22,7 @@ class TransactionManager{ /** * transaction 实例名 */ - private static transactionMdl:string; + private static transactionMdl:any; /** * 切点名 @@ -31,7 +32,7 @@ class TransactionManager{ /** * 切面名 */ - public static aspectName:string = '__NOOMI_TX_ASPECT'; + public static aspectName:string; /** * 隔离级 1read uncommited 2read commited 3repeatable read 4serializable @@ -44,21 +45,39 @@ class TransactionManager{ public static transactionOption:any; /** - * 事务注册map,键为事务类名,值为[methodName1,methodName2,...] + * 事务注册map,键为事务类引用,值为[methodName1,methodName2,...] */ - private static registTransactionMap:Map = new Map(); + private static registTransactionMap:Map = new Map(); static init(cfg:any){ this.initAdvice(); //transaction实例名 - this.transactionMdl = cfg.transaction||'__noomi_transaction'; + // this.transactionMdl = cfg.transaction||'__noomi_transaction'; + if(cfg.transaction){ + //加载自定义事务类 + let path = Util.getAbsPath([process.cwd(),...cfg.transaction.split('/')]) + try{ + const tmp = require(path); + for(let i of Object.keys(tmp)){ + if(typeof tmp[i] === 'function' && tmp[i].name){ + this.transactionMdl = tmp[i]; + break; + } + } + }catch(e){ + throw new NoomiError("2810"); + } + }else{ + this.transactionMdl = NoomiTransaction; + } + this.aspectName = this.transactionMdl.name; //隔离级 if(cfg.isolation_level && typeof cfg.isolation_level === 'number'){ this.isolationLevel = cfg.isolation_level; } //添加transaction到实例工厂,已存在则不再添加 - let tn:string = this.transactionMdl; + let tn:any = this.transactionMdl; //事务类 let clazz:any; if(tn){ @@ -100,7 +119,6 @@ class TransactionManager{ break; } InstanceFactory.addInstance({ - name:tn, class:clazz, singleton:false }); @@ -110,51 +128,51 @@ class TransactionManager{ /** * 注册事务,在addInstance时正式添加到aop - * @param className 类名 + * @param clazz 类的引用 * @param methodName 方法名或方法名串,支持通配符"*" */ - public static registTransaction(className:string,methodName:string|string[]){ + public static registTransaction(clazz:any,methodName:string|string[]){ let arr = typeof methodName === 'string'?[methodName]:methodName; - if(this.registTransactionMap.has(className)){ - arr = this.registTransactionMap.get(className).concat(arr); + if(this.registTransactionMap.has(clazz)){ + arr = this.registTransactionMap.get(clazz).concat(arr); } - this.registTransactionMap.set(className,arr); + this.registTransactionMap.set(clazz,arr); } /** - * 处理实例事务,用于把事务注册map的事务添加到事务aop - * @param instanceName 实例名 - * @param className 类名 + * 处理实例事务, + * @param clazz 类的引用 + * @returns */ - public static handleInstanceTranstraction(instanceName:string,className:string){ - if(!this.registTransactionMap.has(className)){ + public static handleInstanceTranstraction(clazz:any){ + if(!this.registTransactionMap.has(clazz)){ return; } - const methods = this.registTransactionMap.get(className); + const methods = this.registTransactionMap.get(clazz); if(methods){ - this.addTransaction(instanceName,methods); + // this.addTransaction(instanceName,methods); + this.addTransaction(clazz,methods); } //删除已处理的class - this.registTransactionMap.delete(className); + this.registTransactionMap.delete(clazz); } /** * 添加为事务 - * @param instance 实例 或 类 + * @param instance 类的引用 * @param methodName 方法名 */ - public static addTransaction(instance:any,methodName:any){ - let pc = AopFactory.getPointcutById(this.pointcutId); - let name:string = typeof instance === 'string'?instance:instance.__instanceName; + public static addTransaction(clazz:any,methodName:any){ + let name:string = clazz.name; //数组 if(Array.isArray(methodName)){ for(let n of methodName){ let expr:string = '^' + name + '.' + n + '$'; - AopFactory.addExpression('TransactionAdvice',this.pointcutId,expr); + AopFactory.addExpression(this.aspectName+ '.' +this.pointcutId,expr); } }else{ let expr:string = '^' + name + '.' + methodName + '$'; - AopFactory.addExpression('TransactionAdvice',this.pointcutId,expr); + AopFactory.addExpression(this.aspectName+ '.' +this.pointcutId,expr); } } @@ -193,7 +211,7 @@ class TransactionManager{ } /** - * 获取connection + * 获取当前事务的connection */ public static getConnection(id?:number){ if(!id){ @@ -241,35 +259,34 @@ class TransactionManager{ */ private static initAdvice(){ AopFactory.registPointcut({ - className:'TransactionAdvice', + class:TransactionAdvice, id:this.pointcutId }); - AopFactory.registAdvice({ - pointcutId:this.pointcutId, - type:'before', - method:'before', - className:'TransactionAdvice' - }); + // AopFactory.registAdvice({ + // pointcutId:this.pointcutId, + // type:'before', + // method:'before', + // className:'TransactionAdvice' + // }); - AopFactory.registAdvice({ - pointcutId:this.pointcutId, - type:'after-return', - method:'afterReturn', - className:'TransactionAdvice' - }); + // AopFactory.registAdvice({ + // pointcutId:this.pointcutId, + // type:'after-return', + // method:'afterReturn', + // className:'TransactionAdvice' + // }); - AopFactory.registAdvice({ - pointcutId:this.pointcutId, - type:'after-throw', - method:'afterThrow', - className:'TransactionAdvice' - }); + // AopFactory.registAdvice({ + // pointcutId:this.pointcutId, + // type:'after-throw', + // method:'afterThrow', + // className:'TransactionAdvice' + // }); - AopFactory.registAspect('TransactionAdvice'); + AopFactory.registAspect(TransactionAdvice); //添加Aspect InstanceFactory.addInstance({ - name:this.aspectName, class:TransactionAdvice, singleton:true }); diff --git a/core/locales/noomitip.ts b/core/locales/noomitip.ts index e9e8911cdf3b08ab73317a521f85e02f70858f19..fe8bba8d86fdf6aaee18e2d54899b476e4c63e47 100644 --- a/core/locales/noomitip.ts +++ b/core/locales/noomitip.ts @@ -16,6 +16,7 @@ var NoomiErrorTip ={ "1004":"模块路径 '${0}' 不存在", "1010":"实例方法 '${0}' 不存在", "1011":"实例装饰器参数错误", + "1012":"实例'${0}'的'${0}'属性注入类型错误", "2000":"aop配置文件错误,请参阅官方文档!", "2001":"pointcut的expressions参数配置错误", @@ -38,6 +39,11 @@ var NoomiErrorTip ={ "2700":"security文件配置错误,请参阅官方文档!", "2800":"数据源文件配置错误,请参阅官方文档!", + "2801":"数据源connect_manager配置错误", + + "2810":"事务transation实例配置错误", + + "2900":"logger文件配置错误,请参阅官方文档", "3002":"存入值超过缓存最大值", "3010":"键已存在,不能设置为object", @@ -83,6 +89,8 @@ var NoomiErrorTip ={ "2800":"Error in data source configuration file,Please read the official documentation!", + "2900": "logger file path configuration error, please refer to the official document", + "3002":"Attempt to allocate Buffer larger than maximum size", "3010":"key already exists,it cannot be defined as object", "3011":"need value" @@ -113,7 +121,9 @@ var NoomiTip = { "0119":"检测并执行启动钩子...", "0120":"启动钩子执行结束!", "0121":'Http服务器正在运行,监听端口 ${0}', - "0122":'Https服务器正在运行,监听端口 ${0}' + "0122":'Https服务器正在运行,监听端口 ${0}', + "0123":'NoomiLogger初始化', + "0124":'NoomiLogger初始化完成' }, en:{ "0100":"Noomi is booting ...", @@ -138,7 +148,9 @@ var NoomiTip = { "0119":"check and execute launch hooks ...", "0120":"launch hooks execution finished!", "0121":'Http Server is running,listening port ${0}', - "0122":'Https Server is running,listening port ${0}' + "0122":'Https Server is running,listening port ${0}', + "0123": 'noomilogger initialization', + "0124": 'noomilogger initialization completed' } } diff --git a/core/main/aopfactory.ts b/core/main/aopfactory.ts index 6feb611aec69d52410e93bc621d28a60a2762597..0bba735186e4e66a663a2103d54677e0120ce2a5 100644 --- a/core/main/aopfactory.ts +++ b/core/main/aopfactory.ts @@ -9,15 +9,13 @@ import { Util } from "../tools/util"; */ interface IAopAdvice{ /** - * 切点 + * 切点类名的引用 */ - pointcutId?:string; - + class?:any; /** - * 类名 + * 切点名 */ - className?:string; - + pointcutId:string; /** * 通知类型 (before,after,after-return,after-throw,around) */ @@ -33,9 +31,9 @@ interface IAopAdvice{ */ interface IAopAspect{ /** - * 实例名 + * 切面类的引用 */ - instance?:string; + class:any; /** * 切点数组 */ @@ -51,9 +49,9 @@ interface IAopAspect{ */ interface IPointcut{ /** - * 类名 + * 切点对应的类的引用 */ - className:string; + class:any; /** * 切点id */ @@ -84,9 +82,9 @@ class AopPointcut{ id:string; /** - * 实例名 + * 切点对应类的引用 */ - instanceName:string; + class:any; /** * 表达式数组(正则表达式) @@ -101,12 +99,12 @@ class AopPointcut{ /** * 构造器 * @param id 切点id(实例内唯一) - * @param instanceName 实例名 + * @param clazz 类的引用 * @param expressions 该切点对应的表达式数组,表达式为正则表达式串 */ - constructor(id:string,instanceName:string,expressions:Array){ + constructor(id:string,clazz:any,expressions:Array){ this.id = id; - this.instanceName = instanceName; + this.class = clazz; if(expressions){ this.addExpression(expressions); } @@ -160,35 +158,35 @@ class AopPointcut{ class AopFactory{ /** * 切点map,用于存储所有切点 - * key:切面实例名 + '.' + 切点名 + * key:切面类名 + '.' + 切点名 */ private static pointcuts:Map = new Map(); /** - * 已代理方法map,键为instanctName.methodName,避免重复代理 + * 已代理方法map,键为className.methodName,避免重复代理 * @since 0.4.4 */ static proxyMethodMap:Map = new Map(); /** - * 注册切面map,键为className,值为 + * 注册切面map,键为切面类的引用,值为 * { * isAspect:true, //避免用了pointcut,但是未使用Aspect注解 * pointCutId1:{expressions:Array,advices:{type:类型,method:方法名}}, * ... * } */ - private static registAspectMap:Map = new Map(); + private static registAspectMap:Map = new Map(); /** * 注册切面 - * @param className 切面类名 + * @param className 切面类的引用 * @since 1.0.0 */ - public static registAspect(className:string){ - if(!this.registAspectMap.has(className)){ + public static registAspect(clazz:any){ + if(!this.registAspectMap.has(clazz)){ return; } - this.registAspectMap.get(className).isAspect = true; + this.registAspectMap.get(clazz).isAspect = true; } /** * 注册切点 @@ -196,7 +194,7 @@ class AopFactory{ * @since 1.0.0 */ public static registPointcut(cfg:IPointcut){ - let pc = this.getRegistPointcut(cfg.className,cfg.id,true); + let pc = this.getRegistPointcut(cfg.class,cfg.id,true); if(cfg.expressions){ pc.expressions = pc.expressions.concat(cfg.expressions); } @@ -208,35 +206,35 @@ class AopFactory{ * @since 1.0.0 */ public static registAdvice(cfg:IAopAdvice){ - if(!this.registAspectMap.has(cfg.className)){ + if(!this.registAspectMap.has(cfg.class)){ return; } - let pc = this.registAspectMap.get(cfg.className)[cfg.pointcutId]; + let pc = this.registAspectMap.get(cfg.class)[cfg.pointcutId]; if(!pc){ return; } - delete cfg.className; + delete cfg.class; pc.advices.push(cfg); } /** * 从registAspectMap中获取注册的pointcut配置 - * @param className 类名 + * @param clazz 切点对应切面类的应用 * @param pointcutId 切点id * @param create 如果不存在,是否创建,如果为true,则创建,默认false * @returns pointcut配置项 * @since 1.0.0 */ - private static getRegistPointcut(className:string,pointcutId:string,create?:boolean):any{ + private static getRegistPointcut(clazz:any,pointcutId:string,create?:boolean):any{ let pc; - if(this.registAspectMap.has(className)){ - let obj = this.registAspectMap.get(className); + if(this.registAspectMap.has(clazz)){ + let obj = this.registAspectMap.get(clazz); pc = obj[pointcutId]; }else if(create){ - this.registAspectMap.set(className,{}); + this.registAspectMap.set(clazz,{}); } if(!pc && create){ //新建pointcut配置项 - let obj = this.registAspectMap.get(className); + let obj = this.registAspectMap.get(clazz); pc = { advices:[], expressions:[] @@ -248,25 +246,27 @@ class AopFactory{ /** * 处理实例切面 * 把注册的切面添加到切面列表 - * @param instanceName 实例名 - * @param className 类名 + * @param clazz 切面类的引用地址 * @since 1.0.0 */ - public static handleInstanceAspect(instanceName:string,className:string){ - if(!this.registAspectMap.has(className)){ + public static handleInstanceAspect(clazz:any){ + if(!this.registAspectMap.has(clazz)){ return; } - let cfg = this.registAspectMap.get(className); + let cfg = this.registAspectMap.get(clazz); if(!cfg.isAspect){ //非aspect,不处理 return; } + //是切面类,原型链上面添加信息 + // InstanceFactory.getInstanceCfg(instanceName).class.prototype.__isAspect = true; + clazz.prototype.__isAspect = true; delete cfg.isAspect; Object.keys(cfg).forEach(item=>{ let o = cfg[item]; //新建pointcut - let pc = new AopPointcut(item,instanceName,o.expressions); + let pc = new AopPointcut(item,clazz,o.expressions); //加入切点集 - this.pointcuts.set(instanceName + '.' + item,pc); + this.pointcuts.set(clazz.name + '.' + item,pc); //为切点添加advice o.advices.forEach(item1=>{ //添加advice @@ -274,16 +274,15 @@ class AopFactory{ }); }); //删除已处理的class - this.registAspectMap.delete(className); + this.registAspectMap.delete(clazz); } /** * 为切点添加表达式 - * @param className 切点类名 * @param pointcutId 切点id * @param expression 表达式或数组 */ - public static addExpression(className:string,pointcutId:string,expression:string|Array){ + public static addExpression(pointcutId:string,expression:string|Array){ let pc = this.pointcuts.get(pointcutId); if(!pc){ return; @@ -302,50 +301,98 @@ class AopFactory{ //遍历pointcut let pc:AopPointcut; for(let ins of InstanceFactory.getFactory()){ - this.proxyOne(ins[0]); + //代理工厂中所有的单例 + if(InstanceFactory.getInstanceCfg(ins).singleton){ + this.proxyOne(ins[0]); + } } } /** * 为某个类设置代理 - * @param instanceName 实例名 - * @param clazz 类 + * @param clazz 类的引用 */ - public static proxyOne(instanceName:string){ + // public static proxyOne(instanceName:string){ + // if(!this.pointcuts || this.pointcuts.size === 0){ + // return; + // } + // const clazz = InstanceFactory.getInstanceCfg(instanceName).class; + // if(clazz.prototype.__isAspect){ + // return ; + // } + // //遍历pointcut + // let pc:AopPointcut; + // for(pc of this.pointcuts.values()){ + // let reg:RegExp; + // //遍历expression + // for(reg of pc.expressions){ + // Object.getOwnPropertyNames(clazz.prototype).forEach(key=>{ + // //给方法设置代理,constructor 不需要代理 + // if(key === 'constructor' || typeof clazz.prototype[key] !== 'function'){ + // return; + // } + // let method:string = clazz.name + '.' + key; + // // let method:string = clazz.prototype.__instanceName + '.' + key; + // // let method:string = instanceName + '.' + key; + // if(reg.test(method)){ + // if(this.proxyMethodMap.has(method)){ + // let arr = this.proxyMethodMap.get(method); + // //不重复代理,保存该实例需要被代理的所有切点信息 + // if(!arr.includes(pc)){ + // arr.push(pc); + // } + // }else{ + // //首次需要代理方法,保存代理后的方法地址 + // clazz.prototype[key] = AopProxy.invoke(instanceName,key); + // //设置方法对应pointcut数组 + // this.proxyMethodMap.set(method,[pc]); + // } + // } + // }); + // } + // } + // } + //=--修改--个人觉得优先最外层遍历实例类的属性=== + /** + * 为某个类设置代理 + * @param clazz 类的引用 + * @returns + */ + public static proxyOne(clazz:any){ if(!this.pointcuts || this.pointcuts.size === 0){ return; } - const clazz = InstanceFactory.getInstanceCfg(instanceName).class; - //遍历pointcut - let pc:AopPointcut; - for(pc of this.pointcuts.values()){ - let reg:RegExp; - //遍历expression - for(reg of pc.expressions){ - Object.getOwnPropertyNames(clazz.prototype).forEach(key=>{ - //给方法设置代理,constructor 不需要代理 - if(key === 'constructor' || typeof clazz.prototype[key] !== 'function'){ - return; - } - let method:string = clazz.name + '.' + key; + //切点类不代理自己 + if(clazz.prototype.__isAspect){ + return; + } + Object.getOwnPropertyNames(clazz.prototype).forEach((key)=>{ + if(key === 'constructor' || typeof clazz.prototype[key] != 'function'){ + return ; + } + let method:string = clazz.name + '.' +key; + let pc:AopPointcut; + for(pc of this.pointcuts.values()){ + let reg:RegExp; + for(reg of pc.expressions){ if(reg.test(method)){ - if(this.proxyMethodMap.has(method)){ - let arr = this.proxyMethodMap.get(method); - //不重复代理 - if(!arr.includes(pc)){ - arr.push(pc); - } - }else{ - //首次需要代理方法 - clazz.prototype[key] = AopProxy.invoke(instanceName,key); - //设置方法对应pointcut数组 + //添加代理信息,键名classname.methodName + if(!this.proxyMethodMap.has(method)){ this.proxyMethodMap.set(method,[pc]); + //首次代理,修改代理后的函数引用地址 + clazz.prototype[key] = AopProxy.invoke(clazz,key); + }else{ + //添加当前类需要代理的所有切点信息 + let arr = this.proxyMethodMap.get(method); + arr.push(pc); } + break; } - }); + } } - } + }) } + //======== /** * 根据id获取切点 @@ -358,11 +405,11 @@ class AopFactory{ /** * 清理实例aop代理 - * @param instanceName 实例名 + * @param clazz 类的引用 */ - public static clearProxy(instanceName:string){ + public static clearProxy(clazz:any){ for(let k of this.proxyMethodMap.keys()){ - if(k.startsWith(instanceName + '.')){ + if(k.startsWith(clazz + '.')){ this.proxyMethodMap.delete(k); } } @@ -370,7 +417,7 @@ class AopFactory{ /** * 获取advices - * @param instanceName 实例名 + * @param clazz 类的引用 * @param methodName 方法名 * @return { * before:[{instance:切面实例,method:切面方法},...] @@ -379,8 +426,8 @@ class AopFactory{ * throw:[{instance:切面实例,method:切面方法},...] * } */ - public static getAdvices(className:string,methodName:string):object{ - const pointcuts:AopPointcut[] = this.proxyMethodMap.get(className + '.' + methodName); + public static getAdvices(clazz:any,methodName:string):object{ + const pointcuts:AopPointcut[] = this.proxyMethodMap.get(clazz.name + '.' + methodName); if(pointcuts.length === 0){ return null; } @@ -400,7 +447,7 @@ class AopFactory{ continue; } pointcut.advices.forEach(item=>{ - let ins:any = InstanceFactory.getInstance(pointcut.instanceName); + let ins:any = InstanceFactory.getInstance(pointcut.class); switch(item.type){ case 'before': diff --git a/core/main/aopproxy.ts b/core/main/aopproxy.ts index fe4d2176f34da70e28b462cb3f2db694ec0deb08..4d4a6870c183b8d988aa08dabd04996977f9a4d1 100644 --- a/core/main/aopproxy.ts +++ b/core/main/aopproxy.ts @@ -16,12 +16,12 @@ class AopProxy{ * @param func 执行函数 * @param instance 实例 */ - static invoke(instanceName:string,methodName:string):any{ + static invoke(clazz:any,methodName:string):any{ const util = App.util; - const instance = InstanceFactory.getInstance(instanceName); + const instance = InstanceFactory.getInstance(clazz); const func = instance[methodName]; - const clazz = InstanceFactory.getInstanceCfg(instanceName).class; + // const clazztmp = InstanceFactory.getInstanceCfg(clazz).class; /** * 异步方法 */ @@ -30,7 +30,8 @@ class AopProxy{ //advices获取 let advices:any; if(AopFactory){ - advices = AopFactory.getAdvices(clazz.name,methodName); + advices = AopFactory.getAdvices(clazz,methodName); + // advices = AopFactory.getAdvices(clazz.prototype.__instanceName,methodName); } let params:Array = []; for(let p of arguments){ @@ -39,7 +40,7 @@ class AopProxy{ //参数1为实例名,2是方法名,3是被代理方法自带参数(数组) let aopParams:Array = [{ - instanceName:instanceName, + className:clazz.name, methodName:methodName, params:params }]; @@ -102,7 +103,8 @@ class AopProxy{ //advices获取 let advices:any; if(AopFactory){ - advices = AopFactory.getAdvices(clazz.name,methodName); + advices = AopFactory.getAdvices(clazz,methodName); + // advices = AopFactory.getAdvices(clazz.prototype.__instanceName,methodName); } let params:Array = []; for(let p of arguments){ @@ -110,7 +112,7 @@ class AopProxy{ } //参数1为实例名,2是方法名,3是被代理方法自带参数(数组) let aopParams:Array = [{ - instanceName:instanceName, + className:clazz.name, methodName:methodName, params:params }]; diff --git a/core/main/cpufactory.ts b/core/main/cpufactory.ts new file mode 100644 index 0000000000000000000000000000000000000000..83a3fa84f973ab5f49cc770cd5f9f978eee244b3 --- /dev/null +++ b/core/main/cpufactory.ts @@ -0,0 +1,81 @@ +import { App } from "../tools/application"; +import { RequestQueue } from "../web/requestqueue"; + +export class CpuFactory{ + /** + * setInterval对象 + */ + private static iterval:any; + /** + * 上一次CPU信息 + */ + private static oldcpu:any; + /** + * 记录requestQuene.quene连续为空的秒数,不连续置0 + */ + public static quenelen:number = 0; + /** + * 创建Interval对象 + * @returns + */ + public static openInterval(){ + if(this.iterval){ + return ; + } + this.oldcpu = this.getCpu(); + this.iterval = setInterval(this.getCpuUseRate,1000); + } + /** + * 关闭Interval对象 + */ + public static closeInterval(){ + if(this.iterval){ + clearInterval(this.iterval) + this.iterval = null; + } + } + /** + * 30秒服务器没请求关闭定时器 + * 获取CPU使用率,更改RequestQuene中的canHandle + */ + public static getCpuUseRate(){ + let now = CpuFactory.getCpu(); + let idle = now.idle - CpuFactory.oldcpu.idle; + let total = now.total - CpuFactory.oldcpu.total; + let rate = 1 - idle/total; + CpuFactory.oldcpu = now; + // console.log("cpu rate",rate,'----',CpuFactory.oldcpu); + CpuFactory.quenelen = RequestQueue.queue.length === 0 ? CpuFactory.quenelen+1 : 0; + if(rate >0.75){ + RequestQueue.setCanHandle(false); + } + else { + RequestQueue.setCanHandle(true) + if(CpuFactory.quenelen === 30){ + CpuFactory.quenelen = 0; + CpuFactory.closeInterval(); + } + } + } + /** + * 获取cpu 信息 + * @returns + */ + public static getCpu(){ + let cpus:Array = App.os.cpus(); + let idle:number = 0; + let total:number = 0; + let item:any; + for(let i=0;i 0) { - cfg.properties.forEach(function (item) { - _this.addInject(insObj.instance, item.name, item.ref); - }); - } - return insObj.instance; - } - }; - /** - * 为实例添加注入 - * @param instance 实例类 - * @param propName 属性名 - * @param injectName 注入的实例名 - */ - InstanceFactory.addInject = function (instance, propName, injectName) { - // 加入注入依赖 - var insName = instance.__instanceName; - if (!insName) { - return; - } - var ins = this.factory.get(insName); - if (!ins) { - return; - } - //加入注入列表 - this.injectList.push({ - instance: instance, - propName: propName, - injectName: injectName - }); - if (ins.singleton) { - var arr = this.injectMap.get(injectName) || []; - //如果不存在,则加入数组,当注入实例更新后,则需要更新注入 - if (!arr.find(function (item) { return item['insName'] === insName; })) { - arr.push({ insName: insName, propName: propName }); - this.injectMap.set(injectName, arr); - } - } - else { //加入属性列表 - var props = ins.properties || []; - if (!props.find(function (item) { return item.name === propName; })) { - props.push({ - name: propName, - ref: injectName - }); - } - ins.properties = props; - } - //添加到注入到初始化后操作 - this.addAfterInitOperation(this.finishInject, this); - }; - /** - * 完成注入操作 - */ - InstanceFactory.finishInject = function () { - for (var _i = 0, _a = this.injectList; _i < _a.length; _i++) { - var item = _a[_i]; - var instance = InstanceFactory.getInstance(item.injectName); - // 实例不存在 - if (!instance) { - throw new errorfactory_1.NoomiError('1001', item.injectName); - } - //注入到实例,单例才需要注入,否则在getInstance时生成 - var ins = this.factory.get(instance.__instanceName); - if (ins && ins.singleton) { - Reflect.set(item.instance, item.propName, instance); - } - } - //清空inject list - this.injectList = []; - }; - /** - * 获取实例 - * @param name 实例名 - * @param param 参数数组 - * @returns 实例化的对象或null - */ - InstanceFactory.getInstance = function (name, param) { - var _this = this; - var ins = this.factory.get(name); - if (!ins) { - return null; - } - if (ins.singleton) { - return ins.instance; - } - else { - var mdl = ins["class"]; - param = param || ins.params || []; - var instance_1 = Reflect.construct(mdl, param); - //注入属性 - if (ins.properties && ins.properties.length > 0) { - ins.properties.forEach(function (item) { - instance_1[item.name] = _this.getInstance(item.ref); - }); - } - return instance_1; - } - }; - /** - * 通过类获取实例 - * @param clazz 类 - * @param param 参数数组 - * @returns 实例 - */ - InstanceFactory.getInstanceByClass = function (clazz, param) { - return this.getInstance(clazz.prototype.__instanceName, param); - }; - /** - * 获取实例对象 - * @param name 实例名 - * @returns 实例对象 - */ - InstanceFactory.getInstanceObj = function (name) { - return this.factory.get(name); - }; - /** - * 执行实例的一个方法 - * @param instancee 实例名或实例对象 - * @param methodName 方法名 - * @param params 参数数组 - * @param func 方法(与methodName二选一) - * @returns 方法对应的结果 - */ - InstanceFactory.exec = function (instance, methodName, params, func) { - //实例名,需要得到实例对象 - var instanceName = ''; - if (instance && typeof instance === 'string') { - instanceName = instance; - instance = this.getInstance(instance); - } - //实例不存在 - if (!instance) { - throw new errorfactory_1.NoomiError("1001", instanceName); - } - func = func || instance[methodName]; - //方法不存在 - if (!func) { - throw new errorfactory_1.NoomiError("1010", methodName); - } - return func.apply(instance, params); - }; - /** - * @exclude - * 解析实例配置文件 - * @param path 文件路径 - */ - InstanceFactory.parseFile = function (path) { - //读取文件 - var jsonStr = application_1.App.fs.readFileSync(path, 'utf-8'); - var json = null; - try { - json = application_1.App.JSON.parse(jsonStr); - } - catch (e) { - throw new errorfactory_1.NoomiError("1000") + '\n' + e; - } - this.handleJson(json); - }; - /** - * @exclude - * 处理配置对象 - * @param json 实例对象 - */ - InstanceFactory.handleJson = function (json) { - var _this = this; - if (json.module_path) { - if (Array.isArray(json.module_path)) { - json.module_path.forEach(function (item) { - if (!_this.mdlBasePath.includes(item)) { - //加入禁止访问路径 - staticresource_1.StaticResource.addPath(item.charAt(0) === '/' ? item : '/' + item); - _this.mdlBasePath.push(item); - } - }); - } - else if (typeof json.module_path === 'string') { - if (!this.mdlBasePath.includes(json.module_path)) { - var item = json.module_path; - //加入禁止访问路径 - staticresource_1.StaticResource.addPath(item === '/' ? item : '/' + item); - this.mdlBasePath.push(item); - } - } - } - //子文件 - if (Array.isArray(json.files)) { - json.files.forEach(function (item) { - _this.parseFile(util_1.Util.getAbsPath([application_1.App.configPath, item])); - }); - } - //实例数组 - if (Array.isArray(json.instances)) { - json.instances.forEach(function (item) { - if (typeof item === 'string') { //模块在路径中 - _this.addInstances(item); - } - else { - _this.addInstance(item); - } - }); - } - }; - /** - * 从文件添加实例 - * @param path 文件路径 - */ - InstanceFactory.addInstances = function (path) { - var basePath = process.cwd(); - var pathArr = path.split('/'); - var pa = [basePath]; - var handled = false; //是否已处理 - for (var i = 0; i < pathArr.length - 1; i++) { - var p = pathArr[i]; - if (p.indexOf('*') === -1 && p !== "") { - pa.push(p); - } - else if (p === '**') { //所有子孙目录 - handled = true; - if (i < pathArr.length - 2) { - throw new errorfactory_1.NoomiError('1000'); - } - handleDir(pa.join('/'), pathArr[pathArr.length - 1], true); - } - } - if (!handled) { - handleDir(pa.join('/'), pathArr[pathArr.length - 1]); - } - function handleDir(dirPath, fileExt, deep) { - var dir = application_1.App.fs.readdirSync(dirPath, { withFileTypes: true }); - var fn = fileExt; - var reg = util_1.Util.toReg(fn, 3); - //添加 file watcher - if (application_1.App.openWatcher) { - filewatcher_1.FileWatcher.addDir(dirPath, filewatcher_1.EWatcherType.DYNAMIC); - } - for (var _i = 0, dir_1 = dir; _i < dir_1.length; _i++) { - var dirent = dir_1[_i]; - if (dirent.isDirectory()) { - if (deep) { - handleDir(application_1.App.path.resolve(dirPath, dirent.name), fileExt, deep); - } - } - else if (dirent.isFile()) { - // @Instance注解方式文件,自动执行instance创建操作 - if (reg.test(dirent.name)) { - require(application_1.App.path.resolve(dirPath, dirent.name)); - } - } - } - } - }; - /** - * 获取instance工厂 - * @returns 实例工厂 - */ - InstanceFactory.getFactory = function () { - return this.factory; - }; - /** - * 更新与clazz相关的注入 - * @param clazz 类 - * @since 0.4.4 - */ - InstanceFactory.updInject = function (clazz) { - //更改的instance name - var insName = clazz.prototype.__instanceName; - if (!insName) { - return; - } - var arr = this.injectMap.get(insName); - if (!arr || arr.length === 0) { - return; - } - for (var _i = 0, arr_1 = arr; _i < arr_1.length; _i++) { - var cn = arr_1[_i]; - var c = this.getInstance(cn['insName']); - var ins = this.getInstance(insName); - if (c) { - c[cn['propName']] = ins; - } - } - }; - /** - * 添加初始化结束后操作 - * @param foo 待执行操作 - * @since 0.4.0 - */ - InstanceFactory.addAfterInitOperation = function (foo, thisObj) { - //已添加操作不再添加 - if (this.afterInitOperations.find(function (item) { return item['func'] === foo; })) { - return; - } - this.afterInitOperations.push({ - func: foo, - thisObj: thisObj - }); - }; - /** - * 执行初始化操作 - * @since 0.4.0 - */ - InstanceFactory.doAfterInitOperations = function () { - if (this.afterInitOperations.length === 0) { - return; - } - for (var _i = 0, _a = this.afterInitOperations; _i < _a.length; _i++) { - var foo = _a[_i]; - foo['func'].apply(foo['thisObj']); - } - //清理初始化后操作 - this.afterInitOperations = []; - }; - /** - * 实例工厂map,存放所有实例对象 - */ - InstanceFactory.factory = new Map(); - /** - * 模块基础路径数组,加载实例时从该路径加载 - */ - InstanceFactory.mdlBasePath = []; - /** - * 待注入对象数组 - */ - InstanceFactory.injectList = []; - /** - * 注入依赖map 键为注入类实例名,值为数组,数组元素为{className:类名,propName:属性名} - * @since 0.4.4 - */ - InstanceFactory.injectMap = new Map(); - /** - * 初始化后操作数组(实例工厂初始化结束后执行) {func:Function,thisObj:func this指向} - * @since 0.4.0 - */ - InstanceFactory.afterInitOperations = []; - return InstanceFactory; -}()); -exports.InstanceFactory = InstanceFactory; diff --git a/core/main/instancefactory.ts b/core/main/instancefactory.ts index c84cf0fac861957723b414a95a4ec283058365bc..0d58dd68b95aad3694d9af950d1e96f863f56e19 100644 --- a/core/main/instancefactory.ts +++ b/core/main/instancefactory.ts @@ -8,6 +8,7 @@ import { FilterFactory } from "../web/filterfactory"; import { RouteFactory } from "./route/routefactory"; import { WebAfterHandler } from "../web/webafterhandler"; import { AopFactory, AopPointcut } from "./aopfactory"; +import { LoggerFactory } from "../tools/logger/loggerfactory"; /** * 实例属性 @@ -18,9 +19,9 @@ export interface IInstanceProperty{ */ name:string; /** - * 引用实例名 + * 引用的类 */ - ref:string; + refClass:any; } /** @@ -28,19 +29,11 @@ export interface IInstanceProperty{ */ interface IInstanceCfg{ /** - * 实例名 + * 类的引用 */ - name:string; - /** - * 类名或类 - */ - class?:any; - /** - * 模块路径(相对noomi.ini配置的modulepath),与instance二选一 - */ - path?:string; + class:any; /** - * 实例与path 二选一 + * 实例 */ instance?:any; /** @@ -68,7 +61,8 @@ export interface IInstance{ /** * 类引用 */ - class?:any; + // class?:any; + // class:any /** * 单例标志 */ @@ -87,24 +81,15 @@ export interface IInstance{ * 注入参数对象,用于存储待注入对象的参数 */ export interface IInject{ - /** - * 待注入实例 - */ - instance?:any, - - /** - * 待注入类 - */ - clazz?:any, - + class:string; /** * 待注入属性名 */ propName:string, /** - * 注入实例名 + * 待注入类的引用 */ - injectName:string + injectClass:any; } /** @@ -116,9 +101,9 @@ export class InstanceFactory{ /** * 实例工厂map,存放所有实例对象 */ - public static factory:Map = new Map(); + public static factory:Map = new Map(); /** - * 注入依赖map 键为注入类名,值为数组,数组元素为{className:类名,propName:属性名} + * 注入依赖map 键为待注入类名,值为数组,数组元素为{injectClass:待注入类的引用,propName:属性名} * @since 0.4.4 */ private static injectMap:Map = new Map(); @@ -133,49 +118,62 @@ export class InstanceFactory{ /** * 添加单例到工厂 * @param cfg 实例配置对象 - * @param replace 替换之前的实例 * @returns undefined或添加的实例 */ public static addInstance(cfg:IInstanceCfg):any{ - cfg.class.prototype.__instanceName = cfg.name; - this.factory.set(cfg.name,{ - class:cfg.class, - singleton:cfg.singleton!==false - }); + if(this.factory.has(cfg.class)){ + throw new NoomiError("1002",cfg.class.name); + } + cfg.class.prototype.__instanceName = true; + this.factory.set(cfg.class,{ + instance:cfg.instance||undefined, + singleton:cfg.singleton || true, + params:cfg.params + }) + // this.factory.set(cfg.name,{ + // class:cfg.class, + // instance:cfg.instance || undefined, + // params:cfg.params, + // singleton:cfg.singleton!==false + // }); //依赖实例名的相关处理 - AopFactory.handleInstanceAspect(cfg.name,cfg.class.name); - RouteFactory.handleInstanceRoute(cfg.name,cfg.class.name); - TransactionManager.handleInstanceTranstraction(cfg.name,cfg.class.name); - FilterFactory.handleInstanceFilter(cfg.name,cfg.class.name); - WebAfterHandler.handleInstanceHandler(cfg.name,cfg.class.name); + LoggerFactory.handInstanceLogger(cfg.class) + AopFactory.handleInstanceAspect(cfg.class); + RouteFactory.handleInstanceRoute(cfg.class); + TransactionManager.handleInstanceTranstraction(cfg.class); + FilterFactory.handleInstanceFilter(cfg.class); + WebAfterHandler.handleInstanceHandler(cfg.class); //因为可能切面尚未添加到实例工厂,延迟aop代理 setImmediate(()=>{ - AopFactory.clearProxy(cfg.class.prototype.__instanceName); - AopFactory.proxyOne(cfg.class.prototype.__instanceName); + AopFactory.clearProxy(cfg.class); + AopFactory.proxyOne(cfg.class); }); } /** * 注入 - * @param targetClassName 目标类名 + * @param targetClass 待注入目标类引用 * @param propName 注入属性名 - * @param injectName 注入实例名 + * @param injectClass 注入类引用 */ - public static inject(targetClassName:any,propName:string,injectName:string){ - if(this.injectMap.has(targetClassName)){ - let arr = this.injectMap.get(targetClassName); + public static inject(targetClass:any,propName:string,injectClass:any){ + if(typeof injectClass != 'function'){ + throw new NoomiError('1012',[targetClass.name,propName]); + } + if(this.injectMap.has(targetClass)){ + let arr = this.injectMap.get(targetClass); //不重复注入,如果属性已注入,则修改注入名,否则增加到数组 let r = arr.find(item=>item['propName'] === propName); if(r){ - r['injectName'] = injectName; + r['injectClass'] = injectClass; }else{ - arr.push({propName:propName,injectName:injectName}); + arr.push({propName:propName,injectClass:injectClass}); } }else{ - this.injectMap.set(targetClassName,[{propName:propName,injectName:injectName}]); + this.injectMap.set(targetClass,[{propName:propName,injectClass:injectClass}]); } } @@ -185,42 +183,42 @@ export class InstanceFactory{ * @param param 参数数组 * @returns 实例化的对象或null */ - public static getInstance(name:string,param?:Array):any{ - let ins:IInstance = this.factory.get(name); + public static getInstance(clazz:any,param?:Array):any{ + let ins:IInstance = this.factory.get(clazz); if(!ins){ return null; } if(ins.singleton&&ins.instance){ - if(this.injectMap.has(ins.class.name)){ - //重新注入 - this.injectMap.get(ins.class.name).forEach((item)=>{ - ins.instance[item['propName']] = this.getInstance(item['injectName']); - }); - } + // if(this.injectMap.has(ins.class.name)){ + // //重新注入,根据类名信息找到需要注入的类 + // this.injectMap.get(ins.class.name).forEach((item)=>{ + // ins.instance[item['propName']] = this.getInstance(item['injectName']); + // }); + // } return ins.instance; }else{ - let mdl = ins.class; + let mdl = clazz; param = param || ins.params || []; let instance = Reflect.construct(mdl,param); - if(this.injectMap.has(ins.class.name)){ - this.injectMap.get(ins.class.name).forEach((item)=>{ - instance[item['propName']] = this.getInstance(item['injectName']); - }); - } - if(ins.singleton){ + if(ins.singleton){//A,B两个实例互相注入时会死循环 ins.instance = instance; } + if(this.injectMap.has(clazz)){ + this.injectMap.get(clazz).forEach((item)=>{ + instance[item['propName']] = this.getInstance(item['injectClass']); + }); + } return instance; } } /** * 获取实例配置对象 - * @param instanceName 实例名 + * @param instanceName 类的引用 * @returns 实例配置对象 */ - public static getInstanceCfg(instanceName:string):IInstance{ - return this.factory.get(instanceName); + public static getInstanceCfg(clazz:any):IInstance{ + return this.factory.get(clazz); } /** @@ -228,26 +226,26 @@ export class InstanceFactory{ * @param instancee 实例名或实例对象 * @param methodName 方法名 * @param params 参数数组 - * @param func 方法(与methodName二选一) + * @param func 方法(与methodName二选一),func优先 * @returns 方法对应的结果 */ - public static exec(instance:any,methodName:string,params:Array,func?:Function):any{ - //实例名,需要得到实例对象 - let instanceName = ''; - if(instance && typeof instance === 'string'){ - instanceName = instance; - instance = this.getInstance(instance); + public static exec(clazz:any,methodName:string,params:Array,func?:Function):any{ + let className = ""; + //是类的引用 + if(typeof clazz === "function"){ + className = clazz.name; + clazz = this.getInstance(clazz); } //实例不存在 - if(!instance){ - throw new NoomiError("1001",instanceName); + if(!clazz){ + throw new NoomiError("1001",className); } - func = func || instance[methodName]; + func = func || clazz[methodName]; //方法不存在 if(!func){ throw new NoomiError("1010",methodName); } - return func.apply(instance,params); + return func.apply(clazz,params); } /** @@ -282,11 +280,13 @@ export class InstanceFactory{ if(i{ - console.error(r); - });; + await LaunchHookManager.init(); + // if(typeof cfg === 'object'){ //配置为对象 + // LaunchHookManager.init(cfg); + // }else{ //配置为路径 + // LaunchHookManager.parseFile(Util.getAbsPath([basePath,cfg])); + // } + // await LaunchHookManager.run().catch(r=>{ + // console.error(r); + // });; console.log(msgTip["0120"]); - } - + } //如果web config 配置为only https,则不创建http server if(!WebConfig.httpsCfg || !WebConfig.httpsCfg['only_https']){ // http 服务器 this.server = App.http.createServer((req:IncomingMessage,res:ServerResponse)=>{ - // RequestQueue.add(new HttpRequest(req,res)); - RequestQueue.handleOne(new HttpRequest(req,res)); + RequestQueue.add(new HttpRequest(req,res)); + // RequestQueue.handleOne(new HttpRequest(req,res)); }).listen(this.port,(e)=>{ console.log(msgTip["0117"]); console.log(Util.compileString(msgTip["0121"],[this.port])); diff --git a/core/main/route/baseroute.ts b/core/main/route/baseroute.ts index e186b78f70f18725d7c3e5672c8686bc6cf1eea6..a58d990eb04fe492116db12213e7da3f8e5db634 100644 --- a/core/main/route/baseroute.ts +++ b/core/main/route/baseroute.ts @@ -79,7 +79,10 @@ class BaseRoute{ if(!ctType || !ctType.startsWith('application/json')){ let r = m.__handle(); if(r){ - throw new Error(JSON.stringify(r)); + let emsg ={}; + emsg['errmsg'] = r; + emsg['data'] = data; + throw new Error(JSON.stringify(emsg)); } } this.model = m; diff --git a/core/main/route/dist/routefactory.js b/core/main/route/dist/routefactory.js deleted file mode 100644 index f6ccabee0d12757119e48e73e24f5f6d78b790f2..0000000000000000000000000000000000000000 --- a/core/main/route/dist/routefactory.js +++ /dev/null @@ -1,481 +0,0 @@ -"use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -}; -exports.__esModule = true; -exports.ERouteResultType = exports.RouteFactory = void 0; -var instancefactory_1 = require("../instancefactory"); -var errorfactory_1 = require("../../tools/errorfactory"); -var util_1 = require("../../tools/util"); -var application_1 = require("../../tools/application"); -var routeerrorhandler_1 = require("./routeerrorhandler"); -/** - * 路由结果类型 - * @since 0.0.6 - */ -var ERouteResultType; -(function (ERouteResultType) { - /** - * 重定向 - */ - ERouteResultType["REDIRECT"] = "redirect"; - /** - * 路由链,和redirect不同,浏览器地址不会改变 - */ - ERouteResultType["CHAIN"] = "chain"; - /** - * 文件流,主要用于文件下载 - */ - ERouteResultType["STREAM"] = "stream"; - /** - * 什么都不做 - */ - ERouteResultType["NONE"] = "none"; - /** - * json数据,默认类型 - */ - ERouteResultType["JSON"] = "json"; -})(ERouteResultType || (ERouteResultType = {})); -exports.ERouteResultType = ERouteResultType; -/** - * 路由工厂类 - * 用于管理所有路由对象 - */ -var RouteFactory = /** @class */ (function () { - function RouteFactory() { - } - /** - * 添加路由 - * @param path 路由路径,支持通配符*,需要method支持 - * @param clazz 对应类 - * @param method 方法,path中包含*,则不设置 - * @param results 路由处理结果集 - */ - RouteFactory.addRoute = function (path, clazz, method, results) { - if (!path || !clazz) { - return; - } - if (results && results.length > 0) { - for (var _i = 0, results_1 = results; _i < results_1.length; _i++) { - var r = results_1[_i]; - if ((r.type === ERouteResultType.CHAIN || r.type === ERouteResultType.REDIRECT) - && (!r.url || typeof r.url !== 'string' || (r.url = r.url.trim()) === '')) { - throw new errorfactory_1.NoomiError("2101"); - } - } - } - if (method) { - method = method.trim(); - } - //没有通配符 - if (path.indexOf('*') === -1) { - this.staticRouteMap.set(path, { - instanceName: clazz.trim(), - method: method, - results: results - }); - } - else { //有通配符 - if (!this.dynaRouteArr.find(function (item) { return item.path === path; })) { - this.dynaRouteArr.push({ - path: path, - reg: util_1.Util.toReg(path, 3), - instanceName: clazz.trim(), - method: method, - results: results - }); - } - } - }; - /** - * 根据路径获取路由对象 - * @param path url路径 - * @returns 路由对象 - */ - RouteFactory.getRoute = function (path) { - var item; - var method; //方法名 - //下查找非通配符map - if (this.staticRouteMap.has(path)) { - item = this.staticRouteMap.get(path); - method = item.method; - } - else { - for (var i = 0; i < this.dynaRouteArr.length; i++) { - item = this.dynaRouteArr[i]; - //路径测试通过 - if (item.reg.test(path)) { - method = item.method; - if (!method) { - var index = item.path.indexOf("("); - //通配符处理 - if (index !== -1) { - //通配符方法 - method = path.substr(index); - } - } - break; - } - } - } - //找到匹配的则返回 - if (item && method) { - var instance = instancefactory_1.InstanceFactory.getInstance(item.instanceName); - if (instance && typeof instance[method] === 'function') { - return { instance: instance, method: method, results: item.results }; - } - } - return null; - }; - /** - * 路由方法执行 - * @param pathOrRoute 路径或路由 - * @param req request 对象 - * @param res response 对象 - * @param params 调用参数对象 - * @returns 0 正常 1异常 - */ - RouteFactory.handleRoute = function (route, req, res, params) { - return __awaiter(this, void 0, Promise, function () { - var nullArr, r, func, re; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - //尚未初始化 - if (!this.errorHandler) { - this.init({}); - } - //绑定path - if (!route.path && req) { - route.path = req.url; - } - //设置request - if (typeof route.instance.setRequest === 'function') { - route.instance.setRequest(req); - } - //设置response - if (typeof route.instance.setResponse === 'function') { - route.instance.setResponse(res); - } - if (!!params) return [3 /*break*/, 2]; - return [4 /*yield*/, req.init()]; - case 1: - params = _a.sent(); - _a.label = 2; - case 2: - //设置model - if (typeof route.instance.setModel === 'function') { - nullArr = void 0; - // if (route.instance.__getNullCheck) { //空属性 - // nullArr = route.instance.__getNullCheck(route.method); - // } - r = route.instance.setModel(params); - if (r !== null) { //setmodel异常 - throw r; - } - } - func = route.instance[route.method]; - if (typeof func !== 'function') { - throw new errorfactory_1.NoomiError("1010"); - } - return [4 /*yield*/, func.call(route.instance, route.instance || params)]; - case 3: - re = _a.sent(); - return [4 /*yield*/, this.handleResult(route, re)]; - case 4: return [2 /*return*/, _a.sent()]; - } - }); - }); - }; - /** - * 处理路由结果 - * @param route route对象 - * @param data 路由对应方法返回值 - */ - RouteFactory.handleResult = function (route, data) { - return __awaiter(this, void 0, Promise, function () { - var results, r, _i, results_2; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - results = route.results; - if (!(results && results.length > 0)) return [3 /*break*/, 6]; - if (!(results.length === 1)) return [3 /*break*/, 2]; - return [4 /*yield*/, this.handleOneResult(route, results[0], data)]; - case 1: return [2 /*return*/, _a.sent()]; - case 2: - r = void 0; - _i = 0, results_2 = results; - _a.label = 3; - case 3: - if (!(_i < results_2.length)) return [3 /*break*/, 6]; - r = results_2[_i]; - if (!(r.value === undefined || data && data == r.value)) return [3 /*break*/, 5]; - return [4 /*yield*/, this.handleOneResult(route, r, data)]; - case 4: return [2 /*return*/, _a.sent()]; - case 5: - _i++; - return [3 /*break*/, 3]; - case 6: return [4 /*yield*/, this.handleOneResult(route, {}, data)]; - case 7: - //默认回写json - return [2 /*return*/, _a.sent()]; - } - }); - }); - }; - /** - * 处理一个路由结果 - * @param route route对象 - * @param result route result - * @param data 路由执行结果 - * @returns cache数据对象或0 - */ - RouteFactory.handleOneResult = function (route, result, data) { - return __awaiter(this, void 0, Promise, function () { - /** - * 处理带参数的url,参数放在{}中 - * @param url 源url,以${propName}出现 - * @returns 处理后的url - */ - function handleParamUrl(instance, url) { - var reg = /\$\{.*?\}/g; - var r; - //处理带参数url - while ((r = reg.exec(url)) !== null) { - var pn = r[0].substring(2, r[0].length - 1); - url = url.replace(r[0], getValue(instance, pn)); - } - return url; - } - /** - * 获取属性值 - * @param instance 实例 - * @param pn 属性名 - * @returns 属性值 - */ - function getValue(instance, pn) { - if (instance[pn] !== undefined) { - return instance[pn]; - } - else if (instance.model && instance.model[pn] !== undefined) { - return instance.model[pn]; - } - } - var url, instance, res, ret, _a, pa, _i, _b, pn_1, v, pas, url1, params, _c, _d, pn_2, v, route1, pn, fn, mimeType; - return __generator(this, function (_e) { - switch (_e.label) { - case 0: - instance = route.instance; - res = route.instance.response; - ret = 0; - _a = result.type; - switch (_a) { - case ERouteResultType.REDIRECT: return [3 /*break*/, 1]; - case ERouteResultType.CHAIN: return [3 /*break*/, 2]; - case ERouteResultType.NONE: return [3 /*break*/, 4]; - case ERouteResultType.STREAM: return [3 /*break*/, 5]; - } - return [3 /*break*/, 6]; - case 1: - url = handleParamUrl(instance, result.url); - pa = []; - //参数属性 - if (result.params && Array.isArray(result.params) && result.params.length > 0) { - for (_i = 0, _b = result.params; _i < _b.length; _i++) { - pn_1 = _b[_i]; - v = getValue(instance, pn_1); - if (v !== undefined) { - pa.push(pn_1 + '=' + v); - } - } - } - pas = pa.join('&'); - if (pas !== '') { - if (url.indexOf('?') === -1) { - url += '?' + pas; - } - else { - url += '&' + pas; - } - } - res.redirect(url); - return [3 /*break*/, 7]; - case 2: - url = handleParamUrl(instance, result.url); - url1 = application_1.App.url.parse(url).pathname; - params = application_1.App.qs.parse(application_1.App.url.parse(url).query); - //参数处理 - if (result.params && Array.isArray(result.params) && result.params.length > 0) { - for (_c = 0, _d = result.params; _c < _d.length; _c++) { - pn_2 = _d[_c]; - v = getValue(instance, pn_2); - if (v !== undefined) { - params[pn_2] = v; - } - } - } - route1 = this.getRoute(url1); - if (route1 === null) { - throw new errorfactory_1.NoomiError("2103", url1); - } - //设置route path - route1.path = url1; - return [4 /*yield*/, this.handleRoute(route1, route.instance.request, res, params)]; - case 3: return [2 /*return*/, _e.sent()]; - case 4: //什么都不做 - return [3 /*break*/, 7]; - case 5: - pn = result.params[0]; - if (pn) { - fn = getValue(instance, pn); - if (fn) { - fn = util_1.Util.getAbsPath([fn]); - if (!application_1.App.fs.existsSync(fn)) { - throw new errorfactory_1.NoomiError('0050'); - } - res.writeFileToClient({ - data: fn - }); - } - } - return [3 /*break*/, 7]; - case 6: - mimeType = void 0; - //处理json对象 - if (typeof data === 'object') { - data = JSON.stringify(data); - mimeType = 'application/json'; - } - else { - mimeType = 'text/plain'; - } - ret = { - data: data, - mimeType: mimeType - }; - _e.label = 7; - case 7: return [2 /*return*/, ret]; - } - }); - }); - }; - /** - * 处理异常信息 - * @param res response 对象 - * @param e 异常 - */ - RouteFactory.handleException = function (res, e) { - var eh = instancefactory_1.InstanceFactory.getInstance(this.errorHandler); - if (eh) { - eh.handle(res, e); - } - else { - res.writeToClient({ - data: e - }); - } - }; - /** - * 初始化路由工厂 - * @param config 配置文件 - * @param ns 命名空间(上级路由路径) - */ - RouteFactory.init = function (config, ns) { - var _this = this; - //初始化errorHandler - if (!this.errorHandler) { - if (config.route_error_handler) { - this.errorHandler = config.route_error_handler; - } - else { - instancefactory_1.InstanceFactory.addInstance({ - name: 'noomi_route_error_handler', - instance: new routeerrorhandler_1.RouteErrorHandler(), - "class": routeerrorhandler_1.RouteErrorHandler - }); - this.errorHandler = 'noomi_route_error_handler'; - } - } - var ns1 = config.namespace ? config.namespace.trim() : undefined; - var pa = ns ? [ns] : []; - if (ns1) { - pa.push(ns1); - } - //处理本级路由 - if (Array.isArray(config.routes)) { - config.routes.forEach(function (item) { - pa.push(item.path); - //增加namespce前缀 - var p = util_1.Util.getAbsPath(pa, true); - _this.addRoute(p, item.instance_name, item.method, item.results); - }); - } - //处理子路径路由 - if (Array.isArray(config.files)) { - config.files.forEach(function (item) { - _this.parseFile(util_1.Util.getAbsPath([application_1.App.configPath, item]), ns); - }); - } - }; - /** - * 解析路由文件 - * @param path 文件路径 - * @param ns 命名空间,默认 / - */ - RouteFactory.parseFile = function (path, ns) { - //读取文件 - var json = null; - try { - var jsonStr = application_1.App.fs.readFileSync(path, 'utf-8'); - json = application_1.App.JSON.parse(jsonStr); - } - catch (e) { - throw new errorfactory_1.NoomiError("2100") + '\n' + e; - } - this.init(json, ns); - }; - /** - * 动态路由(带通配符)路由集合 - */ - RouteFactory.dynaRouteArr = new Array(); - /** - * 静态路由(不带通配符)路由集合 - */ - RouteFactory.staticRouteMap = new Map(); - return RouteFactory; -}()); -exports.RouteFactory = RouteFactory; diff --git a/core/main/route/routefactory.ts b/core/main/route/routefactory.ts index e022f9e5f0a5de0163de38655ab5c1ad883cd5e6..f2109c2d9a03b271ac24b1c5648dc4f16d62e6e5 100644 --- a/core/main/route/routefactory.ts +++ b/core/main/route/routefactory.ts @@ -5,6 +5,7 @@ import { NoomiError } from "../../tools/errorfactory"; import { Util } from "../../tools/util"; import { App } from "../../tools/application"; import { IWebCacheObj } from "../../web/webcache"; +import { setTimeout } from "timers"; /** @@ -12,10 +13,9 @@ import { IWebCacheObj } from "../../web/webcache"; */ interface IRouteClassCfg{ /** - * 类名 + * 类的引用 */ - className?:string; - + class?:any; /** * 命名空间 */ @@ -27,47 +27,32 @@ interface IRouteClassCfg{ paths?:any[]; } /** - * 路由配置类型 + * 路由注册配置类型 */ interface IRouteCfg{ /** - * 路由路径 - */ - path?:string; - - /** - * 类名 + * 路由类的引用 */ - className?:string; - + class:any; /** * 命名空间 */ namespace?:string; - /** - * 路由类 + * 路径 */ - clazz?:any; - - /** - * 路由正则表达式 - */ - reg?:RegExp; - /** - * 该路由对应的实例名 - */ - instanceName?:string; + path?:string; /** - * 该路由对应的实例方法 + * 路由方法名 */ - method?:string; + method:string; /** * 路由执行结果数组 */ results?:Array; } + /** * 路由结果类型 * @since 0.0.6 @@ -144,85 +129,170 @@ interface IRoute{ */ params?:object; } - +// interface IRouteTmp{ +// path:string; +// results?:Array +// } +// interface IRouterTmp{ +// namespace?:string; +// path?:string; +// } /** * 路由工厂类 * 用于管理所有路由对象 */ class RouteFactory{ /** - * 静态路由(不带通配符)路由集合 + * 路由对象Map */ static routeMap:Map = new Map(); /** * 注册路由map,添加到实例工厂时统一处理 */ - private static registRouteMap:Map = new Map(); + /** + * 可以尝试Map:存储{ + * 类引用:{0:namespace,methodName:{path,results}} + * } + */ + private static registRouteMap:Map = new Map(); + /** + * 已经使用Route装饰器装饰过的路由方法 + */ + private static registMethodMap:Map> = new Map(); + //--test + // private static tmpmethod = {};//object存储 + // public static tmprouteMap:Map = new Map(); + // private static registRouteMapTmp:Map = new Map(); + //用方法名作键,{results,path}作值可以避免一个map就实现过滤路由方法重复,但是当前类未加到实例工厂,会影响其他路由信息 + // public static registRouteTmp(cfg:IRouteCfg){ + // this.registRouteMapTmp.set(cfg.method,{path:cfg.path,results:cfg.results}); + // } + // public static registRouterTmp(cfg:IRouterTmp){ + // let namespace = ''; + // if(cfg.namespace){ + // } + // } /** - * 注册路由 - * @param cfg 路由配置 + * 注册路由信息 + * @param cfg 路由配置类型 + * @param isClass 是否是路由类注册 + * @returns */ - public static registRoute(cfg:IRouteCfg){ - if(!this.registRouteMap.has(cfg.className)){ - this.registRouteMap.set(cfg.className,{ + public static registRoute(cfg:IRouteCfg,isClass:boolean){ + if(!this.registRouteMap.has(cfg.class)){ + this.registRouteMap.set(cfg.class,{ paths:[] }) } - let obj = this.registRouteMap.get(cfg.className); + let obj = this.registRouteMap.get(cfg.class); //命名空间,针对Router注解器 if(cfg.namespace){ obj.namespace = cfg.namespace; + // this.tmpmethod['__namespace'] = cfg.namespace; } if(!cfg.path){ return; } - - if(cfg.clazz){ //router且存在通配符 + //route装饰过的方法 + if(cfg.method){ + this.registMethod(cfg); + } + if(isClass){ //router且存在通配符 if(cfg.path.indexOf('*') !== -1){ let reg = Util.toReg(cfg.path,3); - for(let o of Object.getOwnPropertyNames(cfg.clazz.prototype)){ - if(o === 'constructor' || typeof cfg.clazz.prototype[o] !== 'function'){ + for(let o of Object.getOwnPropertyNames(cfg.class.prototype)){ + if(o === 'constructor' || typeof cfg.class.prototype[o] !== 'function'){ continue; } + if(this.registMethodMap.has(cfg.class)){ + let arr = this.registMethodMap.get(cfg.class); + if(arr.includes(o)){ + continue; + } + } if(reg.test(o)){ obj.paths.push({path:o,method:o}); } } + this.registMethodMap.delete(cfg.class); } }else{ obj.paths.push({path:cfg.path,method:cfg.method,results:cfg.results}); } - } + //---test + // if(cfg.namespace){ + // this.tmpmethod['__namespace'] = cfg.namespace; + // } + // // this.tmpmethod['clazz'] = cfg.class; + // if(isClass){ + // let reg:RegExp = Util.toReg(cfg.path,3); + // for(let o of Object.getOwnPropertyNames(cfg.class.prototype)){ + // if(o === 'constructor'|| typeof cfg.class.prototype[o] !== 'function' ||this.tmpmethod[o]){ + // continue; + // } + // if(!reg.test(o)){ + // continue ; + // } + // this.tmpmethod[o] = {path:o} + // } + // return ; + // } + // this.tmpmethod[cfg.method] = {path:cfg.path,results:cfg.results} + } + /** + * 注册Route路由方法 + * @param cfg 路由配置项 + */ + private static registMethod(cfg:IRouteCfg){ + if(!this.registMethodMap.has(cfg.class)){ + this.registMethodMap.set(cfg.class,[cfg.method]) + } + else{ + let arr = this.registMethodMap.get(cfg.class); + arr.push(cfg.method); + } + } /** * 处理实例路由 * 把注册路由添加到路由对象中 * @param instanceName 实例名 * @param className 类名 */ - public static handleInstanceRoute(instanceName:string,className:string){ - if(!this.registRouteMap.has(className)){ + public static handleInstanceRoute(clazz:any){ + if(!this.registRouteMap.has(clazz)){ return; } - let cfg = this.registRouteMap.get(className); + let cfg = this.registRouteMap.get(clazz); let paths = cfg.paths; for(let p of paths){ - this.addRoute(Util.getUrlPath([cfg.namespace||'',p.path]),instanceName,p.method,p.results); + this.addRoute(Util.getUrlPath([cfg.namespace||'',p.path]),clazz,p.method,p.results); } //删除已处理的class - this.registRouteMap.delete(className); + this.registRouteMap.delete(clazz); + // delete this.registMethodMap; + //---test + // if(Object.keys(this.tmpmethod).length === 0){ + // return ; + // } + // let namespace:string = this.tmpmethod['__namespace']; + // delete this.tmpmethod['__namespace']; + // for(let md of Object.keys(this.tmpmethod)){ + // this.tmpaddRoute(Util.getUrlPath([namespace || '',this.tmpmethod[md].path]),clazz,md,this.tmpmethod[md].results); + // } + // this.tmpmethod = {}; } /** * 添加路由 * @param path 路由路径,支持通配符*,需要method支持 - * @param className 对应类 + * @param clazz 对应类的引用 * @param method 方法,path中包含*,则不设置 * @param results 路由处理结果集 */ - private static addRoute(path:string,className:string,method?:string,results?:Array){ + private static addRoute(path:string,clazz:any,method?:string,results?:Array){ //已存在则不再添加(因为通配符在非通配符后面) if(this.routeMap.has(path)){ return; @@ -239,11 +309,34 @@ class RouteFactory{ method = method.trim(); } this.routeMap.set(path,{ - instanceName:className, + class:clazz, method:method, results:results }); } + //--test + // private static tmpaddRoute(path:string,clazz:any,method?:string,results?:Array){ + // if(this.tmprouteMap.has(path)){ + // return; + // } + // if(results && results.length>0){ + // for(let r of results){ + // if((r.type === ERouteResultType.CHAIN || r.type === ERouteResultType.REDIRECT) + // && (!r.url || typeof r.url !=='string' || (r.url = r.url.trim())=== '')){ + // throw new NoomiError("2101"); + // } + // } + // } + // if(method){ + // method = method.trim(); + // } + // //--test + // this.tmprouteMap.set(path,{ + // class:clazz, + // method:method, + // results:results + // }); + // } /** * 根据路径获取路由对象 @@ -260,7 +353,7 @@ class RouteFactory{ } //找到匹配的则返回 if(item && method){ - let instance = InstanceFactory.getInstance(item.instanceName); + let instance = InstanceFactory.getInstance(item.class); if(instance && typeof instance[method] === 'function'){ return {instance:instance,method:method,results:item.results}; } @@ -278,9 +371,9 @@ class RouteFactory{ */ public static async handleRoute(route:IRoute,req:HttpRequest,res:HttpResponse,params?:object):Promise{ //绑定path - if(!route.path && req){ - route.path = req.url; - } + // if(!route.path && req){ + // route.path = req.url; + // } //设置request if(typeof route.instance.setRequest === 'function'){ @@ -309,6 +402,11 @@ class RouteFactory{ } let re = await func.call(route.instance,route.instance||params); + // console.log('fun call finish'); + // 重定向返回 + if(res.isRedirct){ + return ; + } return await this.handleResult(route,re); } @@ -372,7 +470,8 @@ class RouteFactory{ } } res.redirect(url); - return ERouteResultType.REDIRECT; + // return ERouteResultType.REDIRECT; + return {data:'redirect'}; case ERouteResultType.CHAIN: //路由器链 url = handleParamUrl(instance,result.url); let url1 = App.url.parse(url).pathname; diff --git a/core/tools/application.ts b/core/tools/application.ts index b07dbc374d7a3c69d29ed1c91efd2220e77adcc6..9526af1f46a95b51babe0c76a9bf98d381e639dd 100644 --- a/core/tools/application.ts +++ b/core/tools/application.ts @@ -76,4 +76,8 @@ export class App { * 应用是否部署为集群应用标志 */ static isCluster:boolean = false; + /** + * os 操作系统 + */ + static os = require('os'); } diff --git a/core/tools/decorator.ts b/core/tools/decorator.ts index 4e4e5e1f60908748e3935b5b9b5bd9ee201dabeb..fc594b798897565aaa25573ffd57ac9c7b57a110 100644 --- a/core/tools/decorator.ts +++ b/core/tools/decorator.ts @@ -7,33 +7,28 @@ import { FilterFactory } from '../web/filterfactory'; import { TransactionManager } from '../database/transactionmanager'; import { RouteFactory } from '../main/route/routefactory'; import { WebAfterHandler } from '../web/webafterhandler'; +import { LaunchHookManager } from './launchhookmanager'; /** * @exclude * instance装饰器,添加实例到实例工厂,装饰类 - * @param cfg:object|string 如果为string,则表示实例名 + * @param cfg:object|boolean 如果为boolena,则表示shifou单例 * name:string 实例名,必填 * singleton:bool 是否单例,默认true * params:object 参数 */ function Instance(cfg?:any){ return (target) =>{ - let instanceName:string; let singleton:boolean; let params:any; - if(typeof cfg === 'string'){ - instanceName = cfg; - singleton = true; + if(typeof cfg === 'boolean'){ + singleton = cfg; }else if(typeof cfg === 'object'){ - instanceName = cfg.name; singleton = cfg.singleton!==undefined?cfg.singleton:true; params = cfg.params; - }else{ //实例名默认为类名 - instanceName = target.name; } InstanceFactory.addInstance({ - name:instanceName, //实例名 class:target, params:params, singleton:singleton @@ -44,11 +39,11 @@ function Instance(cfg?:any){ /** * @exclude * IoC注入装饰器,装饰属性 - * @param instanceName:string 实例名,必填 + * @param injectClass:any 注入的类的引用,必填 */ -function Inject(instanceName:string){ +function Inject(injectClass:any){ return (target:any,propertyName:string)=>{ - InstanceFactory.inject(target.constructor.name,propertyName,instanceName); + InstanceFactory.inject(target.constructor,propertyName,injectClass); } } @@ -70,19 +65,17 @@ function Router(cfg?:any){ delete cfg.path; } } - cfg.className = target.name; - cfg.clazz = target; - RouteFactory.registRoute(cfg); + cfg.class = target; + RouteFactory.registRoute(cfg,true); } //未添加到实例工程,则进行添加 if(!target.prototype.__instanceName){ InstanceFactory.addInstance({ - name:target.name, class:target, singleton:false }); }else{ - RouteFactory.handleInstanceRoute(target.name,target.name); + RouteFactory.handleInstanceRoute(target); } } @@ -107,13 +100,13 @@ function Route(cfg:any){ if(typeof cfg === 'string'){ //直接配置路径,默认type json RouteFactory.registRoute({ path:cfg, - className:target.constructor.name, + class:target.constructor, method:propertyName - }); + },false); }else{ - cfg.className = target.constructor.name; + cfg.class = target.constructor; cfg.method = propertyName; - RouteFactory.registRoute(cfg); + RouteFactory.registRoute(cfg,false); } } } @@ -126,7 +119,7 @@ function Route(cfg:any){ function WebFilter(pattern?:any,order?:number){ return function(target:any,name:string){ FilterFactory.registFilter({ - className:target.constructor.name, + class:target.constructor, methodName:name, pattern:pattern, order:order @@ -143,7 +136,7 @@ function WebFilter(pattern?:any,order?:number){ function WebHandler(pattern?:any,order?:number){ return function(target:any,name:string){ WebAfterHandler.registHandler({ - className:target.constructor.name, + class:target.constructor, methodName:name, pattern:pattern, order:order @@ -157,16 +150,15 @@ function WebFilter(pattern?:any,order?:number){ */ function Aspect(){ return (target)=>{ - AopFactory.registAspect(target.name); + AopFactory.registAspect(target); if(!target.prototype.__instanceName){ //添加到实例工厂 InstanceFactory.addInstance({ - name:target.name, //实例名 class:target, singleton:true }); }else{ - AopFactory.handleInstanceAspect(target.name,target.name); + AopFactory.handleInstanceAspect(target); } } } @@ -184,7 +176,7 @@ function Pointcut(expressions?:any){ AopFactory.registPointcut({ id:name, expressions:expressions, - className:target.constructor.name + class:target.constructor }); } } @@ -199,7 +191,7 @@ function Before(pointcutId:string){ AopFactory.registAdvice({ pointcutId:pointcutId, type:'before', - className:target.constructor.name, + class:target.constructor, method:name }); } @@ -215,7 +207,7 @@ function After(pointcutId:string){ AopFactory.registAdvice({ pointcutId:pointcutId, type:'after', - className:target.constructor.name, + class:target.constructor, method:name }); } @@ -231,7 +223,7 @@ function Around(pointcutId:string){ AopFactory.registAdvice({ pointcutId:pointcutId, type:'around', - className:target.constructor.name, + class:target.constructor, method:name }); } @@ -246,7 +238,7 @@ function AfterReturn(pointcutId:string){ AopFactory.registAdvice({ pointcutId:pointcutId, type:'after-return', - className:target.constructor.name, + class:target.constructor, method:name }); } @@ -262,7 +254,7 @@ function AfterThrow(pointcutId:string){ AopFactory.registAdvice({ pointcutId:pointcutId, type:'after-throw', - className:target.constructor.name, + class:target.constructor, method:name }); } @@ -280,17 +272,16 @@ function Transactioner(methodReg?:any){ if(!methodReg){ methodReg = '*'; } - TransactionManager.registTransaction(target.name,methodReg); + TransactionManager.registTransaction(target,methodReg); if(!target.prototype.__instanceName){ //添加到实例工厂 InstanceFactory.addInstance({ - name:target.name, //实例名 class:target, singleton:true }); }else{ - TransactionManager.handleInstanceTranstraction(target.name,target.name); + TransactionManager.handleInstanceTranstraction(target); } } } @@ -351,4 +342,21 @@ function NullCheck(props:Array){ target.constructor.__setNullCheck(name,props); } } -export {Instance,Router,Route,WebFilter,WebHandler,Inject,Aspect,Pointcut,Before,After,Around,AfterReturn,AfterThrow,Transactioner,Transaction,DataModel,DataType,DataValidator,NullCheck} \ No newline at end of file +/** + * LaunchHook钩子配置order + * @param cfg + * @returns + */ +function LaunchHook(oder?:number){ + return (target:any,methodName:string)=>{ + LaunchHookManager.addLuanchHook({ + class:target.constructor, + method:methodName, + order:oder || 1000, + }) + + + } +} + +export {Instance,Router,Route,WebFilter,WebHandler,Inject,Aspect,Pointcut,Before,After,Around,AfterReturn,AfterThrow,Transactioner,Transaction,DataModel,DataType,DataValidator,NullCheck,LaunchHook} \ No newline at end of file diff --git a/core/tools/launchhookmanager.ts b/core/tools/launchhookmanager.ts index 09064424e9d6f06eb0798f792c58a62dc7dbd40b..55925165b2d5370a6ff16152737e18499f188977 100644 --- a/core/tools/launchhookmanager.ts +++ b/core/tools/launchhookmanager.ts @@ -9,9 +9,9 @@ import { InstanceFactory } from "../main/instancefactory"; */ interface IHookObj{ /** - * 实例名 + * 类的引用 */ - instance:string; + class:any; /** * 方法名 @@ -21,9 +21,14 @@ interface IHookObj{ /** * 参数数组 */ - params?:Array + // params?:Array + /** + * 钩子顺序 + */ + order?:number; } + /** * 启动后执行钩子对象管理器 * @since 0.3.5 @@ -32,38 +37,62 @@ export class LaunchHookManager{ /** * hook实例数组 */ - static hooks:Array = new Array(); + private static hooks:Array = new Array(); /** * 初始化 * @param json [{"instance":实例名,"method":方法名,params:参数数组}...] */ - static init(json:Array){ - this.hooks = json; + public static async init(){ + // this.hooks = json; + await this.run() } /** * 批量执行hook方法 */ - static async run(){ + private static async run(){ let h:IHookObj; for(h of this.hooks){ - await InstanceFactory.exec(h.instance,h.method,h.params); + // await InstanceFactory.exec(h.class,h.method,h.params); + try { + let tmp = Reflect.construct(h.class,[]); + // let tmp = new h.class() + await tmp[h.method].apply(); + } catch (error) { + console.error(error) + } + } } /** * 解析配置文件 * @param path launch hook配置文件路径 */ - static parseFile(path:string){ - //读取文件 - let json:any = null; - try{ - let jsonStr:string = App.fs.readFileSync(path,'utf-8'); - json = App.JSON.parse(jsonStr); - }catch(e){ - throw new NoomiError("2600") + '\n' + e; + // static parseFile(path:string){ + // //读取文件 + // let json:any = null; + // try{ + // let jsonStr:string = App.fs.readFileSync(path,'utf-8'); + // json = App.JSON.parse(jsonStr); + // }catch(e){ + // throw new NoomiError("2600") + '\n' + e; + // } + // this.init(json); + // } + public static addLuanchHook(cfg:IHookObj){ + let len:number = this.hooks.length; + if(len === 0){ + this.hooks.push(cfg); + return; + } + let i:number; + cfg.order = cfg.order || 1000;//默认值1000 + for(i=len-1;i>=0;i--){ + if(cfg.order >= this.hooks[i].order){ + break; + } } - this.init(json); + this.hooks.splice(i+1,0,cfg);//order升序排列 } } \ No newline at end of file diff --git a/core/tools/logger/logdecorator.ts b/core/tools/logger/logdecorator.ts new file mode 100644 index 0000000000000000000000000000000000000000..0fa6434e6c17afd871cc796732d0c718e8387280 --- /dev/null +++ b/core/tools/logger/logdecorator.ts @@ -0,0 +1,22 @@ +import { LoggerFactory } from "./loggerfactory" + + + + +export function Logger(patterns?:string){ + return (target)=>{ + LoggerFactory.registLogger({ + class:target, + patterns:patterns?patterns:"*" + + }) + } +} +export function Log(){ + return (target:any,methodName:string)=>{ + LoggerFactory.registLog({ + class:target.constructor, + methodName:methodName + }) + } +} \ No newline at end of file diff --git a/core/tools/logger/loggerfactory.ts b/core/tools/logger/loggerfactory.ts new file mode 100644 index 0000000000000000000000000000000000000000..f13175d35c430138304f2e2e916b9564ce015200 --- /dev/null +++ b/core/tools/logger/loggerfactory.ts @@ -0,0 +1,132 @@ +import { App, InstanceFactory ,NoomiError} from "../../../index"; +import { AopFactory } from "../../main/aopfactory"; +import { Util } from "../util"; +import { NoomiLog } from "./noomilog"; + +export interface ILog{ + class:any; + methodName:string; +} +export interface ILogger{ + class:any; + patterns?:string; +} +export class LoggerFactory{ + /** + * 注册Logger信息 + */ + private static registLoggerMap:Map> = new Map(); + private static LoggerAspect = NoomiLog.name; + private static LoggerPointcut = "__NOOMI_LOG_POINTCUT"; + /** + * 初始化 + */ + public static init(cfg:any){ + + this.initAdvice(); + NoomiLog.init(cfg.debug,cfg.fileLog); + } + public static parseFile(path:string){ + let json:any = null; + try{ + let jsonStr:string = App.fs.readFileSync(path,'utf-8'); + json = App.JSON.parse(jsonStr); + this.init(json); + }catch(e){ + throw new NoomiError("2900") + '\n' + e; + } + } + /** + * 初始化Logger相关通知 + */ + public static initAdvice(){ + AopFactory.registPointcut({ + class:NoomiLog, + id:this.LoggerPointcut, + expressions:[] + }); + AopFactory.registAspect(NoomiLog); + AopFactory.registAdvice({ + type:"before", + method:"before", + class:NoomiLog, + pointcutId:this.LoggerPointcut + }) + AopFactory.registAdvice({ + type:"after", + method:"after", + class:NoomiLog, + pointcutId:this.LoggerPointcut + }) + AopFactory.registAdvice({ + type:"around", + method:"around", + class:NoomiLog, + pointcutId:this.LoggerPointcut + }) + AopFactory.registAdvice({ + type:"after-return", + method:"afterReturn", + class:NoomiLog, + pointcutId:this.LoggerPointcut + }) + AopFactory.registAdvice({ + type:"after-throw", + method:"afterThrow", + class:NoomiLog, + pointcutId:this.LoggerPointcut + }) + InstanceFactory.addInstance({ + class:NoomiLog, + singleton:true + }) + } + /** + * 注册代理信息 + * @param cfg + * @returns + */ + public static registLog(cfg:ILog){ + if(this.registLoggerMap.has(cfg.class)){ + let tmpArr = this.registLoggerMap.get(cfg.class); + if(tmpArr.includes(cfg.methodName)){ + return ; + } + tmpArr.concat(cfg.methodName); + return ; + } + this.registLoggerMap.set(cfg.class,[cfg.methodName]); + + } + public static registLogger(cfg:ILogger){ + let ptns:string = cfg.patterns?cfg.patterns:"*" + let expr:RegExp = Util.toReg(ptns,3); + if(cfg.class){ + for(let item of Object.getOwnPropertyNames(cfg.class.prototype)){ + if(item === 'constructor' || typeof cfg.class.prototype[item] != 'function'){ + continue ; + } + if(expr.test(item)){ + this.registLog({class:cfg.class,methodName:item}) + } + } + } + } + /** + * 处理实例的logger + * @param instanceName + * @param className + * @returns + */ + public static handInstanceLogger(clazz:any){ + let tmpArr = this.registLoggerMap.get(clazz); + if(!tmpArr){ + return ; + } + for(let i=0;ikey:string let si:number = 0; if(ci){ //保留原size @@ -671,7 +673,8 @@ class MemoryCache{ //降序排序 delArr.sort((a,b)=>{ - return b.lru - a.lru; + // return b.lru - a.lru; + return a.lru -b.lru; }); //释放前n个 diff --git a/core/tools/securityfactory.ts b/core/tools/securityfactory.ts index 3e128a691e323c6ccde4cb03ea5d714335070e4f..aabff85633a230fa8ffa2c67c5fe5775b53281af 100644 --- a/core/tools/securityfactory.ts +++ b/core/tools/securityfactory.ts @@ -138,17 +138,17 @@ class SecurityFactory{ // instance:new SecurityFilter(), // class:SecurityFilter // }); - InstanceFactory.addInstance({ - name:'NoomiSecurityFilter', //filter实例名 - instance:new SecurityFilter(), - class:SecurityFilter - }); FilterFactory.registFilter({ - className:'NoomiSecurityFilter', + class:SecurityFilter,//filter类名 pattern:config['expressions'], + methodName:"do", order:1 }); + InstanceFactory.addInstance({ //filter实例名 + instance:new SecurityFilter(), + class:SecurityFilter + }); //创建cache this.cache = new NCache({ diff --git a/core/tools/types.ts b/core/tools/types.ts index 64562c936221ffbc03379062efe6c84e94a0fa85..6ec6e02ae99402351271d621cc5a7a4da1778558 100644 --- a/core/tools/types.ts +++ b/core/tools/types.ts @@ -44,9 +44,9 @@ */ export interface IFilterCfg{ /** - * 类名 + * 类的引用 */ - className?:string; + class:any; /** * 方法需要返回true/false,如果为false,则表示不再继续执行(过滤器链) @@ -69,9 +69,9 @@ */ export interface IFilter{ /** - * 实例名 + * 实例类的引用 */ - instance:string; + class:any; /** * 方法名 */ diff --git a/core/web/filter/modelhandler.ts b/core/web/filter/modelhandler.ts new file mode 100644 index 0000000000000000000000000000000000000000..75f17189f4f778232b0f98916e0bb904b0cc9e5f --- /dev/null +++ b/core/web/filter/modelhandler.ts @@ -0,0 +1,35 @@ +import { InstanceFactory } from "../../.."; +import { HttpRequest } from "../httprequest"; +import { HttpResponse } from "../httpresponse"; +import { WebAfterHandler } from "../webafterhandler"; + +export class ModelHandle{ + /** + * 默认后置处理 + * @param result + * @param req + * @param res + * @returns + */ + async do(result:any,req:HttpRequest,res:HttpResponse){ + if(result.errmsg){ + return {data:{success:false,data:result}} + } + return result; + } + public static async initModelHandler(){ + if(InstanceFactory.getInstance(this)){ + return ; + } + WebAfterHandler.registHandler({ + class:ModelHandle, + methodName:'do', + order:0, + pattern:[/^\/.*/] + }) + InstanceFactory.addInstance({ + class:this, + singleton:true + }) + } +} \ No newline at end of file diff --git a/core/web/filterfactory.ts b/core/web/filterfactory.ts index 74d4ce3d9c8e3e4a17f5d16c6701bb71b06821d3..38662df629d586c2ad1b7b6b1969a90f08dcb622 100644 --- a/core/web/filterfactory.ts +++ b/core/web/filterfactory.ts @@ -24,7 +24,7 @@ export class FilterFactory{ order:优先级 } */ - private static registFilterMap:Map = new Map(); + private static registFilterMap:Map = new Map(); /** * 注册过滤器 @@ -38,8 +38,8 @@ export class FilterFactory{ * @since 1.0.0 */ public static registFilter(cfg:IFilterCfg){ - let name = cfg.className; - delete cfg.className; + let name = cfg.class; + delete cfg.class; this.registFilterMap.set(name,cfg); } @@ -49,21 +49,24 @@ export class FilterFactory{ * @param className 类名 * @since 1.0.0 */ - public static handleInstanceFilter(instanceName:string,className:string){ - if(!this.registFilterMap.has(className)){ + public static handleInstanceFilter(clazz:any){ + if(!this.registFilterMap.has(clazz)){ return; } - const cfg = this.registFilterMap.get(className); + const cfg = this.registFilterMap.get(clazz); let ptns = []; if(!cfg.pattern){ ptns = [/^\/.*/]; }else if(!Array.isArray(cfg.pattern)){ //非数组 ptns = [cfg.pattern]; + }else{ + ptns = ptns.concat(cfg.pattern) } + //修改----上文 //查找重复过滤器类 let f:IFilter = this.filters.find(item=>{ - return item.instance === instanceName && item.method === cfg.methodName; + return item.class === clazz && item.method === cfg.methodName; }); //删除之前添加的过滤器 @@ -73,7 +76,7 @@ export class FilterFactory{ } //加入过滤器集合 this.filters.push({ - instance:instanceName, + class:clazz, method:cfg.methodName, patterns:ptns, order:cfg.order===undefined?10000:cfg.order @@ -82,6 +85,7 @@ export class FilterFactory{ this.filters.sort((a,b)=>{ return a.order - b.order; }); + this.registFilterMap.delete(clazz) } /** @@ -148,7 +152,7 @@ export class FilterFactory{ } for(let item of arr){ - let ins = InstanceFactory.getInstance(item.instance); + let ins = InstanceFactory.getInstance(item.class); if(!ins){ continue; } diff --git a/core/web/httpresponse.ts b/core/web/httpresponse.ts index d190342e86059b85959b499d7852105a0713e2e8..b526f68680146190b526d5c968ad8c84a0bbb1ca 100644 --- a/core/web/httpresponse.ts +++ b/core/web/httpresponse.ts @@ -3,6 +3,7 @@ import { HttpCookie } from "./httpcookie"; import { WebConfig } from "./webconfig"; import { App } from "../tools/application"; import { Stats } from "fs"; +import { ERouteResultType } from "../.."; /** * response回写配置项 @@ -64,7 +65,10 @@ export class HttpResponse extends ServerResponse{ * cookie */ cookie:HttpCookie = new HttpCookie(); - + /** + * 标记当前response是否重定向 + */ + isRedirct:boolean = false; /** * 初始化response对象 * @param req 源request对象 @@ -87,6 +91,9 @@ export class HttpResponse extends ServerResponse{ if(!(data instanceof Buffer)){ if(typeof data === 'object'){ data = JSON.stringify(data); + }//数字或boolean会报错 + else if(typeof data != 'string'){ + data = data +""; } } @@ -110,7 +117,9 @@ export class HttpResponse extends ServerResponse{ return; } + // this.srcRes.writeHead(status, {}).end(data,charset); this.srcRes.writeHead(status, {}).end(data,charset); + } /** @@ -207,6 +216,8 @@ export class HttpResponse extends ServerResponse{ } ); this.srcRes.end(); + this.isRedirct = true; + // return ERouteResultType.REDIRECT; } /** diff --git a/core/web/requestqueue.ts b/core/web/requestqueue.ts index 939fca9173fa4b0b7818793854a983cf9851d938..1f19b09885b32c899a5c120064a1ea6451563f5d 100644 --- a/core/web/requestqueue.ts +++ b/core/web/requestqueue.ts @@ -9,6 +9,9 @@ import { HttpResponse } from "./httpresponse"; import { Util } from "../tools/util"; import { WebCache, IWebCacheObj } from "./webcache"; import { WebAfterHandler } from "./webafterhandler"; +import { ModelHandle } from "./filter/modelhandler"; +import { CpuFactory } from "../main/cpufactory"; +import { NoomiError } from "../tools/errorfactory"; /** * @exclude @@ -32,14 +35,16 @@ class RequestQueue{ * @param res */ static add(req:HttpRequest){ + + if(this.queue.length === 0){ + CpuFactory.openInterval(); + } let timeout = WebConfig.get('request_timeout') || 0; this.queue.push({ req:req, expire:timeout>0?new Date().getTime() + timeout*1000:0 }); - if(this.canHandle){ - this.handle(); - } + this.handle(); } /** @@ -47,23 +52,24 @@ class RequestQueue{ */ static handle(){ //队列轮询 - if(this.queue.length === 0){ - return; - } //cpu超限,延迟1m执行队列 if(!this.canHandle){ - this.canHandle = true; + // this.canHandle = true; setTimeout(()=>{ RequestQueue.handle(); },1000); return; } - + let item:IRequestItem = this.queue.shift(); if(item.expire === 0 || item.expire > new Date().getTime()){ this.handleOne(item.req); } - this.handle(); + // if(this.queue.length === 0){ + // CpuFactory.closeInterval(); + // return; + // } + // this.handle(); } /** @@ -119,12 +125,21 @@ class RequestQueue{ try{ data = await RouteFactory.handleRoute(route,request,response); //重定向直接返回 - if(data === ERouteResultType.REDIRECT){ + if(response.isRedirct){ return; } + // if(data.data === ERouteResultType.REDIRECT){ + // return; + // } }catch(e){ //输出异常对象 - data = e; + //baseRoute.setModel throw出的是Error,其他是NoomiError + if(e instanceof NoomiError){ + console.error(e); + return ; + } + data = JSON.parse(e.message); + ModelHandle.initModelHandler(); console.error(e); } }else{ //静态资源 @@ -193,7 +208,8 @@ class RequestQueue{ }); }else{ //数据对象 response.writeToClient({ - data:data, + // data:data, + data:cData.data, charset:charset }); } diff --git a/core/web/staticresource.ts b/core/web/staticresource.ts index d356e4252f4da9e0f06ec9a1f5e306181227f165..5385c54a9c96acd6a0ca34b829b3a31fe7147298 100644 --- a/core/web/staticresource.ts +++ b/core/web/staticresource.ts @@ -51,6 +51,7 @@ class StaticResource{ //缓存数据对象 let cacheData; //状态码 + //这里的意义是? if(WebConfig.useServerCache){ //从缓存取,如果用浏览器缓存数据,则返回0,不再操作 let ro:number|object = await WebCache.load(request,response,path); if(ro !== undefined && typeof ro === 'object'){ diff --git a/core/web/webafterhandler.ts b/core/web/webafterhandler.ts index 0e79eb25df0705c7d9df3ea598a9274685b4abcd..906aae4df7012f12559b66e8d34c0e92cd3a6d83 100644 --- a/core/web/webafterhandler.ts +++ b/core/web/webafterhandler.ts @@ -20,7 +20,7 @@ class WebAfterHandler{ order:优先级 } */ - private static registHandlerMap:Map = new Map(); + private static registHandlerMap:Map = new Map(); /** * 注册过滤器 @@ -34,8 +34,8 @@ class WebAfterHandler{ * @since 1.0.0 */ public static registHandler(cfg:IFilterCfg){ - let name = cfg.className; - delete cfg.className; + let name = cfg.class; + delete cfg.class; this.registHandlerMap.set(name,cfg); } @@ -45,21 +45,23 @@ class WebAfterHandler{ * @param className 类名 * @since 1.0.0 */ - public static handleInstanceHandler(instanceName:string,className:string){ - if(!this.registHandlerMap.has(className)){ + public static handleInstanceHandler(clazz:any){ + if(!this.registHandlerMap.has(clazz)){ return; } - const cfg = this.registHandlerMap.get(className); + const cfg = this.registHandlerMap.get(clazz); let ptns = []; if(!cfg.pattern){ ptns = [/^\/.*/]; }else if(!Array.isArray(cfg.pattern)){ //非数组 ptns = [cfg.pattern]; + }else{ + ptns = ptns.concat(cfg.pattern); } //查找重复过滤器类 let f:IFilter = this.handlers.find(item=>{ - return item.instance === instanceName && item.method === cfg.methodName; + return item.class === clazz && item.method === cfg.methodName; }); //删除之前添加的过滤器 @@ -69,7 +71,7 @@ class WebAfterHandler{ } //加入过滤器集合 this.handlers.push({ - instance:instanceName, + class:clazz, method:cfg.methodName, patterns:ptns, order:cfg.order===undefined?10000:cfg.order @@ -114,7 +116,7 @@ class WebAfterHandler{ return result; } for(let item of arr){ - let ins = InstanceFactory.getInstance(item.instance); + let ins = InstanceFactory.getInstance(item.class); if(!ins){ continue; } diff --git a/index.js b/index.js index 8123a566a675481de4e080b47d1fb71e169de070..2e22f4cc97284d78a71fff423f918f3f6c4f57e8 100644 --- a/index.js +++ b/index.js @@ -16,38 +16,47 @@ __exportStar(require("./core/database/mssqlconnectionmanager"), exports); __exportStar(require("./core/database/mssqltransaction"), exports); __exportStar(require("./core/database/mysqlconnectionmanager"), exports); __exportStar(require("./core/database/mysqltransaction"), exports); +__exportStar(require("./core/database/noomitransaction"), exports); __exportStar(require("./core/database/oracleconnectionmanager"), exports); __exportStar(require("./core/database/oracletransaction"), exports); -__exportStar(require("./core/database/sequelizeconnectionmanager"), exports); -__exportStar(require("./core/database/sequelizetransaction"), exports); -__exportStar(require("./core/database/noomitransaction"), exports); +__exportStar(require("./core/database/relaenconnectionmanager"), exports); +__exportStar(require("./core/database/relaentransaction"), exports); __exportStar(require("./core/database/transactionadvice"), exports); __exportStar(require("./core/database/transactionmanager"), exports); __exportStar(require("./core/database/transactionproxy"), exports); +__exportStar(require("./core/database/typeormconnectionmanager"), exports); +__exportStar(require("./core/database/typeormtransaction"), exports); __exportStar(require("./core/web/filter/securityfilter"), exports); -__exportStar(require("./core/locales/msg_en"), exports); -__exportStar(require("./core/locales/msg_zh"), exports); -__exportStar(require("./core/main/aopfactory"), exports); -__exportStar(require("./core/main/aopproxy"), exports); -__exportStar(require("./core/tools/application"), exports); -__exportStar(require("./core/main/route/baseroute"), exports); -__exportStar(require("./core/tools/decorator"), exports); -__exportStar(require("./core/tools/errorfactory"), exports); __exportStar(require("./core/web/filterfactory"), exports); +__exportStar(require("./core/web/webafterhandler"), exports); __exportStar(require("./core/web/httpcookie"), exports); __exportStar(require("./core/web/httprequest"), exports); __exportStar(require("./core/web/httpresponse"), exports); +__exportStar(require("./core/web/requestqueue"), exports); +__exportStar(require("./core/web/sessionfactory"), exports); +__exportStar(require("./core/web/staticresource"), exports); +__exportStar(require("./core/web/webconfig"), exports); +__exportStar(require("./core/web/webcache"), exports); +__exportStar(require("./core/locales/noomitip"), exports); +__exportStar(require("./core/locales/noomimodeltip"), exports); +__exportStar(require("./core/main/aopfactory"), exports); +__exportStar(require("./core/main/aopproxy"), exports); __exportStar(require("./core/main/instancefactory"), exports); -__exportStar(require("./core/tools/ncache"), exports); __exportStar(require("./core/main/noomi"), exports); -__exportStar(require("./core/tools/pagefactory"), exports); -__exportStar(require("./core/tools/redisfactory"), exports); -__exportStar(require("./core/web/requestqueue"), exports); +__exportStar(require("./core/main/route/baseroute"), exports); __exportStar(require("./core/main/route/routefactory"), exports); __exportStar(require("./core/main/route/routeerrorhandler"), exports); +__exportStar(require("./core/tools/application"), exports); +__exportStar(require("./core/tools/decorator"), exports); +__exportStar(require("./core/tools/errorfactory"), exports); +__exportStar(require("./core/tools/filewatcher"), exports); +__exportStar(require("./core/tools/launchhookmanager"), exports); +__exportStar(require("./core/tools/model"), exports); +__exportStar(require("./core/tools/ncache"), exports); +__exportStar(require("./core/tools/pagefactory"), exports); +__exportStar(require("./core/tools/redisfactory"), exports); __exportStar(require("./core/tools/securityfactory"), exports); -__exportStar(require("./core/web/sessionfactory"), exports); -__exportStar(require("./core/web/staticresource"), exports); +__exportStar(require("./core/tools/threadlocal"), exports); +__exportStar(require("./core/tools/types"), exports); __exportStar(require("./core/tools/util"), exports); -__exportStar(require("./core/web/webcache"), exports); -__exportStar(require("./core/web/webconfig"), exports); +__exportStar(require("./core/tools/validator"), exports); diff --git "a/noomi \351\227\256\351\242\230\346\225\264\347\220\206(1).md" "b/noomi \351\227\256\351\242\230\346\225\264\347\220\206(1).md" deleted file mode 100644 index fb00df387680e1e9aca50ba1ca9a8fb81b7c5ded..0000000000000000000000000000000000000000 --- "a/noomi \351\227\256\351\242\230\346\225\264\347\220\206(1).md" +++ /dev/null @@ -1,12 +0,0 @@ -# noomi 问题整理 - - **《aop 和 route 配置文件方式要不要也框架内部自动将路由类添加到实例工厂呢?》** - -3. **热部署**没有效果。**《静态资源:在 handleStaticRes 方法中处理单个静态目录时,需要将 url 从:"\\\\static\\\\index.html" => "/static/index.html";动态资源监听的是 js。》** - -5. 纯配置文件方式实现**事务**不能使用,事务管理器中没有读取方法表达式。**《不支持》** - -6. **ncache** 中的clearByLRU()方法,随机获取10个元素的key 时,在迭代器使用下标?释放元素时,value 数组已排序,key 数组并未排序,但直接使用value 数组下标获取了key 数组项。 - -7. 在**model.ts** 中,实体类的属性名、类型、验证器使用map 来存储,但是在__initPropMap() 方法中将这个map 传给了Object.getOwnPropertyNames() 方法? 还有为什么一定要克隆一下这个map?解答:因为每个方法都会设置不同的字段null属性检查,如果不克隆后修改,则改变的是原来的对象,nullcheck会一直保留 - diff --git "a/noomi \351\227\256\351\242\230\346\225\264\347\220\206.md" "b/noomi \351\227\256\351\242\230\346\225\264\347\220\206.md" index 8e1f841f0e5664c57bf545f02eacf46640771f14..523fc6d5d592d900cbf1f28e0048628dbdfe390e 100644 --- "a/noomi \351\227\256\351\242\230\346\225\264\347\220\206.md" +++ "b/noomi \351\227\256\351\242\230\346\225\264\347\220\206.md" @@ -1,10 +1,13 @@ -# noomi 问题整理 - -1. 配置文件方式配置**路由**会使用绝对路径做键,配置不成功。 ok -2. **aop** 配置文件中的files(子文件列表)配置项没有被读取过。 ok -3. **热部署**没有效果。 ok -4. **Transactioner** 装饰器只能传字符串参数不能传数组参数。ok -5. 纯配置文件方式实现**事务**不能使用,事务管理器中没有读取方法表达式。 不提供 -6. **ncache** 中的clearByLRU()方法,随机获取10个元素的key 时,在迭代器使用下标?释放元素时,value 数组已排序,key 数组并未排序,但直接使用value 数组下标获取了key 数组项。 -7. 在**model.ts** 中,实体类的属性名、类型、验证器使用map 来存储,但是在__initPropMap() 方法中将这个map 传给了Object.getOwnPropertyNames() 方法? 还有为什么一定要克隆一下这个map? - +# noomi 问题整理 + +1. 配置文件方式配置**路由**会使用绝对路径做键,配置不成功。 ok +2. **aop** 配置文件中的files(子文件列表)配置项没有被读取过。 ok +3. **热部署**没有效果。 ok +4. **Transactioner** 装饰器只能传字符串参数不能传数组参数。ok +5. 纯配置文件方式实现**事务**不能使用,事务管理器中没有读取方法表达式。 不提供 +6. **ncache** 中的clearByLRU()方法,随机获取10个元素的key 时,在迭代器使用下标?释放元素时,value 数组已排序,key 数组并未排序,但直接使用value 数组下标获取了key 数组项。 +7. 在**model.ts** 中,实体类的属性名、类型、验证器使用map 来存储,但是在__initPropMap() 方法中将这个map 传给了Object.getOwnPropertyNames() 方法? 还有为什么一定要克隆一下这个map? +---问题 +instance相互注入会堆栈溢出,死循环 +aop代理完全不能用 +热部署,dao注入service service注入route ,dao service为单例时,热部署修改service会更新dao,service的修改,但是只修改dao时,失效 diff --git "a/noomi\344\277\256\346\224\271\350\256\260\345\275\225.md" "b/noomi\344\277\256\346\224\271\350\256\260\345\275\225.md" new file mode 100644 index 0000000000000000000000000000000000000000..133ce9c09319624b33f753d2bc554a6a862a0b9b --- /dev/null +++ "b/noomi\344\277\256\346\224\271\350\256\260\345\275\225.md" @@ -0,0 +1,17 @@ +# 修改: +- 1.aop代理,切点表达式*处理,允许使用* 。可以通过设置在切面类的prototype__isAspect属性区别 +- 2.路由注册,新定义registMethodMap记录被Route装饰过的方法,被Route装饰过的方法,Router不进行addRoute +- 3.InstanceFatory.handle()中handDir传参修改。之前的pa[]中 pa[0]为d:\\...绝对路径pa[1-..]为string,直接Array.join('/)会变成D:\\../...,虽然目前没报错,但是逻辑不对 +- 4.数据库,DbMannager.init()时创建了connect mannager实例,使用addInstance({instance:new CM()}),但是addInstance中没保存instance,也没保存cm创建需要的参数。故修改addInstance(); +- 5.事务,事务基于Aop,Aop针对的类名,TransactionManager.handleInstanceTranstraction中传入addTransaction的参数---->改为className,同时Aop中的事务切点名为类名加切点名,因此修改TransactionManager.addExpress()中向AopFatory.addExpress()传入的切点名 +- 6.handleResult中修改data为数据对象时调用res.writeToClient传入的参数。因为在RouteFactory.handOneResult()中对json数据和默认数据进行了封装->{data,mimeType}并返回,此时requestQuene.handResult()会处理,当data=''时,会返回{mimeType},故修改。 +- 7.在route中调用this.response.redirect(); + 修改: + - 1.在response.redirect()中返回ERouteResultType.REDIRECT + - 2.直接在HttpResponse中内置一个private isredirect属性。用于判断当前response是否redirect +//---舍弃 +- 8.security部分:securityFactory中应先注册filter再addInstance-->处理handFilter...,security.json中的expression[],是string ,可以直接注销采用默认?还是转为RegExp,,,handFilter中对parttern的拼接出现问题 +//---未做------ +- 9.model处理信息错误时,requestQuene.hanldeOne()捕获错误,将错误信息传入到webHandler,新建ModelHandler处理 +- 10.删除热部署,security部分,重启项目,删除缓存 +- Instance Transaction Aspect 冲突。先执行Transaction、Aspect等装饰器会以类名为实例名生成实例。如果再使用Instance装饰器,自定义实例名生成实例会再生成一个但是,但是事务注册信息map已经删除 \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 287124f0207427c5ea7a08509717ba6f229069c0..a52d3c4460c135058cf94bf6371b282614470a77 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,133 +1,886 @@ { "name": "noomi", "version": "1.0.0-beta1", - "lockfileVersion": 2, + "lockfileVersion": 1, "requires": true, - "packages": { - "": { - "name": "noomi", - "version": "1.0.0-beta1", - "license": "MIT", - "dependencies": { - "@types/node": "^14.14.31", - "json5": "^2.1.3", - "mime": "^2.5.2", - "redis": "^3.0.2", - "uuid": "^8.3.2" - }, - "engines": { - "node": ">=13.20.0" - } + "dependencies": { + "@socket.io/base64-arraybuffer": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@socket.io/base64-arraybuffer/-/base64-arraybuffer-1.0.2.tgz", + "integrity": "sha512-dOlCBKnDw4iShaIsH/bxujKTM18+2TOAsYz+KSc11Am38H4q5Xw8Bbz97ZYdrVNM+um3p7w86Bvvmcn9q+5+eQ==" + }, + "@sqltools/formatter": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@sqltools/formatter/-/formatter-1.2.3.tgz", + "integrity": "sha512-O3uyB/JbkAEMZaP3YqyHH7TMnex7tWyCbCI4EfJdOCoN6HIhqdJBWTM6aCCiWQ/5f5wxjgU735QAIpJbjDvmzg==" + }, + "@types/component-emitter": { + "version": "1.2.11", + "resolved": "https://registry.npmjs.org/@types/component-emitter/-/component-emitter-1.2.11.tgz", + "integrity": "sha512-SRXjM+tfsSlA9VuG8hGO2nft2p8zjXCK1VcC6N4NXbBbYbSia9kzCChYQajIjzIqOOOuh5Ock6MmV2oux4jDZQ==" + }, + "@types/cookie": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/@types/cookie/-/cookie-0.4.1.tgz", + "integrity": "sha512-XW/Aa8APYr6jSVVA1y/DEIZX0/GMKLEVekNG727R8cs56ahETkRAy/3DR7+fJyh7oUgGwNQaRfXCun0+KbWY7Q==" }, - "node_modules/@types/node": { + "@types/cors": { + "version": "2.8.12", + "resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.12.tgz", + "integrity": "sha512-vt+kDhq/M2ayberEtJcIN/hxXy1Pk+59g2FV/ZQceeaTyCtCucjL2Q7FXlFjtWn4n15KCr1NE2lNNFhp0lEThw==" + }, + "@types/node": { "version": "14.14.37", "resolved": "https://registry.npm.taobao.org/@types/node/download/@types/node-14.14.37.tgz", "integrity": "sha512-XYmBiy+ohOR4Lh5jE379fV2IU+6Jn4g5qASinhitfyO71b/sCo6MKsMLF5tc7Zf2CE8hViVQyYSobJNke8OvUw==" }, - "node_modules/json5": { - "version": "2.2.0", - "resolved": "https://registry.npm.taobao.org/json5/download/json5-2.2.0.tgz", - "integrity": "sha512-f+8cldu7X/y7RAJurMEJmdoKXGB/X550w2Nr3tTbezL6RwEE/iMcm+tZnXeoZtKuOq6ft8+CqzEkrIgx1fPoQA==", - "dependencies": { - "minimist": "^1.2.5" - }, - "bin": { - "json5": "lib/cli.js" + "@types/zen-observable": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/@types/zen-observable/-/zen-observable-0.8.3.tgz", + "integrity": "sha512-fbF6oTd4sGGy0xjHPKAt+eS2CrxJ3+6gQ3FGcBoIJR2TLAyCkCyI8JqZNy+FeON0AhVgNJoUumVoZQjBFUqHkw==" + }, + "accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "requires": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + } + }, + "ajv": { + "version": "6.12.6", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", + "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", + "requires": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + } + }, + "ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==" + }, + "ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "requires": { + "color-convert": "^2.0.1" + } + }, + "any-promise": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz", + "integrity": "sha1-q8av7tzqUugJzcA3au0845Y10X8=" + }, + "app-root-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/app-root-path/-/app-root-path-3.0.0.tgz", + "integrity": "sha512-qMcx+Gy2UZynHjOHOIXPNvpf+9cjvk3cWrBBK7zg4gH9+clobJRb9NGzcT7mQTcV/6Gm/1WelUtqxVXnNlrwcw==" + }, + "argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==" + }, + "array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha1-ml9pkFGx5wczKPKgCJaLZOopVdI=" + }, + "asn1": { + "version": "0.2.6", + "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.6.tgz", + "integrity": "sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ==", + "requires": { + "safer-buffer": "~2.1.0" + } + }, + "assert-plus": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz", + "integrity": "sha1-8S4PPF13sLHN2RRpQuTpbB5N1SU=" + }, + "async": { + "version": "0.9.2", + "resolved": "https://registry.npmjs.org/async/-/async-0.9.2.tgz", + "integrity": "sha1-rqdNXmHB+JlhO/ZL2mbUx48v0X0=" + }, + "asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k=" + }, + "aws-sign2": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/aws-sign2/-/aws-sign2-0.7.0.tgz", + "integrity": "sha1-tG6JCTSpWR8tL2+G1+ap8bP+dqg=" + }, + "aws4": { + "version": "1.11.0", + "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.11.0.tgz", + "integrity": "sha512-xh1Rl34h6Fi1DC2WWKfxUTVqRsNnr6LsKz2+hfwDxQJWmrx8+c7ylaqBMcHfl1U1r2dsifOvKX3LQuLNZ+XSvA==" + }, + "balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==" + }, + "base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==" + }, + "base64id": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/base64id/-/base64id-2.0.0.tgz", + "integrity": "sha512-lGe34o6EHj9y3Kts9R4ZYs/Gr+6N7MCaMlIFA3F1R2O5/m7K06AxfSeO5530PEERE6/WyEg3lsuyw4GHlPZHog==" + }, + "bcrypt-pbkdf": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz", + "integrity": "sha1-pDAdOJtqQ/m2f/PKEaP2Y342Dp4=", + "requires": { + "tweetnacl": "^0.14.3" + } + }, + "body-parser": { + "version": "1.19.2", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.19.2.tgz", + "integrity": "sha512-SAAwOxgoCKMGs9uUAUFHygfLAyaniaoun6I8mFY9pRAJL9+Kec34aU+oIjDhTycub1jozEfEwx1W1IuOYxVSFw==", + "requires": { + "bytes": "3.1.2", + "content-type": "~1.0.4", + "debug": "2.6.9", + "depd": "~1.1.2", + "http-errors": "1.8.1", + "iconv-lite": "0.4.24", + "on-finished": "~2.3.0", + "qs": "6.9.7", + "raw-body": "2.4.3", + "type-is": "~1.6.18" }, - "engines": { - "node": ">=6" + "dependencies": { + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "requires": { + "ms": "2.0.0" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" + }, + "qs": { + "version": "6.9.7", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.9.7.tgz", + "integrity": "sha512-IhMFgUmuNpyRfxA90umL7ByLlgRXu6tIfKPpF5TmcfRLlLCckfP/g3IQmju6jjpu+Hh8rA+2p6A27ZSPOOHdKw==" + } } }, - "node_modules/json5/node_modules/minimist": { - "version": "1.2.5", - "resolved": "https://registry.npm.taobao.org/minimist/download/minimist-1.2.5.tgz?cache=0&sync_timestamp=1611032391891&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fminimist%2Fdownload%2Fminimist-1.2.5.tgz", - "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==", - "license": "MIT" + "brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } }, - "node_modules/mime": { - "version": "2.5.2", - "resolved": "https://registry.npm.taobao.org/mime/download/mime-2.5.2.tgz?cache=0&sync_timestamp=1613586050319&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fmime%2Fdownload%2Fmime-2.5.2.tgz", - "integrity": "sha512-tqkh47FzKeCPD2PUiPB6pkbMzsCasjxAfC62/Wap5qrUWcb+sFasXUC5I3gYM5iBM8v/Qpn4UK0x+j0iHyFPDg==", - "license": "MIT", - "bin": { - "mime": "cli.js" + "buffer": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz", + "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==", + "requires": { + "base64-js": "^1.3.1", + "ieee754": "^1.2.1" + } + }, + "bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==" + }, + "caseless": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz", + "integrity": "sha1-G2gcIf+EAzyCZUMJBolCDRhxUdw=" + }, + "chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "cli-highlight": { + "version": "2.1.11", + "resolved": "https://registry.npmjs.org/cli-highlight/-/cli-highlight-2.1.11.tgz", + "integrity": "sha512-9KDcoEVwyUXrjcJNvHD0NFc/hiwe/WPVYIleQh2O1N2Zro5gWJZ/K+3DGn8w8P/F6FxOgzyC5bxDyHIgCSPhGg==", + "requires": { + "chalk": "^4.0.0", + "highlight.js": "^10.7.1", + "mz": "^2.4.0", + "parse5": "^5.1.1", + "parse5-htmlparser2-tree-adapter": "^6.0.0", + "yargs": "^16.0.0" }, - "engines": { - "node": ">=4.0.0" + "dependencies": { + "yargs": { + "version": "16.2.0", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-16.2.0.tgz", + "integrity": "sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw==", + "requires": { + "cliui": "^7.0.2", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.0", + "y18n": "^5.0.5", + "yargs-parser": "^20.2.2" + } + } } }, - "node_modules/redis": { - "version": "3.1.0", - "resolved": "https://registry.npm.taobao.org/redis/download/redis-3.1.0.tgz", - "integrity": "sha512-//lAOcEtNIKk2ekZibes5oyWKYUVWMvMB71lyD/hS9KRePNkB7AU3nXGkArX6uDKEb2N23EyJBthAv6pagD0uw==", + "cliui": { + "version": "7.0.4", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-7.0.4.tgz", + "integrity": "sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==", + "requires": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.0", + "wrap-ansi": "^7.0.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" + }, + "combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "requires": { + "delayed-stream": "~1.0.0" + } + }, + "component-emitter": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.3.0.tgz", + "integrity": "sha512-Rd3se6QB+sO1TwqZjscQrurpEPIfO0/yYnSin6Q/rD3mOutHvUrCAhJub3r90uNb+SESBuE0QYoB90YdfatsRg==" + }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=" + }, + "connect": { + "version": "3.7.0", + "resolved": "https://registry.npmjs.org/connect/-/connect-3.7.0.tgz", + "integrity": "sha512-ZqRXc+tZukToSNmh5C2iWMSoV3X1YUcPbqEM4DkEG5tNQXrQUZCNVGGv3IuicnkMtPfGf3Xtp8WCXs295iQ1pQ==", + "requires": { + "debug": "2.6.9", + "finalhandler": "1.1.2", + "parseurl": "~1.3.3", + "utils-merge": "1.0.1" + }, "dependencies": { - "denque": "^1.5.0", - "redis-commands": "^1.7.0", - "redis-errors": "^1.2.0", - "redis-parser": "^3.0.0" + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "requires": { + "ms": "2.0.0" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" + } + } + }, + "connect-assetmanager": { + "version": "0.0.28", + "resolved": "https://registry.npmjs.org/connect-assetmanager/-/connect-assetmanager-0.0.28.tgz", + "integrity": "sha1-sfZNLDtpdMfN6vBFMw2rSHYQo8Q=", + "requires": { + "request": ">=0.10.0", + "step": ">=0.0.3" + } + }, + "connect-assetmanager-handlers": { + "version": "0.0.18", + "resolved": "https://registry.npmjs.org/connect-assetmanager-handlers/-/connect-assetmanager-handlers-0.0.18.tgz", + "integrity": "sha1-V1OxojB80OLxRbi2264FDgDClRA=", + "requires": { + "request": ">=0.9.5", + "step": ">=0.0.3", + "uglify-js": ">=0.0.1" + } + }, + "content-disposition": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "requires": { + "safe-buffer": "5.2.1" + } + }, + "content-type": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.4.tgz", + "integrity": "sha512-hIP3EEPs8tB9AT1L+NUqtwOAps4mk2Zob89MWXMHjHWg9milF/j4osnnQLXBCBFBk/tvIG/tUc9mOUJiPBhPXA==" + }, + "cookie": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.4.2.tgz", + "integrity": "sha512-aSWTXFzaKWkvHO1Ny/s+ePFpvKsPnjc551iI41v3ny/ow6tBG5Vd+FuqGNhh1LxOmVzOlGUriIlOaokOvhaStA==" + }, + "cookie-signature": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", + "integrity": "sha1-4wOogrNCzD7oylE6eZmXNNqzriw=" + }, + "core-util-is": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", + "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=" + }, + "cors": { + "version": "2.8.5", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", + "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", + "requires": { + "object-assign": "^4", + "vary": "^1" + } + }, + "dashdash": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/dashdash/-/dashdash-1.14.1.tgz", + "integrity": "sha1-hTz6D3y+L+1d4gMmuN1YEDX24vA=", + "requires": { + "assert-plus": "^1.0.0" + } + }, + "date-format": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/date-format/-/date-format-4.0.4.tgz", + "integrity": "sha512-/jyf4rhB17ge328HJuJjAcmRtCsGd+NDeAtahRBTaK6vSPR6MO5HlrAit3Nn7dVjaa6sowW0WXt8yQtLyZQFRg==" + }, + "debug": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.3.tgz", + "integrity": "sha512-/zxw5+vh1Tfv+4Qn7a5nsbcJKPaSvCDhojn6FEl9vupwK2VCSDtEiEtqr8DFtzYFOdz63LBkxec7DYuc2jon6Q==", + "requires": { + "ms": "2.1.2" + } + }, + "delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha1-3zrhmayt+31ECqrgsp4icrJOxhk=" + }, + "depd": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", + "integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=" + }, + "destroy": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz", + "integrity": "sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA=" + }, + "dotenv": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-8.6.0.tgz", + "integrity": "sha512-IrPdXQsk2BbzvCBGBOTmmSH5SodmqZNt4ERAZDmW4CT+tL8VtvinqywuANaFu4bOMWki16nqf0e4oC0QIaDr/g==" + }, + "ecc-jsbn": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz", + "integrity": "sha1-OoOpBOVDUyh4dMVkt1SThoSamMk=", + "requires": { + "jsbn": "~0.1.0", + "safer-buffer": "^2.1.0" + } + }, + "ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0=" + }, + "ejs": { + "version": "3.1.6", + "resolved": "https://registry.npmjs.org/ejs/-/ejs-3.1.6.tgz", + "integrity": "sha512-9lt9Zse4hPucPkoP7FHDF0LQAlGyF9JVpnClFLFH3aSSbxmyoqINRpp/9wePWJTUl4KOQwRL72Iw3InHPDkoGw==", + "requires": { + "jake": "^10.6.1" + } + }, + "emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==" + }, + "encodeurl": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", + "integrity": "sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k=" + }, + "engine.io": { + "version": "6.1.3", + "resolved": "https://registry.npmjs.org/engine.io/-/engine.io-6.1.3.tgz", + "integrity": "sha512-rqs60YwkvWTLLnfazqgZqLa/aKo+9cueVfEi/dZ8PyGyaf8TLOxj++4QMIgeG3Gn0AhrWiFXvghsoY9L9h25GA==", + "requires": { + "@types/cookie": "^0.4.1", + "@types/cors": "^2.8.12", + "@types/node": ">=10.0.0", + "accepts": "~1.3.4", + "base64id": "2.0.0", + "cookie": "~0.4.1", + "cors": "~2.8.5", + "debug": "~4.3.1", + "engine.io-parser": "~5.0.3", + "ws": "~8.2.3" + } + }, + "engine.io-parser": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.0.3.tgz", + "integrity": "sha512-BtQxwF27XUNnSafQLvDi0dQ8s3i6VgzSoQMJacpIcGNrlUdfHSKbgm3jmjCVvQluGzqwujQMPAoMai3oYSTurg==", + "requires": { + "@socket.io/base64-arraybuffer": "~1.0.2" + } + }, + "escalade": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz", + "integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==" + }, + "escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg=" + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=" + }, + "etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha1-Qa4u62XvpiJorr/qg6x9eSmbCIc=" + }, + "express": { + "version": "4.17.3", + "resolved": "https://registry.npmjs.org/express/-/express-4.17.3.tgz", + "integrity": "sha512-yuSQpz5I+Ch7gFrPCk4/c+dIBKlQUxtgwqzph132bsT6qhuzss6I8cLJQz7B3rFblzd6wtcI0ZbGltH/C4LjUg==", + "requires": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "1.19.2", + "content-disposition": "0.5.4", + "content-type": "~1.0.4", + "cookie": "0.4.2", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "~1.1.2", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "~1.1.2", + "fresh": "0.5.2", + "merge-descriptors": "1.0.1", + "methods": "~1.1.2", + "on-finished": "~2.3.0", + "parseurl": "~1.3.3", + "path-to-regexp": "0.1.7", + "proxy-addr": "~2.0.7", + "qs": "6.9.7", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "0.17.2", + "serve-static": "1.14.2", + "setprototypeof": "1.2.0", + "statuses": "~1.5.0", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" }, - "engines": { - "node": ">=10" + "dependencies": { + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "requires": { + "ms": "2.0.0" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" + }, + "qs": { + "version": "6.9.7", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.9.7.tgz", + "integrity": "sha512-IhMFgUmuNpyRfxA90umL7ByLlgRXu6tIfKPpF5TmcfRLlLCckfP/g3IQmju6jjpu+Hh8rA+2p6A27ZSPOOHdKw==" + } + } + }, + "extend": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", + "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==" + }, + "extsprintf": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.3.0.tgz", + "integrity": "sha1-lpGEQOMEGnpBT4xS48V06zw+HgU=" + }, + "fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==" + }, + "fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==" + }, + "filelist": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/filelist/-/filelist-1.0.2.tgz", + "integrity": "sha512-z7O0IS8Plc39rTCq6i6iHxk43duYOn8uFJiWSewIq0Bww1RNybVHSCjahmcC87ZqAm4OTvFzlzeGu3XAzG1ctQ==", + "requires": { + "minimatch": "^3.0.4" + } + }, + "finalhandler": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.1.2.tgz", + "integrity": "sha512-aAWcW57uxVNrQZqFXjITpW3sIUQmHGG3qSb9mUah9MgMC4NeWhNOlNjXEYq3HjRAvL6arUviZGGJsBg6z0zsWA==", + "requires": { + "debug": "2.6.9", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "on-finished": "~2.3.0", + "parseurl": "~1.3.3", + "statuses": "~1.5.0", + "unpipe": "~1.0.0" }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/node-redis" + "dependencies": { + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "requires": { + "ms": "2.0.0" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" + } } }, - "node_modules/redis/node_modules/denque": { - "version": "1.5.0", - "resolved": "https://registry.npm.taobao.org/denque/download/denque-1.5.0.tgz", - "integrity": "sha512-CYiCSgIF1p6EUByQPlGkKnP1M9g0ZV3qMIrqMqZqdwazygIA/YP2vrbcyl1h/WppKJTdl1F85cXIle+394iDAQ==", - "engines": { - "node": ">=0.10" + "flatted": { + "version": "3.2.5", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.2.5.tgz", + "integrity": "sha512-WIWGi2L3DyTUvUrwRKgGi9TwxQMUEqPOPQBVi71R96jZXJdFskXEmf54BoZaS1kknGODoIGASGEzBUYdyMCBJg==" + }, + "forever-agent": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/forever-agent/-/forever-agent-0.6.1.tgz", + "integrity": "sha1-+8cfDEGt6zf5bFd60e1C2P2sypE=" + }, + "form-data": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-2.3.3.tgz", + "integrity": "sha512-1lLKB2Mu3aGP1Q/2eCOx0fNbRMe7XdwktwOruhfqqd0rIJWwN4Dh+E3hrPSlDCXnSR7UtZ1N38rVXm+6+MEhJQ==", + "requires": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.6", + "mime-types": "^2.1.12" + } + }, + "forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==" + }, + "fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac=" + }, + "fs-extra": { + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.0.1.tgz", + "integrity": "sha512-NbdoVMZso2Lsrn/QwLXOy6rm0ufY2zEOKCDzJR/0kBsb0E6qed0P3iYK+Ath3BfvXEeu4JhEtXLgILx5psUfag==", + "requires": { + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + } + }, + "fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=" + }, + "get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==" + }, + "getpass": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/getpass/-/getpass-0.1.7.tgz", + "integrity": "sha1-Xv+OPmhNVprkyysSgmBOi6YhSfo=", + "requires": { + "assert-plus": "^1.0.0" + } + }, + "glob": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.0.tgz", + "integrity": "sha512-lmLf6gtyrPq8tTjSmrO94wBeQbFR3HbLHbuyD69wuyQkImp2hWqMGB47OX65FBkPffO641IP9jWa1z4ivqG26Q==", + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "graceful-fs": { + "version": "4.2.9", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.9.tgz", + "integrity": "sha512-NtNxqUcXgpW2iMrfqSfR73Glt39K+BLwWsPs94yR63v45T0Wbej7eRmL5cWfwEgqXnmjQp3zaJTshdRW/qC2ZQ==" + }, + "har-schema": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/har-schema/-/har-schema-2.0.0.tgz", + "integrity": "sha1-qUwiJOvKwEeCoNkDVSHyRzW37JI=" + }, + "har-validator": { + "version": "5.1.5", + "resolved": "https://registry.npmjs.org/har-validator/-/har-validator-5.1.5.tgz", + "integrity": "sha512-nmT2T0lljbxdQZfspsno9hgrG3Uir6Ks5afism62poxqBM6sDnMEuPmzTq8XN0OEwqKLLdh1jQI3qyE66Nzb3w==", + "requires": { + "ajv": "^6.12.3", + "har-schema": "^2.0.0" } }, - "node_modules/redis/node_modules/redis-commands": { - "version": "1.7.0", - "resolved": "https://registry.npm.taobao.org/redis-commands/download/redis-commands-1.7.0.tgz", - "integrity": "sha512-nJWqw3bTFy21hX/CPKHth6sfhZbdiHP6bTawSgQBlKOVRG7EZkfHbbHwQJnrE4vsQf0CMNE+3gJ4Fmm16vdVlQ==" + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==" + }, + "highlight.js": { + "version": "10.7.3", + "resolved": "https://registry.npmjs.org/highlight.js/-/highlight.js-10.7.3.tgz", + "integrity": "sha512-tzcUFauisWKNHaRkN4Wjl/ZA07gENAjFl3J/c480dprkGTg5EQstgaNFqBfUqCq54kZRIEcreTsAgF/m2quD7A==" + }, + "hotcode": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/hotcode/-/hotcode-0.0.6.tgz", + "integrity": "sha1-3N/Rys1mBkkJCMXMovdFFDQVWK0=", + "requires": { + "connect": ">=1.7.1", + "connect-assetmanager": ">=0.0.24", + "connect-assetmanager-handlers": ">=0.0.17", + "ejs": ">=0.4.3", + "express": ">=2.4.7", + "optimist": ">=0.2.6", + "socket.io": ">=0.8.5" + } + }, + "hotnode": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/hotnode/-/hotnode-0.0.8.tgz", + "integrity": "sha1-OtqmPVslLCbxKUXIJ9YSXGDIBzM=", + "requires": { + "watch": "0.5.0" + } + }, + "http-errors": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.8.1.tgz", + "integrity": "sha512-Kpk9Sm7NmI+RHhnj6OIWDI1d6fIoFAtFt9RLaTMRlg/8w49juAStsrBgp0Dp4OdxdVbRIeKhtCUvoi/RuAhO4g==", + "requires": { + "depd": "~1.1.2", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": ">= 1.5.0 < 2", + "toidentifier": "1.0.1" + } }, - "node_modules/redis/node_modules/redis-errors": { + "http-signature": { "version": "1.2.0", - "resolved": "https://registry.npm.taobao.org/redis-errors/download/redis-errors-1.2.0.tgz", - "integrity": "sha1-62LSrbFeTq9GEMBK/hUpOEJQq60=", - "engines": { - "node": ">=4" + "resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.2.0.tgz", + "integrity": "sha1-muzZJRFHcvPZW2WmCruPfBj7rOE=", + "requires": { + "assert-plus": "^1.0.0", + "jsprim": "^1.2.2", + "sshpk": "^1.7.0" } }, - "node_modules/redis/node_modules/redis-parser": { + "iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "requires": { + "safer-buffer": ">= 2.1.2 < 3" + } + }, + "ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==" + }, + "inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "requires": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + "ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==" + }, + "is-fullwidth-code-point": { "version": "3.0.0", - "resolved": "https://registry.npm.taobao.org/redis-parser/download/redis-parser-3.0.0.tgz", - "integrity": "sha1-tm2CjNyv5rS4pCin3vTGvKwxyLQ=", - "dependencies": { - "redis-errors": "^1.0.0" + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==" + }, + "is-typedarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", + "integrity": "sha1-5HnICFjfDBsR3dppQPlgEfzaSpo=" + }, + "isstream": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz", + "integrity": "sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo=" + }, + "jake": { + "version": "10.8.2", + "resolved": "https://registry.npmjs.org/jake/-/jake-10.8.2.tgz", + "integrity": "sha512-eLpKyrfG3mzvGE2Du8VoPbeSkRry093+tyNjdYaBbJS9v17knImYGNXQCUV0gLxQtF82m3E8iRb/wdSQZLoq7A==", + "requires": { + "async": "0.9.x", + "chalk": "^2.4.2", + "filelist": "^1.0.1", + "minimatch": "^3.0.4" }, - "engines": { - "node": ">=4" + "dependencies": { + "ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "requires": { + "color-convert": "^1.9.0" + } + }, + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "requires": { + "color-name": "1.1.3" + } + }, + "color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=" + }, + "has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" + }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "requires": { + "has-flag": "^3.0.0" + } + } } }, - "node_modules/redis/node_modules/redis-parser/node_modules/redis-errors": { - "version": "1.2.0", - "resolved": "https://registry.npm.taobao.org/redis-errors/download/redis-errors-1.2.0.tgz", - "integrity": "sha1-62LSrbFeTq9GEMBK/hUpOEJQq60=", - "engines": { - "node": ">=4" + "js-yaml": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", + "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", + "requires": { + "argparse": "^2.0.1" } }, - "node_modules/uuid": { - "version": "8.3.2", - "resolved": "https://registry.npm.taobao.org/uuid/download/uuid-8.3.2.tgz", - "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", - "bin": { - "uuid": "dist/bin/uuid" - } - } - }, - "dependencies": { - "@types/node": { - "version": "14.14.37", - "resolved": "https://registry.npm.taobao.org/@types/node/download/@types/node-14.14.37.tgz", - "integrity": "sha512-XYmBiy+ohOR4Lh5jE379fV2IU+6Jn4g5qASinhitfyO71b/sCo6MKsMLF5tc7Zf2CE8hViVQyYSobJNke8OvUw==" + "jsbn": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/jsbn/-/jsbn-0.1.1.tgz", + "integrity": "sha1-peZUwuWi3rXyAdls77yoDA7y9RM=" + }, + "json-schema": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.4.0.tgz", + "integrity": "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA==" + }, + "json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==" + }, + "json-stringify-safe": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", + "integrity": "sha1-Epai1Y/UXxmg9s4B1lcB4sc1tus=" }, "json5": { "version": "2.2.0", @@ -144,11 +897,229 @@ } } }, + "jsonfile": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz", + "integrity": "sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==", + "requires": { + "graceful-fs": "^4.1.6", + "universalify": "^2.0.0" + } + }, + "jsprim": { + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/jsprim/-/jsprim-1.4.2.tgz", + "integrity": "sha512-P2bSOMAc/ciLz6DzgjVlGJP9+BrJWu5UDGK70C2iweC5QBIeFf0ZXRvGjEj2uYgrY2MkAAhsSWHDWlFtEroZWw==", + "requires": { + "assert-plus": "1.0.0", + "extsprintf": "1.3.0", + "json-schema": "0.4.0", + "verror": "1.10.0" + } + }, + "log4js": { + "version": "6.4.2", + "resolved": "https://registry.npmjs.org/log4js/-/log4js-6.4.2.tgz", + "integrity": "sha512-k80cggS2sZQLBwllpT1p06GtfvzMmSdUCkW96f0Hj83rKGJDAu2vZjt9B9ag2vx8Zz1IXzxoLgqvRJCdMKybGg==", + "requires": { + "date-format": "^4.0.4", + "debug": "^4.3.3", + "flatted": "^3.2.5", + "rfdc": "^1.3.0", + "streamroller": "^3.0.4" + } + }, + "md5-node": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/md5-node/-/md5-node-1.0.1.tgz", + "integrity": "sha1-DiLQCdRr3JWx08XoyP7dwaXDqog=" + }, + "media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g=" + }, + "merge-descriptors": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", + "integrity": "sha1-sAqqVW3YtEVoFQ7J0blT8/kMu2E=" + }, + "methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha1-VSmk1nZUE07cxSZmVoNbD4Ua/O4=" + }, "mime": { "version": "2.5.2", "resolved": "https://registry.npm.taobao.org/mime/download/mime-2.5.2.tgz?cache=0&sync_timestamp=1613586050319&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fmime%2Fdownload%2Fmime-2.5.2.tgz", "integrity": "sha512-tqkh47FzKeCPD2PUiPB6pkbMzsCasjxAfC62/Wap5qrUWcb+sFasXUC5I3gYM5iBM8v/Qpn4UK0x+j0iHyFPDg==" }, + "mime-db": { + "version": "1.51.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.51.0.tgz", + "integrity": "sha512-5y8A56jg7XVQx2mbv1lu49NR4dokRnhZYTtL+KGfaa27uq4pSTXkwQkFJl4pkRMyNFz/EtYDSkiiEHx3F7UN6g==" + }, + "mime-types": { + "version": "2.1.34", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.34.tgz", + "integrity": "sha512-6cP692WwGIs9XXdOO4++N+7qjqv0rqxxVvJ3VHPh/Sc9mVZcQP+ZGhkKiTvWMQRr2tbHkJP/Yn7Y0npb3ZBs4A==", + "requires": { + "mime-db": "1.51.0" + } + }, + "minimatch": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", + "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "requires": { + "brace-expansion": "^1.1.7" + } + }, + "minimist": { + "version": "0.0.10", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.10.tgz", + "integrity": "sha1-3j+YVD2/lggr5IrRoMfNqDYwHc8=" + }, + "mkdirp": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", + "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==" + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + }, + "mz": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz", + "integrity": "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==", + "requires": { + "any-promise": "^1.0.0", + "object-assign": "^4.0.1", + "thenify-all": "^1.0.0" + } + }, + "negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==" + }, + "oauth-sign": { + "version": "0.9.0", + "resolved": "https://registry.npmjs.org/oauth-sign/-/oauth-sign-0.9.0.tgz", + "integrity": "sha512-fexhUFFPTGV8ybAtSIGbV6gOkSv8UtRbDBnAyLQw4QPKkgNlsH2ByPGtMUqdWkos6YCRmAqViwgZrJc/mRDzZQ==" + }, + "object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=" + }, + "on-finished": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz", + "integrity": "sha1-IPEzZIGwg811M3mSoWlxqi2QaUc=", + "requires": { + "ee-first": "1.1.1" + } + }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "requires": { + "wrappy": "1" + } + }, + "optimist": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/optimist/-/optimist-0.6.1.tgz", + "integrity": "sha1-2j6nRob6IaGaERwybpDrFaAZZoY=", + "requires": { + "minimist": "~0.0.1", + "wordwrap": "~0.0.2" + } + }, + "parse5": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-5.1.1.tgz", + "integrity": "sha512-ugq4DFI0Ptb+WWjAdOK16+u/nHfiIrcE+sh8kZMaM0WllQKLI9rOUq6c2b7cwPkXdzfQESqvoqK6ug7U/Yyzug==" + }, + "parse5-htmlparser2-tree-adapter": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/parse5-htmlparser2-tree-adapter/-/parse5-htmlparser2-tree-adapter-6.0.1.tgz", + "integrity": "sha512-qPuWvbLgvDGilKc5BoicRovlT4MtYT6JfJyBOMDsKoiT+GiuP5qyrPCnR9HcPECIJJmZh5jRndyNThnhhb/vlA==", + "requires": { + "parse5": "^6.0.1" + }, + "dependencies": { + "parse5": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-6.0.1.tgz", + "integrity": "sha512-Ofn/CTFzRGTTxwpNEs9PP93gXShHcTq255nzRYSKe8AkVpZY7e1fpmTfOyoIvjP5HG7Z2ZM7VS9PPhQGW2pOpw==" + } + } + }, + "parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==" + }, + "path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=" + }, + "path-to-regexp": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", + "integrity": "sha1-32BBeABfUi8V60SQ5yR6G/qmf4w=" + }, + "performance-now": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/performance-now/-/performance-now-2.1.0.tgz", + "integrity": "sha1-Ywn04OX6kT7BxpMHrjZLSzd8nns=" + }, + "proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "requires": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + } + }, + "psl": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/psl/-/psl-1.8.0.tgz", + "integrity": "sha512-RIdOzyoavK+hA18OGGWDqUTsCLhtA7IcZ/6NCs4fFJaHBDab+pDDmDIByWFRQJq2Cd7r1OoQxBGKOaztq+hjIQ==" + }, + "punycode": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", + "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==" + }, + "qs": { + "version": "6.5.3", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.5.3.tgz", + "integrity": "sha512-qxXIEh4pCGfHICj1mAJQ2/2XVZkjCDTcEgfoSQxc/fYivUZxTkk7L3bDBJSoNrEzXI17oUO5Dp07ktqE5KzczA==" + }, + "range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==" + }, + "raw-body": { + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.4.3.tgz", + "integrity": "sha512-UlTNLIcu0uzb4D2f4WltY6cVjLi+/jEN4lgEUj3E04tpMDpUlkBo/eSn6zou9hum2VMNpCCUone0O0WeJim07g==", + "requires": { + "bytes": "3.1.2", + "http-errors": "1.8.1", + "iconv-lite": "0.4.24", + "unpipe": "1.0.0" + } + }, "redis": { "version": "3.1.0", "resolved": "https://registry.npm.taobao.org/redis/download/redis-3.1.0.tgz", @@ -192,10 +1163,458 @@ } } }, + "reflect-metadata": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.1.13.tgz", + "integrity": "sha512-Ts1Y/anZELhSsjMcU605fU9RE4Oi3p5ORujwbIKXfWa+0Zxs510Qrmrce5/Jowq3cHSZSJqBjypxmHarc+vEWg==" + }, + "relaen": { + "version": "0.3.0-final", + "resolved": "https://registry.npmjs.org/relaen/-/relaen-0.3.0-final.tgz", + "integrity": "sha512-6JiQ03PHtVtoMqVWIoZYr4XFROlar6m4LJcLQq6FC9vpcuowNtqRyYDGgf8V+rPCpKhpurUs6NV3EFf9m7k5Ng==" + }, + "request": { + "version": "2.88.2", + "resolved": "https://registry.npmjs.org/request/-/request-2.88.2.tgz", + "integrity": "sha512-MsvtOrfG9ZcrOwAW+Qi+F6HbD0CWXEh9ou77uOb7FM2WPhwT7smM833PzanhJLsgXjN89Ir6V2PczXNnMpwKhw==", + "requires": { + "aws-sign2": "~0.7.0", + "aws4": "^1.8.0", + "caseless": "~0.12.0", + "combined-stream": "~1.0.6", + "extend": "~3.0.2", + "forever-agent": "~0.6.1", + "form-data": "~2.3.2", + "har-validator": "~5.1.3", + "http-signature": "~1.2.0", + "is-typedarray": "~1.0.0", + "isstream": "~0.1.2", + "json-stringify-safe": "~5.0.1", + "mime-types": "~2.1.19", + "oauth-sign": "~0.9.0", + "performance-now": "^2.1.0", + "qs": "~6.5.2", + "safe-buffer": "^5.1.2", + "tough-cookie": "~2.5.0", + "tunnel-agent": "^0.6.0", + "uuid": "^3.3.2" + }, + "dependencies": { + "uuid": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.4.0.tgz", + "integrity": "sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==" + } + } + }, + "require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha1-jGStX9MNqxyXbiNE/+f3kqam30I=" + }, + "rfdc": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.3.0.tgz", + "integrity": "sha512-V2hovdzFbOi77/WajaSMXk2OLm+xNIeQdMMuB7icj7bk6zi2F8GGAxigcnDFpJHbNyNcgyJDiP+8nOrY5cZGrA==" + }, + "safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==" + }, + "safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" + }, + "sax": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/sax/-/sax-1.2.4.tgz", + "integrity": "sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw==" + }, + "send": { + "version": "0.17.2", + "resolved": "https://registry.npmjs.org/send/-/send-0.17.2.tgz", + "integrity": "sha512-UJYB6wFSJE3G00nEivR5rgWp8c2xXvJ3OPWPhmuteU0IKj8nKbG3DrjiOmLwpnHGYWAVwA69zmTm++YG0Hmwww==", + "requires": { + "debug": "2.6.9", + "depd": "~1.1.2", + "destroy": "~1.0.4", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "0.5.2", + "http-errors": "1.8.1", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "~2.3.0", + "range-parser": "~1.2.1", + "statuses": "~1.5.0" + }, + "dependencies": { + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "requires": { + "ms": "2.0.0" + }, + "dependencies": { + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" + } + } + }, + "mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==" + }, + "ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + } + } + }, + "serve-static": { + "version": "1.14.2", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.14.2.tgz", + "integrity": "sha512-+TMNA9AFxUEGuC0z2mevogSnn9MXKb4fa7ngeRMJaaGv8vTwnIEkKi+QGvPt33HSnf8pRS+WGM0EbMtCJLKMBQ==", + "requires": { + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "0.17.2" + } + }, + "setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==" + }, + "sha.js": { + "version": "2.4.11", + "resolved": "https://registry.npmjs.org/sha.js/-/sha.js-2.4.11.tgz", + "integrity": "sha512-QMEp5B7cftE7APOjk5Y6xgrbWu+WkLVQwk8JNjZ8nKRciZaByEW6MubieAiToS7+dwvrjGhH8jRXz3MVd0AYqQ==", + "requires": { + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, + "socket.io": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/socket.io/-/socket.io-4.4.1.tgz", + "integrity": "sha512-s04vrBswdQBUmuWJuuNTmXUVJhP0cVky8bBDhdkf8y0Ptsu7fKU2LuLbts9g+pdmAdyMMn8F/9Mf1/wbtUN0fg==", + "requires": { + "accepts": "~1.3.4", + "base64id": "~2.0.0", + "debug": "~4.3.2", + "engine.io": "~6.1.0", + "socket.io-adapter": "~2.3.3", + "socket.io-parser": "~4.0.4" + } + }, + "socket.io-adapter": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/socket.io-adapter/-/socket.io-adapter-2.3.3.tgz", + "integrity": "sha512-Qd/iwn3VskrpNO60BeRyCyr8ZWw9CPZyitW4AQwmRZ8zCiyDiL+znRnWX6tDHXnWn1sJrM1+b6Mn6wEDJJ4aYQ==" + }, + "socket.io-parser": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.0.4.tgz", + "integrity": "sha512-t+b0SS+IxG7Rxzda2EVvyBZbvFPBCjJoyHuE0P//7OAsN23GItzDRdWa6ALxZI/8R5ygK7jAR6t028/z+7295g==", + "requires": { + "@types/component-emitter": "^1.2.10", + "component-emitter": "~1.3.0", + "debug": "~4.3.1" + } + }, + "sshpk": { + "version": "1.17.0", + "resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.17.0.tgz", + "integrity": "sha512-/9HIEs1ZXGhSPE8X6Ccm7Nam1z8KcoCqPdI7ecm1N33EzAetWahvQWVqLZtaZQ+IDKX4IyA2o0gBzqIMkAagHQ==", + "requires": { + "asn1": "~0.2.3", + "assert-plus": "^1.0.0", + "bcrypt-pbkdf": "^1.0.0", + "dashdash": "^1.12.0", + "ecc-jsbn": "~0.1.1", + "getpass": "^0.1.1", + "jsbn": "~0.1.0", + "safer-buffer": "^2.0.2", + "tweetnacl": "~0.14.0" + } + }, + "statuses": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz", + "integrity": "sha1-Fhx9rBd2Wf2YEfQ3cfqZOBR4Yow=" + }, + "step": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/step/-/step-1.0.0.tgz", + "integrity": "sha1-swDp0q6QV9TXhjOq4jA4E6lL3/I=" + }, + "streamroller": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/streamroller/-/streamroller-3.0.4.tgz", + "integrity": "sha512-GI9NzeD+D88UFuIlJkKNDH/IsuR+qIN7Qh8EsmhoRZr9bQoehTraRgwtLUkZbpcAw+hLPfHOypmppz8YyGK68w==", + "requires": { + "date-format": "^4.0.4", + "debug": "^4.3.3", + "fs-extra": "^10.0.1" + } + }, + "string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "requires": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + } + }, + "strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "requires": { + "ansi-regex": "^5.0.1" + } + }, + "supervisor": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/supervisor/-/supervisor-0.12.0.tgz", + "integrity": "sha1-3n5jNwFbKRhRwQ81OMSn8EkX7ME=" + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "requires": { + "has-flag": "^4.0.0" + } + }, + "thenify": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz", + "integrity": "sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==", + "requires": { + "any-promise": "^1.0.0" + } + }, + "thenify-all": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/thenify-all/-/thenify-all-1.6.0.tgz", + "integrity": "sha1-GhkY1ALY/D+Y+/I02wvMjMEOlyY=", + "requires": { + "thenify": ">= 3.1.0 < 4" + } + }, + "toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==" + }, + "tough-cookie": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.5.0.tgz", + "integrity": "sha512-nlLsUzgm1kfLXSXfRZMc1KLAugd4hqJHDTvc2hDIwS3mZAfMEuMbc03SujMF+GEcpaX/qboeycw6iO8JwVv2+g==", + "requires": { + "psl": "^1.1.28", + "punycode": "^2.1.1" + } + }, + "tslib": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.1.tgz", + "integrity": "sha512-77EbyPPpMz+FRFRuAFlWMtmgUWGe9UOG2Z25NqCwiIjRhOf5iKGuzSe5P2w1laq+FkRy4p+PCuVkJSGkzTEKVw==" + }, + "tunnel-agent": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha1-J6XeoGs2sEoKmWZ3SykIaPD8QP0=", + "requires": { + "safe-buffer": "^5.0.1" + } + }, + "tweetnacl": { + "version": "0.14.5", + "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz", + "integrity": "sha1-WuaBd/GS1EViadEIr6k/+HQ/T2Q=" + }, + "type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "requires": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + } + }, + "typeorm": { + "version": "0.2.41", + "resolved": "https://registry.npmjs.org/typeorm/-/typeorm-0.2.41.tgz", + "integrity": "sha512-/d8CLJJxKPgsnrZWiMyPI0rz2MFZnBQrnQ5XP3Vu3mswv2WPexb58QM6BEtmRmlTMYN5KFWUz8SKluze+wS9xw==", + "requires": { + "@sqltools/formatter": "^1.2.2", + "app-root-path": "^3.0.0", + "buffer": "^6.0.3", + "chalk": "^4.1.0", + "cli-highlight": "^2.1.11", + "debug": "^4.3.1", + "dotenv": "^8.2.0", + "glob": "^7.1.6", + "js-yaml": "^4.0.0", + "mkdirp": "^1.0.4", + "reflect-metadata": "^0.1.13", + "sha.js": "^2.4.11", + "tslib": "^2.1.0", + "xml2js": "^0.4.23", + "yargs": "^17.0.1", + "zen-observable-ts": "^1.0.0" + } + }, + "uglify-js": { + "version": "3.15.2", + "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.15.2.tgz", + "integrity": "sha512-peeoTk3hSwYdoc9nrdiEJk+gx1ALCtTjdYuKSXMTDqq7n1W7dHPqWDdSi+BPL0ni2YMeHD7hKUSdbj3TZauY2A==" + }, + "universalify": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.0.tgz", + "integrity": "sha512-hAZsKq7Yy11Zu1DE0OzWjw7nnLZmJZYTDZZyEFHZdUhV8FkH5MCfoU1XMaxXovpyW5nq5scPqq0ZDP9Zyl04oQ==" + }, + "unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha1-sr9O6FFKrmFltIF4KdIbLvSZBOw=" + }, + "uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "requires": { + "punycode": "^2.1.0" + } + }, + "utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha1-n5VxD1CiZ5R7LMwSR0HBAoQn5xM=" + }, "uuid": { "version": "8.3.2", "resolved": "https://registry.npm.taobao.org/uuid/download/uuid-8.3.2.tgz", "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==" + }, + "vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha1-IpnwLG3tMNSllhsLn3RSShj2NPw=" + }, + "verror": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/verror/-/verror-1.10.0.tgz", + "integrity": "sha1-OhBcoXBTr1XW4nDB+CiGguGNpAA=", + "requires": { + "assert-plus": "^1.0.0", + "core-util-is": "1.0.2", + "extsprintf": "^1.2.0" + } + }, + "watch": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/watch/-/watch-0.5.0.tgz", + "integrity": "sha1-HrE5mzQglgEnQx76ZGtxjaFG038=" + }, + "wordwrap": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-0.0.3.tgz", + "integrity": "sha1-o9XabNXAvAAI03I0u68b7WMFkQc=" + }, + "wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "requires": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + } + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" + }, + "ws": { + "version": "8.2.3", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.2.3.tgz", + "integrity": "sha512-wBuoj1BDpC6ZQ1B7DWQBYVLphPWkm8i9Y0/3YdHjHKHiohOJ1ws+3OccDWtH+PoC9DZD5WOTrJvNbWvjS6JWaA==" + }, + "xml2js": { + "version": "0.4.23", + "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.4.23.tgz", + "integrity": "sha512-ySPiMjM0+pLDftHgXY4By0uswI3SPKLDw/i3UXbnO8M/p28zqexCUoPmQFrYD+/1BzhGJSs2i1ERWKJAtiLrug==", + "requires": { + "sax": ">=0.6.0", + "xmlbuilder": "~11.0.0" + } + }, + "xmlbuilder": { + "version": "11.0.1", + "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-11.0.1.tgz", + "integrity": "sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA==" + }, + "y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==" + }, + "yargs": { + "version": "17.3.1", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.3.1.tgz", + "integrity": "sha512-WUANQeVgjLbNsEmGk20f+nlHgOqzRFpiGWVaBrYGYIGANIIu3lWjoyi0fNlFmJkvfhCZ6BXINe7/W2O2bV4iaA==", + "requires": { + "cliui": "^7.0.2", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.3", + "y18n": "^5.0.5", + "yargs-parser": "^21.0.0" + }, + "dependencies": { + "yargs-parser": { + "version": "21.0.0", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.0.0.tgz", + "integrity": "sha512-z9kApYUOCwoeZ78rfRYYWdiU/iNL6mwwYlkkZfJoyMR1xps+NEBX5X7XmRpxkZHhXJ6+Ey00IwKxBBSW9FIjyA==" + } + } + }, + "yargs-parser": { + "version": "20.2.9", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.9.tgz", + "integrity": "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==" + }, + "zen-observable": { + "version": "0.8.15", + "resolved": "https://registry.npmjs.org/zen-observable/-/zen-observable-0.8.15.tgz", + "integrity": "sha512-PQ2PC7R9rslx84ndNBZB/Dkv8V8fZEpk83RLgXtYd0fwUgEjseMn1Dgajh2x6S8QbZAFa9p2qVCEuYZNgve0dQ==" + }, + "zen-observable-ts": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/zen-observable-ts/-/zen-observable-ts-1.1.0.tgz", + "integrity": "sha512-1h4zlLSqI2cRLPJUHJFL8bCWHhkpuXkF+dbGkRaWjgDIG26DmzyshUMrdV/rL3UnR+mhaX4fRq8LPouq0MYYIA==", + "requires": { + "@types/zen-observable": "0.8.3", + "zen-observable": "0.8.15" + } } } } diff --git a/package.json b/package.json index a6aed560a52494fa41fd9fa2ab9dfd56bf9ba14b..3df7afa19230033d75b720c4c78cd0b3d5df07ed 100644 --- a/package.json +++ b/package.json @@ -30,9 +30,16 @@ "homepage": "https://github.com/noomijs/noomi#readme", "dependencies": { "@types/node": "^14.14.31", + "hotcode": "0.0.6", + "hotnode": "0.0.8", "json5": "^2.1.3", + "log4js": "^6.4.2", + "md5-node": "^1.0.1", "mime": "^2.5.2", "redis": "^3.0.2", + "relaen": "^0.3.0-final", + "supervisor": "^0.12.0", + "typeorm": "^0.2.41", "uuid": "^8.3.2" }, "engines": { diff --git a/test/app/module/advice/testadvice.ts b/test/app/module/advice/testadvice.ts deleted file mode 100644 index 9c63f69a7e6149d615710d8b1405edb7bac14dd6..0000000000000000000000000000000000000000 --- a/test/app/module/advice/testadvice.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { Aspect, Pointcut, Before, Around, AfterThrow, After, AfterReturn, Instance } from "../../../../core/tools/decorator"; - -@Aspect() -class TestAdvice{ - @Pointcut(["DataImpl.*"]) - testPointcut; - - @Before("testPointcut") - before(){ - console.log("注解前置通知,参数:",arguments[0]); - } - @After("testPointcut") - after(){ - console.log("注释后置通知,方法名:",arguments[0].methodName); - } - - @Around("testPointcut") - around(){ - console.log("注释环绕通知,方法名:",arguments[0].methodName); - } - - @AfterThrow("testPointcut") - afterThrow(){ - console.log("注释异常通知,方法名:",arguments[0].methodName); - } - - @AfterReturn("testPointcut") - afterReturn(args){ - console.log("注释返回通知,方法名:",arguments[0].methodName); - } -} - -export{TestAdvice} \ No newline at end of file diff --git a/test/app/module/common/datehandler.ts b/test/app/module/common/datehandler.ts deleted file mode 100644 index 12694a26d4069c982b8666db49ec6110eeff0c35..0000000000000000000000000000000000000000 --- a/test/app/module/common/datehandler.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { Instance } from "../../../../core/tools/decorator"; - -@Instance({ - name:'dateHandler' -}) -class DateHandler{ - tickerToDTString(ticker:number){ - let d = new Date(ticker); - let year=d.getFullYear(); - let month=d.getMonth()+1; - let date=d.getDate(); - let hour=d.getHours(); - let minute=d.getMinutes(); - let second=d.getSeconds(); - return year+"-"+month+"-"+date+" "+hour+":"+minute+":"+second; - } -} - -export {DateHandler}; \ No newline at end of file diff --git a/test/app/module/dao/entity/group.ts b/test/app/module/dao/entity/group.ts deleted file mode 100644 index 370f8edd12cff737c73d98031ff46c25cb409df6..0000000000000000000000000000000000000000 --- a/test/app/module/dao/entity/group.ts +++ /dev/null @@ -1,53 +0,0 @@ -import {BaseEntity,Entity,Column,Id,OneToMany,EntityProxy} from 'relaen'; -import {GroupUser} from './groupuser'; - -@Entity("t_group",'test') -export class Group extends BaseEntity{ - @Id() - @Column({ - name:'group_id', - type:'int', - nullable:false - }) - private groupId:number; - - @Column({ - name:'group_name', - type:'string', - nullable:true, - length:32 - }) - private groupName:string; - - @OneToMany({ - entity:'GroupUser', - mappedBy:'group' - }) - private groupUsers:Array; - - constructor(idValue?:number){ - super(); - this.groupId = idValue; - } - public getGroupId():number{ - return this.groupId; - } - public setGroupId(value:number){ - this.groupId = value; - } - - public getGroupName():string{ - return this.groupName; - } - public setGroupName(value:string){ - this.groupName = value; - } - - public async getGroupUsers():Promise>{ - return await EntityProxy.get(this,'groupUsers'); - } - public setGroupUsers(value:Array){ - this.groupUsers = value; - } - -} \ No newline at end of file diff --git a/test/app/module/dao/entity/groupuser.ts b/test/app/module/dao/entity/groupuser.ts deleted file mode 100644 index dc803f873fcf83d6a4a9e17302e06cdebe1617eb..0000000000000000000000000000000000000000 --- a/test/app/module/dao/entity/groupuser.ts +++ /dev/null @@ -1,56 +0,0 @@ -import {BaseEntity,Entity,Column,Id,JoinColumn,ManyToOne,EntityProxy} from 'relaen'; -import {User} from './user'; -import {Group} from './group'; - -@Entity("t_group_user",'test') -export class GroupUser extends BaseEntity{ - @Id() - @Column({ - name:'group_user_id', - type:'int', - nullable:false - }) - private groupUserId:number; - - @ManyToOne({entity:'User'}) - @JoinColumn({ - name:'user_id', - refName:'user_id', - nullable:true - }) - private user:User; - - @ManyToOne({entity:'Group'}) - @JoinColumn({ - name:'group_id', - refName:'group_id', - nullable:true - }) - private group:Group; - - constructor(idValue?:number){ - super(); - this.groupUserId = idValue; - } - public getGroupUserId():number{ - return this.groupUserId; - } - public setGroupUserId(value:number){ - this.groupUserId = value; - } - - public async getUser():Promise{ - return await EntityProxy.get(this,'user'); - } - public setUser(value:User){ - this.user = value; - } - - public async getGroup():Promise{ - return await EntityProxy.get(this,'group'); - } - public setGroup(value:Group){ - this.group = value; - } - -} \ No newline at end of file diff --git a/test/app/module/dao/entity/shop.ts b/test/app/module/dao/entity/shop.ts deleted file mode 100644 index 86c89bcd4e44207572dd93139654781d1ab86e53..0000000000000000000000000000000000000000 --- a/test/app/module/dao/entity/shop.ts +++ /dev/null @@ -1,85 +0,0 @@ -import {BaseEntity,Entity,Column,Id,JoinColumn,ManyToOne,EntityProxy} from 'relaen'; -import {UserInfo} from './userinfo'; - -@Entity("t_shop",'test') -export class Shop extends BaseEntity{ - @Id() - @Column({ - name:'shop_id', - type:'int', - nullable:false - }) - private shopId:number; - - @ManyToOne({entity:'UserInfo'}) - @JoinColumn({ - name:'owner_id', - refName:'user_id', - nullable:true - }) - private owner:UserInfo; - - @ManyToOne({entity:'UserInfo'}) - @JoinColumn({ - name:'manager_id', - refName:'user_id', - nullable:true - }) - private manager:UserInfo; - - @Column({ - name:'shop_name', - type:'string', - nullable:true, - length:32 - }) - private shopName:string; - - @Column({ - name:'address', - type:'string', - nullable:true, - length:128 - }) - private address:string; - - constructor(idValue?:number){ - super(); - this.shopId = idValue; - } - public getShopId():number{ - return this.shopId; - } - public setShopId(value:number){ - this.shopId = value; - } - - public async getOwner():Promise{ - return await EntityProxy.get(this,'owner'); - } - public setOwner(value:UserInfo){ - this.owner = value; - } - - public async getManager():Promise{ - return await EntityProxy.get(this,'manager'); - } - public setManager(value:UserInfo){ - this.manager = value; - } - - public getShopName():string{ - return this.shopName; - } - public setShopName(value:string){ - this.shopName = value; - } - - public getAddress():string{ - return this.address; - } - public setAddress(value:string){ - this.address = value; - } - -} \ No newline at end of file diff --git a/test/app/module/dao/entity/user.ts b/test/app/module/dao/entity/user.ts deleted file mode 100644 index 55a1e903640a1dad44013c7c27af7657ed340c17..0000000000000000000000000000000000000000 --- a/test/app/module/dao/entity/user.ts +++ /dev/null @@ -1,82 +0,0 @@ -import {BaseEntity,Entity,Column,Id,OneToMany,EntityProxy, OneToOne} from 'relaen'; -import {GroupUser} from './groupuser'; -import {UserInfo} from './userinfo'; - -@Entity("t_user",'test') -export class User extends BaseEntity{ - @Id() - @Column({ - name:'user_id', - type:'int', - nullable:false - }) - private userId:number; - - @Column({ - name:'user_name', - type:'string', - nullable:true, - length:32 - }) - private userName:string; - - @Column({ - name:'user_pwd', - type:'string', - nullable:true, - length:32 - }) - private userPwd:string; - - @OneToMany({ - entity:'GroupUser', - mappedBy:'user' - }) - private groupUsers:Array; - - @OneToOne({ - entity:'UserInfo', - mappedBy:'user' - }) - private userInfo:Array; - - constructor(idValue?:number){ - super(); - this.userId = idValue; - } - public getUserId():number{ - return this.userId; - } - public setUserId(value:number){ - this.userId = value; - } - - public getUserName():string{ - return this.userName; - } - public setUserName(value:string){ - this.userName = value; - } - - public getUserPwd():string{ - return this.userPwd; - } - public setUserPwd(value:string){ - this.userPwd = value; - } - - public async getGroupUsers():Promise>{ - return await EntityProxy.get(this,'groupUsers'); - } - public setGroupUsers(value:Array){ - this.groupUsers = value; - } - - public async getUserInfo():Promise>{ - return await EntityProxy.get(this,'userInfo'); - } - public setUserInfo(value:Array){ - this.userInfo = value; - } - -} \ No newline at end of file diff --git a/test/app/module/dao/entity/userinfo.ts b/test/app/module/dao/entity/userinfo.ts deleted file mode 100644 index bc380c18b4e292b832d2025aa76019464c3e8d35..0000000000000000000000000000000000000000 --- a/test/app/module/dao/entity/userinfo.ts +++ /dev/null @@ -1,126 +0,0 @@ -import {BaseEntity,Entity,Column,Id,JoinColumn,OneToOne,OneToMany,EntityProxy} from 'relaen'; -import {User} from './user'; -import {Shop} from './shop'; - -@Entity("t_user_info",'test') -export class UserInfo extends BaseEntity{ - @Id() - @Column({ - name:'user_id', - type:'int', - nullable:false - }) - private userId:number; - - @OneToOne({entity:'User'}) - @JoinColumn({ - name:'user_id', - refName:'user_id', - nullable:true - }) - private user:User; - - @Column({ - name:'real_name', - type:'string', - nullable:true, - length:64 - }) - private realName:string; - - @Column({ - name:'age', - type:'int', - nullable:true - }) - private age:number; - - @Column({ - name:'sexy', - type:'string', - nullable:true, - length:1 - }) - private sexy:string; - - @Column({ - name:'remarks', - type:'string', - nullable:true, - length:256 - }) - private remarks:string; - - @OneToMany({ - entity:'Shop', - mappedBy:'owner' - }) - private ownShops:Array; - - @OneToMany({ - entity:'Shop', - mappedBy:'manager' - }) - private manageShops:Array; - - constructor(idValue?:number){ - super(); - this.userId = idValue; - } - public getUserId():number{ - return this.userId; - } - public setUserId(value:number){ - this.userId = value; - } - - public async getUser():Promise{ - return await EntityProxy.get(this,'user'); - } - public setUser(value:User){ - this.user = value; - } - - public getRealName():string{ - return this.realName; - } - public setRealName(value:string){ - this.realName = value; - } - - public getAge():number{ - return this.age; - } - public setAge(value:number){ - this.age = value; - } - - public getSexy():string{ - return this.sexy; - } - public setSexy(value:string){ - this.sexy = value; - } - - public getRemarks():string{ - return this.remarks; - } - public setRemarks(value:string){ - this.remarks = value; - } - - public async getOwnShops():Promise>{ - return await EntityProxy.get(this,'ownShops'); - } - public setOwnShops(value:Array){ - this.ownShops = value; - } - - public async getManageShops():Promise>{ - return await EntityProxy.get(this,'manageShops'); - } - public setManageShops(value:Array){ - this.manageShops = value; - } - -} \ No newline at end of file diff --git a/test/app/module/dao/impl/ormfactory.ts b/test/app/module/dao/impl/ormfactory.ts deleted file mode 100644 index ce7f12e5a6420533e9a5744110db96a5af4d8c24..0000000000000000000000000000000000000000 --- a/test/app/module/dao/impl/ormfactory.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { createConnection, Connection } from "typeorm"; - -export class OrmFactory{ - - static async getConnection():Promise{ - return await createConnection({ - "type":"mysql", - "host":"localhost", - "port":3306, - "username":"root", - "password":"field", - "database":"codement", - "entities": [ - "build/test/app/module/dao/pojo/*.js" - ], - "logging":true, - "extra":{ - "connectionLimit":10 - } - }); - } -} \ No newline at end of file diff --git a/test/app/module/dao/initdata.sql b/test/app/module/dao/initdata.sql deleted file mode 100644 index 0affddbdcdcfa4d18a159a2870a685c799f9ff3a..0000000000000000000000000000000000000000 --- a/test/app/module/dao/initdata.sql +++ /dev/null @@ -1,41 +0,0 @@ -insert into t_user(user_id,user_name,user_pwd,enabled) values(1,'field','123456',1); -insert into t_user(user_id,user_name,user_pwd,enabled) values(2,'yang','123456',1); -insert into t_user(user_id,user_name,user_pwd,enabled) values(3,'zhangs','123456',1); -insert into t_user(user_id,user_name,user_pwd,enabled) values(4,'tangb','123456',1); -insert into t_user(user_id,user_name,user_pwd,enabled) values(5,'lis','123456',1); - -insert into t_authority(authority_id,authority) values(1,'auth1'); -insert into t_authority(authority_id,authority) values(2,'auth2'); -insert into t_authority(authority_id,authority) values(3,'auth3'); -insert into t_authority(authority_id,authority) values(4,'auth4'); - -insert into t_group(group_id,group_name) values(1,'admin'); -insert into t_group(group_id,group_name) values(2,'custom'); - -insert into t_resource(resource_id,url) values(1,'/getuserinfo'); -insert into t_resource(resource_id,url) values(2,'/showuserinfo'); -insert into t_resource(resource_id,url) values(3,'/upload'); - - -insert into t_resource_authority(resource_authority_id,resource_id,authority_id) values (1,1,1); -insert into t_resource_authority(resource_authority_id,resource_id,authority_id) values (2,1,2); -insert into t_resource_authority(resource_authority_id,resource_id,authority_id) values (3,1,3); -insert into t_resource_authority(resource_authority_id,resource_id,authority_id) values (4,1,4); -insert into t_resource_authority(resource_authority_id,resource_id,authority_id) values (5,1,1); -insert into t_resource_authority(resource_authority_id,resource_id,authority_id) values (6,2,2); -insert into t_resource_authority(resource_authority_id,resource_id,authority_id) values (7,2,3); -insert into t_resource_authority(resource_authority_id,resource_id,authority_id) values (8,2,4); -insert into t_resource_authority(resource_authority_id,resource_id,authority_id) values (9,3,1); - -insert into t_group_user(group_user_id,group_id,user_id) values(1,1,1); -insert into t_group_user(group_user_id,group_id,user_id) values(2,2,2); -insert into t_group_user(group_user_id,group_id,user_id) values(3,2,3); -insert into t_group_user(group_user_id,group_id,user_id) values(4,2,4); - -insert into t_group_authority(group_authority_id,group_id,authority_id) values(1,1,1); -insert into t_group_authority(group_authority_id,group_id,authority_id) values(2,1,2); -insert into t_group_authority(group_authority_id,group_id,authority_id) values(3,1,3); -insert into t_group_authority(group_authority_id,group_id,authority_id) values(4,1,4); -insert into t_group_authority(group_authority_id,group_id,authority_id) values(5,2,2); -insert into t_group_authority(group_authority_id,group_id,authority_id) values(6,2,3); -insert into t_group_authority(group_authority_id,group_id,authority_id) values(7,2,4); diff --git a/test/app/module/dao/pojo/authority.ts b/test/app/module/dao/pojo/authority.ts deleted file mode 100644 index f1c94f7e7f15de56a30673a7e5437b975f640bc8..0000000000000000000000000000000000000000 --- a/test/app/module/dao/pojo/authority.ts +++ /dev/null @@ -1,37 +0,0 @@ -// import {BaseEntity,Column,Entity,OneToMany, JoinTable, ManyToMany, PrimaryGeneratedColumn} from "typeorm"; -// import { Group } from "./group"; -// import { Resource } from "./resource"; -// import { GroupAuthority } from "./groupauthority"; -// import { ResourceAuthority } from "./resourceauthority"; - -// @Entity("t_authority" ,{schema:"codement" } ) -// export class Authority extends BaseEntity{ - -// @PrimaryGeneratedColumn() -// @Column("bigint",{ -// nullable:false, -// primary:true, -// name:"authority_id" -// }) -// authorityId:number; - - -// @Column("varchar",{ -// nullable:false, -// length:50, -// name:"authority" -// }) -// authority:string; - -// @OneToMany(()=>GroupAuthority, (groupAuthority: GroupAuthority)=>groupAuthority.authority,{ onDelete: 'CASCADE' ,onUpdate: 'CASCADE' }) -// tGroupAuthoritys:GroupAuthority[]; - -// @OneToMany(()=>ResourceAuthority, (resourceAuthority: ResourceAuthority)=>resourceAuthority.authority,{ onDelete: 'CASCADE' ,onUpdate: 'CASCADE' }) -// resourceAuthorities:ResourceAuthority[]; - -// // @ManyToMany(type=>Group,group=>group.authorities) -// // groups:Group[]; - -// // @ManyToMany(type=>Resource,resource=>resource.authorities) -// // resources:Resource[]; -// } diff --git a/test/app/module/dao/pojo/group.ts b/test/app/module/dao/pojo/group.ts deleted file mode 100644 index 5e6bb7aa81bf5b5c9d1087704a34ab1b1e645ae0..0000000000000000000000000000000000000000 --- a/test/app/module/dao/pojo/group.ts +++ /dev/null @@ -1,44 +0,0 @@ -// import {BaseEntity,Column,Entity,Index,JoinColumn,JoinTable,ManyToMany,ManyToOne,OneToMany,OneToOne,PrimaryColumn,PrimaryGeneratedColumn,RelationId} from "typeorm"; -// import { User } from "./user"; -// import { Authority } from "./authority"; -// import { GroupAuthority } from "./groupauthority"; -// import { GroupUser } from "./groupuser"; - -// @Entity("t_group" ,{schema:"codement" } ) -// export class Group extends BaseEntity{ -// @PrimaryGeneratedColumn() -// @Column("bigint",{ -// nullable:false, -// primary:true, -// name:"group_id" -// }) -// groupId:number; - -// @Column("varchar",{ -// nullable:true, -// length:50, -// name:"group_name" -// }) -// groupName:string | null; - - -// @Column("varchar",{ -// nullable:true, -// length:200, -// name:"remarks" -// }) -// remarks:string | null; - -// @OneToMany(()=>GroupUser, (groupUser: GroupUser)=>groupUser.group,{ onDelete: 'CASCADE' ,onUpdate: 'CASCADE' }) -// groupUsers:GroupUser[]; - -// @OneToMany(()=>GroupAuthority, (groupAuthority: GroupAuthority)=>groupAuthority.group,{ onDelete: 'CASCADE' ,onUpdate: 'CASCADE' }) -// groupAuthorities:GroupAuthority[]; - -// // @ManyToMany(type=>User,user=>user.groups) -// // users:User[]; - -// // @ManyToMany(type=>Authority,authority=>authority.groups) -// // @JoinTable() -// // authorities:Promise; -// } diff --git a/test/app/module/dao/pojo/groupauthority.ts b/test/app/module/dao/pojo/groupauthority.ts deleted file mode 100644 index d57f736388bd982f231e5bf4381840cb61072ec1..0000000000000000000000000000000000000000 --- a/test/app/module/dao/pojo/groupauthority.ts +++ /dev/null @@ -1,30 +0,0 @@ -// import {BaseEntity,Column,Entity,Index,JoinColumn,JoinTable,ManyToMany,ManyToOne,OneToMany,OneToOne,PrimaryColumn,PrimaryGeneratedColumn,RelationId} from "typeorm"; -// import {Authority} from "./authority"; -// import {Group} from "./group"; - - -// @Entity("t_group_authority" ,{schema:"codement" } ) -// @Index("FK_GROUPAUTH_REF_AUTH",["authority",]) -// @Index("FK_GROUP_AU_REF_GROUP",["group",]) -// export class GroupAuthority { - -// @Column("bigint",{ -// nullable:false, -// primary:true, -// name:"group_authority_id" -// }) -// group_authority_id:number; - - - -// @ManyToOne(()=>Authority, (authority: Authority)=>authority.tGroupAuthoritys,{ nullable:false,onDelete: 'CASCADE',onUpdate: 'CASCADE' ,eager:true}) -// @JoinColumn({ name:'authority_id'}) -// authority:Authority | null; - - - -// @ManyToOne(()=>Group, (group: Group)=>group.groupAuthorities,{ onDelete: 'CASCADE',onUpdate: 'CASCADE' ,eager:true}) -// @JoinColumn({ name:'group_id'}) -// group:Group | null; - -// } diff --git a/test/app/module/dao/pojo/groupuser.ts b/test/app/module/dao/pojo/groupuser.ts deleted file mode 100644 index 138b34b84d65f6aca31eaaee49a0099106d7774d..0000000000000000000000000000000000000000 --- a/test/app/module/dao/pojo/groupuser.ts +++ /dev/null @@ -1,30 +0,0 @@ -// import {BaseEntity,Column,Entity,Index,JoinColumn,JoinTable,ManyToMany,ManyToOne,OneToMany,OneToOne,PrimaryColumn,PrimaryGeneratedColumn,RelationId} from "typeorm"; -// import { User } from "./user"; -// import { Group } from "./group"; - - -// @Entity("t_group_user" ,{schema:"codement" } ) -// @Index("FK_GROUP_USER_REF_GROUP",["group",]) -// @Index("FK_GROUP_USER_REF_USER",["user",]) -// export class GroupUser { - -// @Column("bigint",{ -// nullable:false, -// primary:true, -// name:"group_user_id" -// }) -// groupUserId:number; - - - -// @ManyToOne(()=>User, (user: User)=>user.groupUsers,{ onDelete: 'CASCADE',onUpdate: 'CASCADE' ,eager:true}) -// @JoinColumn({ name:'user_id'}) -// user:User | null; - - - -// @ManyToOne(()=>Group, (group: Group)=>group.groupUsers,{ onDelete: 'CASCADE',onUpdate: 'CASCADE' ,eager:true}) -// @JoinColumn({ name:'group_id'}) -// group:Group | null; - -// } diff --git a/test/app/module/dao/pojo/resource.ts b/test/app/module/dao/pojo/resource.ts deleted file mode 100644 index b4b867c839381e0037d59eb848ce9ff79fcd59f8..0000000000000000000000000000000000000000 --- a/test/app/module/dao/pojo/resource.ts +++ /dev/null @@ -1,35 +0,0 @@ -// import {BaseEntity,Column,Entity,Index,JoinColumn,JoinTable,ManyToMany,ManyToOne,OneToMany,OneToOne,PrimaryColumn,PrimaryGeneratedColumn,RelationId} from "typeorm"; -// import { Authority } from "./authority"; -// import { ResourceAuthority } from "./resourceauthority"; - -// @Entity("t_resource" ,{schema:"codement" } ) -// export class Resource extends BaseEntity{ - -// @PrimaryGeneratedColumn() -// @Column("bigint",{ -// nullable:false, -// primary:true, -// name:"resource_id" -// }) -// resourceId:number; - -// @Column("varchar",{ -// nullable:true, -// length:500, -// name:"url" -// }) -// url:string | null; - - -// @Column("varchar",{ -// nullable:true, -// length:50, -// name:"title" -// }) -// title:string | null; - -// @OneToMany(()=>ResourceAuthority, (resourceAuthority: ResourceAuthority)=>resourceAuthority.authority,{ onDelete: 'CASCADE' ,onUpdate: 'CASCADE' }) -// resourceAuthorities:ResourceAuthority[]; -// // @ManyToMany(type=>Authority,authority=>authority.resources) -// // authorities:Authority[]; -// } diff --git a/test/app/module/dao/pojo/resourceauthority.ts b/test/app/module/dao/pojo/resourceauthority.ts deleted file mode 100644 index 98ea2f90fd3f3bede593fe9bca571579399c0de2..0000000000000000000000000000000000000000 --- a/test/app/module/dao/pojo/resourceauthority.ts +++ /dev/null @@ -1,30 +0,0 @@ -// import {BaseEntity,Column,Entity,Index,JoinColumn,JoinTable,ManyToMany,ManyToOne,OneToMany,OneToOne,PrimaryColumn,PrimaryGeneratedColumn,RelationId} from "typeorm"; -// import { Authority } from "./authority"; -// import { Resource } from "./resource"; - - -// @Entity("t_resource_authority" ,{schema:"codement" } ) -// @Index("FK_RES_AUTH_REF_AUTH",["authority",]) -// @Index("FK_RES_AUTH_REF_RES",["resource",]) -// export class ResourceAuthority { - -// @Column("bigint",{ -// nullable:false, -// primary:true, -// name:"resource_authority_id" -// }) -// resourceAuthorityId:number; - - - -// @ManyToOne(()=>Authority, (authority: Authority)=>authority.resourceAuthorities,{ onDelete: 'CASCADE',onUpdate: 'CASCADE',eager:true }) -// @JoinColumn({ name:'authority_id'}) -// authority:Authority | null; - - - -// @ManyToOne(()=>Resource, (resource: Resource)=>resource.resourceAuthorities,{ onDelete: 'CASCADE',onUpdate: 'CASCADE' ,eager:true}) -// @JoinColumn({ name:'resource_id'}) -// resource:Resource | null; - -// } diff --git a/test/app/module/dao/pojo/user.ts b/test/app/module/dao/pojo/user.ts deleted file mode 100644 index 43d3aa443253143a2259673e4d84b114c3759d4b..0000000000000000000000000000000000000000 --- a/test/app/module/dao/pojo/user.ts +++ /dev/null @@ -1,53 +0,0 @@ -// import {BaseEntity,Column,Entity,Index,JoinColumn,JoinTable,ManyToMany,ManyToOne,OneToMany,OneToOne,PrimaryColumn,PrimaryGeneratedColumn,RelationId} from "typeorm"; -// import { Group } from "./group"; -// import { GroupUser } from "./groupuser"; - -// @Entity("t_user" ,{schema:"codement" } ) -// export class User extends BaseEntity{ - -// @PrimaryGeneratedColumn() -// @Column("bigint",{ -// nullable:false, -// primary:true, -// name:"user_id" -// }) -// userId:number; - - -// @Column("varchar",{ -// nullable:true, -// length:50, -// name:"user_name" -// }) -// userName:string | null; - - -// @Column("varchar",{ -// nullable:true, -// length:32, -// name:"user_pwd" -// }) -// userPwd:string | null; - - -// @Column("tinyint",{ -// nullable:true, -// width:1, -// name:"enabled" -// }) -// enabled:boolean | null; - -// @OneToMany(()=>GroupUser, (groupUser: GroupUser)=>groupUser.user,{ onDelete: 'CASCADE' ,onUpdate: 'CASCADE' }) -// groupUsers:GroupUser[]; -// // @ManyToMany(type=>Group,group=>group.users) -// // @JoinTable({ -// // name:'t_group_user', -// // joinColumn:{ -// // name:'user_id' -// // }, -// // inverseJoinColumn:{ -// // name:'group_id' -// // } -// // }) -// // groups:Group[]; -// } diff --git a/test/app/module/dao/pojosequelize/authority.ts b/test/app/module/dao/pojosequelize/authority.ts deleted file mode 100644 index 59dc757f9797bfbda3ab2364490cabe105da9571..0000000000000000000000000000000000000000 --- a/test/app/module/dao/pojosequelize/authority.ts +++ /dev/null @@ -1,19 +0,0 @@ -// import{Table,Column,Model,HasMany} from 'sequelize-typescript'; -// import ResourceAuthority from './resourceauthority'; - - -// @Table({tableName:'t_authority'}) -// export default class Authority extends Model{ -// @Column({ -// primaryKey:true, -// field:'authority_id' -// }) -// authorityId:number; - -// @Column -// authority:string; - -// @HasMany(()=>ResourceAuthority) -// resourceAuthorities:ResourceAuthority[]; -// } -// // export{Authority} diff --git a/test/app/module/dao/pojosequelize/resource.ts b/test/app/module/dao/pojosequelize/resource.ts deleted file mode 100644 index 3e05b6133a3784cee4eb575c196ffe7da5993547..0000000000000000000000000000000000000000 --- a/test/app/module/dao/pojosequelize/resource.ts +++ /dev/null @@ -1,19 +0,0 @@ -// import{Table,Column,Model,HasMany} from 'sequelize-typescript'; -// import ResourceAuthority from './resourceauthority'; - -// @Table({tableName:'t_resource'}) - -// export default class Resource extends Model{ -// @Column({ -// primaryKey:true, -// field:'resource_id' -// }) -// resourceId:number; - -// @Column -// url:string; - -// @HasMany(()=>ResourceAuthority) -// resourceAuthorities:ResourceAuthority[]; -// } -// // export{Resource} diff --git a/test/app/module/dao/pojosequelize/resourceauthority.ts b/test/app/module/dao/pojosequelize/resourceauthority.ts deleted file mode 100644 index f5c31181a27505f54fb384a9a7e0a519953915d8..0000000000000000000000000000000000000000 --- a/test/app/module/dao/pojosequelize/resourceauthority.ts +++ /dev/null @@ -1,33 +0,0 @@ -// import{Table,Column,Model,HasMany, ForeignKey, BelongsTo} from 'sequelize-typescript'; -// import Resource from './resource'; -// import Authority from './authority'; - -// @Table({tableName:'t_resource_authority'}) - -// export default class ResourceAuthority extends Model{ -// @Column({ -// primaryKey:true, -// field:'resource_authority_id' -// }) -// resourceAuthorityId:number; - -// // @ForeignKey(()=>Resource) -// @Column({ -// field:'resource_id' -// }) -// resourceId:number; - -// // @BelongsTo(()=>Resource) -// resource:Resource - -// @ForeignKey(()=>Authority) -// @Column({ -// field:'authority_id' -// }) -// authorityId:number; - -// @BelongsTo(()=>Authority) -// authority:Authority; -// } - -// // export {ResourceAuthority} \ No newline at end of file diff --git a/test/app/module/filter/nodomfilter.ts b/test/app/module/filter/nodomfilter.ts deleted file mode 100644 index 415b6691e684bae360e829d1c6984a9e045fc254..0000000000000000000000000000000000000000 --- a/test/app/module/filter/nodomfilter.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { Instance, WebFilter } from "../../../../core/tools/decorator"; - -@Instance({ - name:'nodomFilter' -}) -class NodomFilter{ - @WebFilter(/.*/,1) - do(request,response){ - const url = require("url"); - let path = url.parse(request.url).pathname; - - if(path.indexOf('/test/router') === 0){ - console.log('nodom filter wrong',path); - } else{ - console.log('nodom filter',path); - } - - return true; - } -} - -export{NodomFilter}; \ No newline at end of file diff --git a/test/app/module/filter/pathfilter.ts b/test/app/module/filter/pathfilter.ts deleted file mode 100644 index b2a2267fa792422fb9dd00922793ba154d2bb3a9..0000000000000000000000000000000000000000 --- a/test/app/module/filter/pathfilter.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { Instance, WebFilter, Inject } from "../../../../core/tools/decorator"; -import { UserService } from "../service/userservice"; - -@Instance({ - name:'pathFilter' -}) -class PathFilter{ - @Inject("userService") - us:UserService; - @WebFilter(/\/user\/.*/,1000) - do2(request,response){ - console.log(request,response); - this.us.sayHello(); - const url = require("url"); - let path = url.parse(request.url).pathname; - console.log('pathfilter',path); - return true; - } -} - -export{PathFilter}; \ No newline at end of file diff --git a/test/app/module/model/mbase.ts b/test/app/module/model/mbase.ts deleted file mode 100644 index 9aa53326bd428679840f3b898e3bc208de43de05..0000000000000000000000000000000000000000 --- a/test/app/module/model/mbase.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { BaseModel } from "../../../../core/tools/model"; -import { DataType, DataValidator } from "../../../../core/tools/decorator"; - -export class MBase extends BaseModel{ - /** - * id串 1,2,3 - */ - ids:string; - - /** - * 页号 - */ - @DataType('int') - page:number; - - /** - * 页面大小 - */ - @DataType('int') - rows: number; - - /** - * 排序 - */ - // TODO 验证排序格式{field: userNo, type: desc} - orders: object; - - @DataValidator({ - in:[['F','M']] - }) - sexy:string; -} \ No newline at end of file diff --git a/test/app/module/model/muser.ts b/test/app/module/model/muser.ts deleted file mode 100644 index 7a047cf8b5848c3d265a2693d3714d34b7251c05..0000000000000000000000000000000000000000 --- a/test/app/module/model/muser.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { DataType, DataValidator} from "../../../../core/tools/decorator"; -import { MBase } from "./mbase"; - -export class MUser extends MBase{ - - @DataType('int') - @DataValidator({ - min:[2] - }) - age:number; - - @DataValidator({ - in:[['F','M']] - }) - sexy:string; - - @DataType('string') - @DataValidator({ - betweenLength:[2,20] - }) - userName:string; - - @DataType('string') - @DataValidator({ - betweenLength:[6,20] - }) - pwd:string; - - @DataType('string') - @DataValidator({ - mobile:[] - }) - myMobile:string; - - @DataType('string') - @DataValidator({ - email:[] - }) - myEmail:string; - - @DataType('string') - @DataValidator({ - url:[] - }) - myHome:string; - - @DataType('string') - @DataValidator({ - betweenLength:[6,20], - checkPwd:[] - }) - pwd2:string; - - @DataType('int') - userTypeId:number; - - @DataType('string') - @DataValidator({ - url:[] - }) - url:string; - /** - * 自定义验证 - * @param value - */ - checkPwd(value){ - if(this['pwd'] === value){ - return null; - } - return "密码和验证密码不一致"; - } - - check(value,arr){ - if(arr.includes(value)){ - return null; - } - return ""; - } -} \ No newline at end of file diff --git a/test/app/module/model/musertype.ts b/test/app/module/model/musertype.ts deleted file mode 100644 index cbbf52234f69dfeba1929798f89d36ff0b194a44..0000000000000000000000000000000000000000 --- a/test/app/module/model/musertype.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { BaseModel } from "../../../../core/tools/model"; -import { DataType, DataValidator} from "../../../../core/tools/decorator"; -import { MBase } from "./mbase"; - -export class MUserType extends MBase{ - - @DataType('int') - userTypeId:number; - - @DataType('string') - @DataValidator({ - betweenLength:[2,20] - }) - userTypeName:string; - - @DataType('string') - url:string; - - @DataValidator({ - in:[['X','Y']] - }) - sexy:string; -} \ No newline at end of file diff --git a/test/app/module/route/commodityroute.ts b/test/app/module/route/commodityroute.ts deleted file mode 100644 index 359a127469572a2f9a6d7d005c04de9f03be6674..0000000000000000000000000000000000000000 --- a/test/app/module/route/commodityroute.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { Inject, Instance, Router, Route } from "../../../../core/tools/decorator"; -import { UserService } from "../service/userservice"; -import { BaseRoute } from "../../../../core/main/route/baseroute"; -import { DataImpl } from "../service/dataimpl"; - -/** - * 测试用户 - */ -@Router({ - namespace:'/commodity', - path:'*' -}) - -export class CommodityRoute extends BaseRoute{ - - getinfo(params){ - let pageno = params.pageno; - let pagesize = params.pagesize; - if(!pageno || !pagesize){ - // pageno = 1; - // pagesize = 10; - return; - }else{ - if(pageno){ - pageno = parseInt(pageno); - } - if(pagesize){ - pagesize = parseInt(pagesize); - } - } - - let index = (pageno-1) * pagesize; - return { - "vip":0.9, - "total":33, - "rows":[ - {"id":index+1,"name":"女款韩版休闲圆领宽松运动风条纹撞色短袖连衣裙","price":46,"oprice":399,"discount":0.12,"head":"imgs/1.jpg","desc":"女款韩版休闲圆领宽松运动风条纹撞色短袖连衣裙女款韩版休闲圆领宽松运动风条纹撞色短袖连衣裙女款韩版休闲圆领宽松运动风条纹撞色短袖连衣裙女款韩版休闲圆领宽松运动风条纹撞色短袖连衣裙"}, - {"id":index+2,"name":"夏季新款韩版时尚气质蝴蝶结圆领收腰连衣裙夏连衣裙女裙子","price":44,"oprice":478,"discount":0.09,"head":"imgs/2.jpg","desc":"夏季新款韩版时尚气质蝴蝶结圆领收腰连衣裙夏连衣裙女裙子夏季新款韩版时尚气质蝴蝶结圆领收腰连衣裙夏连衣裙女裙子夏季新款韩版时尚气质蝴蝶结圆领收腰连衣裙夏连衣裙女裙子夏季新款韩版时尚气质蝴蝶结圆领收腰连衣裙夏连衣裙女裙子"}, - {"id":index+3,"name":"夏新款显瘦仙女圆领直筒修身短袖女士时尚连衣裙","price":56,"oprice":499,"discount":0.12,"head":"imgs/3.jpg","desc":"夏新款显瘦仙女圆领直筒修身短袖女士时尚连衣裙夏新款显瘦仙女圆领直筒修身短袖女士时尚连衣裙夏新款显瘦仙女圆领直筒修身短袖女士时尚连衣裙夏新款显瘦仙女圆领直筒修身短袖女士时尚连衣裙"}, - {"id":index+4,"name":"2020可甜可盐系穿搭复古衬衫格子拼接假两件连衣裙气质收腰裙子","price":46,"oprice":399,"discount":0.12,"head":"imgs/4.jpg","desc":"2020可甜可盐系穿搭复古衬衫格子拼接假两件连衣裙气质收腰裙子2020可甜可盐系穿搭复古衬衫格子拼接假两件连衣裙气质收腰裙子2020可甜可盐系穿搭复古衬衫格子拼接假两件连衣裙气质收腰裙子2020可甜可盐系穿搭复古衬衫格子拼接假两件连衣裙气质收腰裙子"}, - {"id":index+5,"name":"【春装连衣裙】个性纯色舒适显瘦气质复古百褶束腰设计款简约长裙个性纯色舒适显瘦气质复古百褶束腰设计款简约长裙个性纯色舒适显瘦气质复古百褶束腰设计款简约长裙个性纯色舒适显瘦气质复古百褶束腰设计款简约长裙个性纯色舒适显瘦气质复古百褶束腰设计款简约长裙","price":59,"oprice":668,"discount":0.09,"head":"imgs/5.jpg","desc":"【春装连衣裙】个性纯色舒适显瘦气质复古百褶束腰设计款简约长裙【春装连衣裙】个性纯色舒适显瘦气质复古百褶束腰设计款简约长裙【春装连衣裙】个性纯色舒适显瘦气质复古百褶束腰设计款简约长裙"}, - {"id":index+6,"name":"2020夏装新款气质红色露肩宽松休闲遮肉女士连衣裙","price":95,"oprice":519,"discount":0.18,"head":"imgs/6.jpg","desc":"2020夏装新款气质红色露肩宽松休闲遮肉女士连衣裙2020夏装新款气质红色露肩宽松休闲遮肉女士连衣裙2020夏装新款气质红色露肩宽松休闲遮肉女士连衣裙2020夏装新款气质红色露肩宽松休闲遮肉女士连衣裙"}, - {"id":index+7,"name":"【2020夏装新款】女时尚森系V领修身桔梗法式雪纺连衣裙","price":168,"oprice":798,"discount":0.22,"head":"imgs/7.jpg","desc":"【2020夏装新款】女时尚森系V领修身桔梗法式雪纺连衣裙【2020夏装新款】女时尚森系V领修身桔梗法式雪纺连衣裙【2020夏装新款】女时尚森系V领修身桔梗法式雪纺连衣裙【2020夏装新款】女时尚森系V领修身桔梗法式雪纺连衣裙"}, - {"id":index+8,"name":"七格格泡泡袖连衣裙女2020夏季新款宽松设计感可盐可甜裙子","price":149,"oprice":529,"discount":0.29,"head":"imgs/8.jpg","desc":"七格格泡泡袖连衣裙女2020夏季新款宽松设计感可盐可甜裙子七格格泡泡袖连衣裙女2020夏季新款宽松设计感可盐可甜裙子七格格泡泡袖连衣裙女2020夏季新款宽松设计感可盐可甜裙子七格格泡泡袖连衣裙女2020夏季新款宽松设计感可盐可甜裙子七格格泡泡袖连衣裙女2020夏季新款宽松设计感可盐可甜裙子七格格泡泡袖连衣裙女2020夏季新款宽松设计感可盐可甜裙子"}, - {"id":index+9,"name":"2020夏季气质雪纺中长裙沙滩裙子中长款性感V领喇叭袖连衣裙女1099","price":66,"oprice":269,"discount":0.25,"head":"imgs/9.jpg","desc":"2020夏季气质雪纺中长裙沙滩裙子中长款性感V领喇叭袖连衣裙女10992020夏季气质雪纺中长裙沙滩裙子中长款性感V领喇叭袖连衣裙女10992020夏季气质雪纺中长裙沙滩裙子中长款性感V领喇叭袖连衣裙女10992020夏季气质雪纺中长裙沙滩裙子中长款性感V领喇叭袖连衣裙女10992020夏季气质雪纺中长裙沙滩裙子中长款性感V领喇叭袖连衣裙女1099"}, - {"id":index+10,"name":"夏季新品波点v领雪纺连衣裙女收腰显瘦女士连衣裙夏女","price":79,"oprice":979,"discount":0.09,"head":"imgs/10.jpg","desc":"夏季新品波点v领雪纺连衣裙女收腰显瘦女士连衣裙夏女夏季新品波点v领雪纺连衣裙女收腰显瘦女士连衣裙夏女夏季新品波点v领雪纺连衣裙女收腰显瘦女士连衣裙夏女夏季新品波点v领雪纺连衣裙女收腰显瘦女士连衣裙夏女夏季新品波点v领雪纺连衣裙女收腰显瘦女士连衣裙夏女"}, - {"id":index+11,"name":"2020可甜可盐系穿搭复古衬衫格子拼接假两件连衣裙气质收腰裙子","price":46,"oprice":399,"discount":0.12,"head":"imgs/4.jpg","desc":"2020可甜可盐系穿搭复古衬衫格子拼接假两件连衣裙气质收腰裙子2020可甜可盐系穿搭复古衬衫格子拼接假两件连衣裙气质收腰裙子2020可甜可盐系穿搭复古衬衫格子拼接假两件连衣裙气质收腰裙子2020可甜可盐系穿搭复古衬衫格子拼接假两件连衣裙气质收腰裙子"}, - {"id":index+12,"name":"【春装连衣裙】个性纯色舒适显瘦气质复古百褶束腰设计款简约长裙个性纯色舒适显瘦气质复古百褶束腰设计款简约长裙个性纯色舒适显瘦气质复古百褶束腰设计款简约长裙个性纯色舒适显瘦气质复古百褶束腰设计款简约长裙个性纯色舒适显瘦气质复古百褶束腰设计款简约长裙","price":59,"oprice":668,"discount":0.09,"head":"imgs/5.jpg","desc":"【春装连衣裙】个性纯色舒适显瘦气质复古百褶束腰设计款简约长裙【春装连衣裙】个性纯色舒适显瘦气质复古百褶束腰设计款简约长裙【春装连衣裙】个性纯色舒适显瘦气质复古百褶束腰设计款简约长裙"}, - {"id":index+13,"name":"2020夏装新款气质红色露肩宽松休闲遮肉女士连衣裙","price":95,"oprice":519,"discount":0.18,"head":"imgs/6.jpg","desc":"2020夏装新款气质红色露肩宽松休闲遮肉女士连衣裙2020夏装新款气质红色露肩宽松休闲遮肉女士连衣裙2020夏装新款气质红色露肩宽松休闲遮肉女士连衣裙2020夏装新款气质红色露肩宽松休闲遮肉女士连衣裙"}, - ] - } - } - - -} \ No newline at end of file diff --git a/test/app/module/route/rbase.ts b/test/app/module/route/rbase.ts deleted file mode 100644 index c9c6e4c69ae92e459e7fba65634fa278835e7e77..0000000000000000000000000000000000000000 --- a/test/app/module/route/rbase.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { BaseRoute } from "../../../../core/main/route/baseroute"; -import { DataModel } from "../../../../core/tools/decorator"; - -export class RBase extends BaseRoute{ - timestamp = { - createdFeild: 'createdAt', - updatedFeild: 'updatedAt' - }; - - constructor() { - super(); - - } - public getPage(){ - return this.model['page']; - } -} \ No newline at end of file diff --git a/test/app/module/route/uploadroute.ts b/test/app/module/route/uploadroute.ts deleted file mode 100644 index 0391f65be2bc4adbc54eee92dc10d6c4d4133534..0000000000000000000000000000000000000000 --- a/test/app/module/route/uploadroute.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { BaseRoute } from "../../../../core/main/route/baseroute"; -import { Route, Router } from "../../../../core/tools/decorator"; -import { App } from "../../../../core/tools/application"; - -@Router() -export class UploadRoute extends BaseRoute{ - @Route('/upload') - upload(data){ - let rows = this.model.file; - let path = App.path.resolve(''); - if(Array.isArray(rows)){ - let ra = []; - let i=1; - for(let r of rows){ - let relPath = r.path.substr(path.length); - ra.push({ - id:i++, - url:'http://localhost:3000' + relPath, - fileName:r.fileName - }); - } - return{ - rows:ra - } - }else{ - let relPath = rows.path.substr(path.length); - return { - id:(Math.random() * 20)|0, - url:'http://localhost:3000' + relPath, - fileName:rows.fileName - }; - } - } -} \ No newline at end of file diff --git a/test/app/module/route/userroute.ts b/test/app/module/route/userroute.ts deleted file mode 100644 index 4ffc5d88f7c162ed1ec39ec546609cbee1148671..0000000000000000000000000000000000000000 --- a/test/app/module/route/userroute.ts +++ /dev/null @@ -1,134 +0,0 @@ -import { Inject, Router, Route, DataModel, NullCheck} from "../../../../core/tools/decorator"; -import { UserService } from "../service/userservice"; -import { DataImpl } from "../service/dataimpl"; -import { MUser } from "../model/muser"; -import { RBase } from "./rbase"; - -/** - * 测试用户 - */ -@Router({ - namespace:'/user', - path:'get*' -}) -@DataModel(MUser) -export class UserRoute extends RBase{ - userName:string; - // age:number; - @Inject("userService") - userService:UserService; - @Inject("DataImpl") - dataImpl:DataImpl; - - downloadPath:string; - - async user(){ - return{success:true,user:'yes'}; - } - @Route({ - path:'/addres' - }) - - async addres(){ - try{ - let r = await this.dataImpl.add(); - return{ - success:true, - result:r - } - }catch(e){ - return {success:false,result:e.message}; - } - } - @NullCheck(['sexy']) - getUserName(){ - return {uname:'yang'}; - } - - @Route({ - path:'/getinfo', - results:[{ - value:1, - type:"redirect", - url:"/user/showinfo", - params:['userName','age'] - },{ - value:2, - type:"chain", - url:"/user/last1", - params:["type"] - },{ - value:3, - type:'stream', - // url:'/user/down', - params:['downloadPath'] - }] - }) - @NullCheck(['userName','age']) - async getinfo(){ - // console.log(this.model); - if(this.model.type==1){ - return 1; - }else if(this.model.type==2){ - this.userName = 'bbb'; - return 2; - }else if(this.model.type==3){ - this.downloadPath = '/test/test.js'; - return 3; - } - - return { - success:true, - result:await this.dataImpl.test('hello') - } - } - - async getinfo1(){ - let s = await this.dataImpl.methodC(); - return s; - } - - @Route('/showinfo') - async showinfo(){ - return await new Promise((resolve,reject)=>{ - if(this.model.userName === 'aaa'){ - resolve({ - success:true, - result:1 - }); - }else{ - resolve({ - success:true, - result:this.model.userName - }); - } - }); - } - - @Route('/last') - last(){ - // return this.model.type; - return { - info:"this is the last info" - } - } - - - async addtwo(){ - try{ - let r = await this.userService.addTwoUser(this.model.id,this.model.name,this.model.age,this.model.mobile); - return {success:true} - }catch(e){ - return {success:false,msg:e}; - } - } - - async testNest(){ - try{ - let r = await this.dataImpl.methodA(); - return {success:true} - }catch(e){ - return {success:false,msg:e}; - } - } -} \ No newline at end of file diff --git a/test/app/module/route/usertyperoute.ts b/test/app/module/route/usertyperoute.ts deleted file mode 100644 index b6c79e321819b9309899fc7e8821c0de1fcad43f..0000000000000000000000000000000000000000 --- a/test/app/module/route/usertyperoute.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { Inject, Instance, Router, Route, DataModel } from "../../../../core/tools/decorator"; -import { BaseRoute } from "../../../../core/main/route/baseroute"; -import { MUserType } from "../model/musertype"; - -/** - * 测试用户 - */ -@Router({ - namespace:'/user/info/type', - path:'*' -}) -@DataModel(MUserType) -export class UserTypeRoute extends BaseRoute{ - gettype(){ - return {'userType':1}; - } -} - diff --git a/test/app/module/service/dataimpl.ts b/test/app/module/service/dataimpl.ts deleted file mode 100644 index 7a65c9dc67d4556f2e9f9bde27854e51ee953638..0000000000000000000000000000000000000000 --- a/test/app/module/service/dataimpl.ts +++ /dev/null @@ -1,183 +0,0 @@ -import { getConnection, closeConnection, getManager } from "../../../../core/database/connectionmanager"; -import { Transaction, Instance, Transactioner, Inject } from "../../../../core/tools/decorator"; -// import { Resource } from "../dao/pojo/resource"; -// import { ResourceAuthority } from "../dao/pojo/resourceauthority"; -// import { EntityManager } from "typeorm"; -// import Resource from "../dao/pojosequelize/resource"; -// import ResourceAuthority from "../dao/pojosequelize/resourceauthority"; -// import { Sequelize } from "sequelize-typescript"; -import { UserService } from "./userservice"; -import { User } from "../dao/entity/user"; -import { Connection, EntityManagerFactory ,EntityManager} from "relaen"; -import { UserInfo } from "../dao/entity/userinfo"; - -// import { Resource } from "../dao/pojo/resource"; -// import { EntityManager } from "typeorm"; -// import ResourceAuthority from "../dao/pojosequelize/resourceauthority"; -// import Resource from "../dao/pojosequelize/resource"; - -@Transactioner() -class DataImpl{ - @Inject('userService') - us:UserService; - - async test(ss){ - throw ss; - } - // @Transaction() - async addRes(url:string,id?:number){ - //mysql - // let sql:string = "insert into t_resource(url,resource_id) values(?,?)"; - // let r = await new Promise(async (resolve,reject)=>{ - // let conn = await getConnection(); - // if(conn == null){ - // reject("conn is null"); - // } - // conn.query(sql,[url,id],(err,result)=>{ - // if(err){ - // reject(err); - // } - // resolve(result); - // }); - // }); - - //oracle - // let sql:string = "insert into t_resource(resource_id,url) values(13,'"+url+"')"; - // let conn = await getConnection(); - // let r = await conn.execute(sql); - - //mssql - // let sql:string = "insert into t_resource(resource_id,url) values(14,'"+url+"')"; - // let conn = await getConnection(); - // let r = await conn.query(sql); - - //sequelize - // let seq:Sequelize = await getConnection(); - // let res:Resource = await seq.getRepository(Resource).create({ - // resourceId:id, - // url:url - // }); - // let r1 = await res.save(); - //typeorm - // let res = new Resource(); - // res.resourceId = id; - // res.url = url; - // let manager:EntityManager = await getManager(); - // let r1 = await manager.save(res); - - //relaen - // let em:EntityManager = await getManager(); - let user:User = new User(id); - user.setUserName('aaaa'); - await user.save(true); - // em.save(user); - let ui:UserInfo = new UserInfo(); - ui.setRealName('yang'); - ui.setAge(10); - ui.setSexy('M'); - ui.setUser(user); - await ui.save(true); - // await em.close(); - return 2; - } - // @Transaction() - async addResAuth(){ - //mysql - // let sql:string = "insert into t_resource_authority(resource_id,authority_id) values(3,4)"; - // let r = await new Promise(async (resolve,reject)=>{ - // let conn = await getConnection(); - // conn.query(sql,(err,result)=>{ - // if(err){ - // reject(err); - // } - // resolve(result); - // }); - // }); - - //oracle - // let sql:string = "insert into t_resource_authority(resource_authority_id,resource_id,authority_id) values(2,3,4)"; - // let conn = await getConnection(); - // let r = await conn.execute(sql); - - //mssql - // let sql:string = "insert into t_resource_authority(resource_authority_id,resource_id,authority_id) values(2,3,4)"; - // let conn = await getConnection(); - // try{ - // let r = await conn.query(sql); - // }catch(e){ - // console.log(e); - // } - - //sequelize - // const res = new Resource({ - // resourceId:100, - // authorityId:2 - // }) - // let r1 = await res.save(); - - //typeorm - // let manager:EntityManager = await getManager(); - // const res = new ResourceAuthority(); - // await manager.save(res); - // return 1; - - //relaen - // let conn:Connection = await getConnection(); - // let em:EntityManager = EntityManagerFactory.createEntityManager(conn); - // let user:User = new User(4); - // user.setUserName('yanglei'); - // user.setAge(10); - // user.setSexy('M'); - // await user.save(); - // em.close(); - // await conn.close(); - } - - // @Transaction() - async add(){ - // let r1 = await this.addResAuth(); - // try{ - // let r1 = await this.addRes('/testtran'); - // let r2 = await this.addRes('/testtran1',14); - // }catch(e){ - // return false; - // } - // this.us.sayHello(); - // let r1 = await this.addRes('/testtran1'); - // throw 'hahaha'; - - // await this.addResAuth(); - await this.addRes('/testtran1',100); - await this.addRes('/testtran1',100); - return true; - // if(r1 === 1 && r2 === 2){ - // return true; - // }else{ - // return false; - // } - } - - - async methodA(){ - // try{ - await this.mehtodB(); - // }catch(e){ - // console.log(e); - // } - - // await this.methodC(); - console.log('finished'); - } - - async mehtodB(){ - // throw new Error('methodB failed'); - await this.methodC(); - } - - async methodC(){ - // throw new Error('methodB failed'); - return 'methodC' - } -} - -export{DataImpl} \ No newline at end of file diff --git a/test/app/module/service/myrouteerror.ts b/test/app/module/service/myrouteerror.ts deleted file mode 100644 index 91be087841b6ed9fd6ed1ee6f82079256330ebc4..0000000000000000000000000000000000000000 --- a/test/app/module/service/myrouteerror.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { RouteErrorHandler } from "../../../../core/main/route/routeerrorhandler"; -import { HttpResponse } from "../../../../core/web/httpresponse"; -import { Instance } from "../../../../core/tools/decorator"; - -@Instance('myRouteError') -class MyRouteError extends RouteErrorHandler{ - handle(res:HttpResponse,e:Error){ - res.writeToClient({data:e.message}); - } -} \ No newline at end of file diff --git a/test/app/module/service/testhook.ts b/test/app/module/service/testhook.ts deleted file mode 100644 index 7b631b82258bdff5a11b7d402554baf6a9698ab0..0000000000000000000000000000000000000000 --- a/test/app/module/service/testhook.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { Instance, Inject } from "../../../../core/tools/decorator"; -import { UserService } from "./userservice"; - -@Instance("testHook") -export class TestHook{ - haha(firstName:string,show:boolean){ - if(show){ - console.log('hahaha"' + firstName + '"'); - }else{ - console.log('hahaha'); - } - - } -} \ No newline at end of file diff --git a/test/app/module/service/userservice.ts b/test/app/module/service/userservice.ts deleted file mode 100644 index 9da0a52ab4a493b731de075eeb533104f31c789c..0000000000000000000000000000000000000000 --- a/test/app/module/service/userservice.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { Transactioner, Instance } from "../../../../core/tools/decorator"; - -import { WebConfig } from "../../../../core/web/webconfig"; -import {EntityManager} from "relaen"; -import { User } from "../dao/entity/user"; -import { getConnection, getManager } from "../../../../core/database/connectionmanager"; - -@Transactioner(['addUser','addTwoUser']) -@Instance('userService') -export class UserService{ - constructor(){ - // console.log(WebConfig.cors); - } - - sayHello(){ - console.log('hello'); - } - async addUser( - name:string, - age:string, - mobile:string):Promise{ - let conn:any = await getConnection(); - let r:any = await new Promise((resolve,reject)=>{ - conn.query('insert into t_user(name,age,mobile) values(?,?,?)', - [name,age,mobile], - (err,results)=>{ - if(err){ - reject(err); - }else{ - resolve(results); - } - }); - }); - return r.insertId; - } - async addUserWithId( - id:string, - name:string, - age:string, - mobile:string):Promise{ - let conn:any = await getConnection(); - let r:any = await new Promise((resolve,reject)=>{ - conn.query('insert into t_user(id,name,age,mobile) values(?,?,?,?)', - [id,name,age,mobile], - (err,results)=>{ - if(err){ - reject(err); - }else{ - resolve(results); - } - }); - }); - return r.insertId; - } - async addTwoUser(id:string, - name:string, - age:string, - mobile:string):Promise{ - //如果传入的主键id在数据表中已经存在,则会回滚事务, - // 否则添加两条name age mobile相同,id不同的数据记录 - await this.addUser(name,age,mobile); - await this.addUserWithId(id,name,age,mobile); - } - - async addUser1(){ - for(let i=0;i<100;i++){ - let em:EntityManager = await getManager(); - let user:User = new User(); - user.setUserName('test'); - await user.save(); - em.close(); - } - } -} \ No newline at end of file diff --git a/test/app/module/webhandler/favicohandler.ts b/test/app/module/webhandler/favicohandler.ts deleted file mode 100644 index 550542da0fd5f936efbf4276a089bf86844cb0b7..0000000000000000000000000000000000000000 --- a/test/app/module/webhandler/favicohandler.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { Instance, WebFilter, Inject, WebHandler } from "../../../../core/tools/decorator"; -import { WebAfterHandler } from "../../../../core/web/webafterhandler"; - -@Instance('faviconHandler') -export class FaviconHandler{ - @WebHandler(/\/favicon.ico$/,1000) - handle(result,request,response){ - if(result===404){ - return {}; - } - return null; - } -} \ No newline at end of file diff --git a/test/app/module/webhandler/routehandler.ts b/test/app/module/webhandler/routehandler.ts deleted file mode 100644 index 702db4b40b76e6f4ebf77aa215dd7ff02545ca17..0000000000000000000000000000000000000000 --- a/test/app/module/webhandler/routehandler.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { Instance, WebHandler } from "../../../../core/tools/decorator"; - -@Instance('routeHandler') -export class RouteHandler{ - @WebHandler(/\w+(?!\.\w+)$/,1) - handle(result,request,response){ - if(result instanceof Error){ - return {success:false,message:result.message} - } - return result; - } -} \ No newline at end of file diff --git a/test/pages/css/video.css b/test/pages/css/video.css deleted file mode 100644 index b8c9a1349e55ab07fb58ba751a6928e4616509fb..0000000000000000000000000000000000000000 --- a/test/pages/css/video.css +++ /dev/null @@ -1,8 +0,0 @@ -video{ - width:500px; - height:300px; -} - -ol{ - width:300px; -} \ No newline at end of file diff --git a/test/pages/error/403.html b/test/pages/error/403.html deleted file mode 100644 index 02acf819b18cbe9fdb239ba92c2bdf2fb94073e8..0000000000000000000000000000000000000000 --- a/test/pages/error/403.html +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - 403错误-noomi测试 - - -

403错误

-

您无权访问该页面!

-

You have no right to access this page!

- - \ No newline at end of file diff --git a/test/pages/error/404.html b/test/pages/error/404.html deleted file mode 100644 index a1c05d6acfb77794970adaf86e2f85eb0a1b482d..0000000000000000000000000000000000000000 --- a/test/pages/error/404.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - 404错误-noomi测试 - - -

404错误

-

你访问的页面不在了

- - \ No newline at end of file diff --git a/test/pages/files/file1.js b/test/pages/files/file1.js deleted file mode 100644 index a4c33792fbc66136b6c048704aaa9f8e08db032e..0000000000000000000000000000000000000000 --- a/test/pages/files/file1.js +++ /dev/null @@ -1,160 +0,0 @@ -整体架构 -cell 挂载到指定方法 -cellpool存放初始化的cell,每次调用时,从cellpool找到空闲的cell,然后给cell挂载指定方法,cell负责计算过程管理,比如局部变量、外部引用 - - -InstanceFactory 实例工厂 -Context 上下文 - -mime: 需要安装mime包 - -IoC : 采用装饰器进行注入 -Aop : 定义切面、接入点 -问题:Aop针对注入对象,需要进行参数代理 - - -启动过程 -1. 读config/noomi.ini文件 -2. session 工厂建立 -3. 找到context文件路径 -4. 读instance context文件并进行实例工厂初始化 -5. 读route 文件进行路由工厂初始化 -6. 读aop文件进行aop工厂初始化 - - -2019-9-2 -Aop执行时,实例的方法需要通过代理来执行,否则无法进行aop嗅探,所以需要对需要aop的所有方法进行代理处理 -遍历实例方法: -Object.getOwnPropertyNames(instance.__proto__),实例的方法通过类的原型链继承 -今天出现一个问题,就是在inject注解代码中,针对方法做代理后,UserService的dateHandler注入属性变成了undefined -找到原因:方法调用时,沿用了之前的调用方式,需要用apply赋予this指向 - -2019-9-3 -需要修改AopProxy,aop不应该修改InstanceFactory.exec,它应该是对原框架无扰,所以要在AopProxy中重写调用方法 - -2019-9-4 -过滤器和静态资源管理完成了 -在noomi.ini中增加了error page的配置,根据错误可以跳转到错误页面了 -出现一个问题:utf8回写页面出现中文乱码问题,改成gbk正常,待解决,解决方案:response setheader时content-type里面加charset参数。 - -模型驱动问题 -因为js数据没有类型,无法做到模型的数据转换 - -问题: -关于node很多操作都是异步,instance factory 怎么控制其执行顺序 - -2019-9-6 -尝试 async-hooks 监听异步操作方法 - -2019-9-10 -尝试注解(装饰器)方式,或者要求带有异步的方法用async定义类,用await调用方法 - -2019-9-11 -有两种方法,一种返回普通结果,一种返回promise对象(异步),有两种调用方式,一种直接调用,一种aop织入 -1、返回普通结果的直接调用:调用后直接返回结果,可供继续执行 -2、返回普通结果的aop织入:前置方法执sh行-被织入方法执行-后置(异常)方法执行,分两种情况: - 1)前置、后置方法都返回普通结果,则直接执行即可 - 2)前置、后置方法存在返回promise情况,需要加await执行 模拟同步 -3、返回promise对象的直接调用:用await模拟同步 -4、返回promise对象的aop织入:用await模拟同步 - - -2019-9-16 -上传功能 - -2019-9-20 -form提交分为两种,一种form内容小于5M,一种form内容大于5M -小于5M的内容,存放在buffer中,大于5M的内容存放到文件中,然后解析文件功能。 - -2019-9-21 -用stream处理,req本身是incommingstream,直接处理即可 -有个问题,incommingstream默认是utf8,而文件必须为binary - -2019-10-5 -route results 如果只有一个,则不判断返回结果,如果没有,则默认返回 ajax json - -2019-10-7 -修改httprequest 和httpresponse类,在createserver时代理createserver中的request和response - -2019-10-8 -还剩下异常处理+国际化、redisfactory、事务 -继续noomi中的redis的文件加载 - -2019-10-9 -sessionfactory getSession 需要整理 - -2019-10-10 -异常处理、oracle,mssql,mongodb接入安全框架 - -后续工作,orm、事务 -2019-10-11 -事务管理器,管理所有事务,事务分为不同(分数据库、第三方框架)。 -事务嵌套,如何解决内部事务的事务获取问题 -假定每个用户,同一时刻只有一个事务,则事务的启用,必须加锁,为每个用户设定事务等待队列。 -数据库方法基本都是采用异步,所以存在单个用户同时有多个事务处理的情况。 - -security增加redis支持,后期可能还需要增加token支持 - -2019-10-13 -事务处理 mysql 、sequenlize - -2019-10-16 -cpu超限时的拒绝连接问题 -放弃事务机制 -增加aop注解方式 - - -2019-10-25 -事务嵌套,提交时execution id不正确 -整理connection manager、transaction manager,增加mssql、oracle支持 -增加sequlize、typeorm支持 - -2019-10-28 -因为是静态方法,所以在aopproxy这儿引用出了问题 - -2019-10-30 -bug:session id 生成方式有错误,集群环境下会出现重复值,需转成uuid -bug:直接绑定事务代理方法不正确,因为可能存在其它切面的情况,需要修改代理方法 - -2019-10-6 -上传后图出问题,ok -访问action时需要登录的情况,这个时候应该跳回到登录前页面,而不是action,ok - -异常信息处理 - -2019-10-12 -response writetoclient headers 需要检查代码 - -2019-11-17 -transactionproxy dodatabase 方法需要修改,事务用完后需要从transactionmanager删除 - -2019-11-25 -instances配置,当模块路径不存在时报错 - -2019-11-27 -当请求路径不在路由列表时,过滤器不执行 - -2019-12-2 -如果static_path下不存在某个路径,则报错 - -2019-12-8 -多个应用部署时,redis存在 cache name相同的问题 - -2019-12-11 -安全相关数据为空时,报错 - -2019-12-16 -路由方法名与namespace一致时报错 - -2019-12-18 -处理重复请求过滤 - -2019-12-28 -嵌套事务时,a 调用b,如果b抛出异常,而a进行了捕获,则不会进行回滚,noomi这块没有处理 - -2020-4-27 -safari使用redis,压缩缓存,会导致不能解析 - -2020-5-31 -fetch处理问题,httprequest 处理数据 -修复路由路径存在包含问题的bug \ No newline at end of file diff --git a/test/pages/imgs/homebg.png b/test/pages/imgs/homebg.png deleted file mode 100644 index f46a9c191e80adf4702401217496765c31324f9c..0000000000000000000000000000000000000000 Binary files a/test/pages/imgs/homebg.png and /dev/null differ diff --git a/test/pages/jpg1 b/test/pages/jpg1 deleted file mode 100644 index f46a9c191e80adf4702401217496765c31324f9c..0000000000000000000000000000000000000000 Binary files a/test/pages/jpg1 and /dev/null differ diff --git a/test/pages/js/a.js b/test/pages/js/a.js deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/test/pages/js/app.js b/test/pages/js/app.js deleted file mode 100644 index fff38cf25d333a8e4acd1cf4ab9d5e9e84c5f6a7..0000000000000000000000000000000000000000 --- a/test/pages/js/app.js +++ /dev/null @@ -1,7 +0,0 @@ -class app { - static fs = require('fs'); - static path = require('path'); - static url = require('url'); - const uuid = require('uuid'); -} -exports.app = app; \ No newline at end of file diff --git a/test/pages/js/apppath/aaa/bbb/ccc/f2.js b/test/pages/js/apppath/aaa/bbb/ccc/f2.js deleted file mode 100644 index cc55870dab1e29864b75daf689924f70a89f8986..0000000000000000000000000000000000000000 --- a/test/pages/js/apppath/aaa/bbb/ccc/f2.js +++ /dev/null @@ -1,2 +0,0 @@ -console.log('ddd'); -console.log('fffg'); \ No newline at end of file diff --git a/test/pages/js/apppath/aaa/bbb/ccc/f3.js b/test/pages/js/apppath/aaa/bbb/ccc/f3.js deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/test/pages/js/apppath/aaa/bbb/f1.js b/test/pages/js/apppath/aaa/bbb/f1.js deleted file mode 100644 index 946a4c154bb730b03bd5956abb8921ba82e15a7a..0000000000000000000000000000000000000000 --- a/test/pages/js/apppath/aaa/bbb/f1.js +++ /dev/null @@ -1,7 +0,0 @@ -console.log('xaaa'); -function foo(){ - console.log('xxxx'); - - - -} \ No newline at end of file diff --git a/test/pages/js/homebg.png b/test/pages/js/homebg.png deleted file mode 100644 index f46a9c191e80adf4702401217496765c31324f9c..0000000000000000000000000000000000000000 Binary files a/test/pages/js/homebg.png and /dev/null differ diff --git a/test/pages/js/index.js b/test/pages/js/index.js deleted file mode 100644 index 23b631d746bbcbe5f0c6d496e8686b30bf21eb0d..0000000000000000000000000000000000000000 --- a/test/pages/js/index.js +++ /dev/null @@ -1 +0,0 @@ -console.log('222'); \ No newline at end of file diff --git a/test/pages/js/jpg1 b/test/pages/js/jpg1 deleted file mode 100644 index d3ba4284f764aee76eabbc5c4dd5094d5f32dcc0..0000000000000000000000000000000000000000 --- a/test/pages/js/jpg1 +++ /dev/null @@ -1,3559 +0,0 @@ -const NUITipWords = { - uploading: '上传中...', - total: '共', - record: '条', - NO: '第', - page: '页', - weekday: { - sunday: '日', - monday: '一', - tuesday: '二', - wednesday: '三', - thursday: '四', - friday: '五', - saturday: '六' - }, - buttons: { - ok: '确定', - cancel: '取消', - close: '关闭', - yes: '是', - no: '否', - today: '今天', - now: '此时' - } -}; -document.oncontextmenu = function (e) { - e.preventDefault(); -}; -class UITool { - static clearSpace(src) { - if (src && typeof src === 'string') { - return src.replace(/\s+/g, ''); - } - } - static adjustPosAndSize(module, key, x, y, distance, bodyHeight, changeSize) { - let el = module.container.querySelector("[key='" + key + "']"); - if (!el) { - setTimeout(() => { - UITool.adjustPosAndSize(module, key, x, y, distance, document.body.scrollHeight, changeSize); - }, 0); - } - else { - let scTop = document.documentElement.scrollTop || document.body.scrollTop; - y += scTop; - let height = bodyHeight > window.innerHeight ? bodyHeight : window.innerHeight; - if (changeSize) { - el.style.maxHeight = (window.innerHeight - 50) + 'px'; - } - if (y + el.offsetHeight > height && y > el.offsetHeight + distance) { - el.style.transform = 'translate(0,' + -(el.offsetHeight + distance) + 'px)'; - } - else { - el.style.transform = 'translate(0,0)'; - } - } - } - static handleUIParam(dom, defDom, paramArr, props, defaultValues) { - let error = false; - for (let i = 0; i < paramArr.length; i++) { - let pName = props[i]; - let p = paramArr[i]; - let type; - let pa; - if (p.includes('|')) { - pa = p.split('|'); - p = pa[0]; - type = pa[1]; - } - let v = dom.getProp(p); - if (v) { - v = this.clearSpace(v); - if (v !== '') { - switch (type) { - case 'number': - if (!nodom.Util.isNumberString(v)) { - error = true; - } - else { - defDom[pName] = parseInt(v); - } - break; - case 'array': - let va = v.split(','); - if (pa.length === 3) { - if (nodom.Util.isNumberString(pa[2])) { - if (parseInt(pa[2]) > va.length) { - error = true; - } - } - else { - if (pa[2] === 'number') { - for (let i = 0; i < va.length; i++) { - let v1 = va[i]; - if (!nodom.Util.isNumberString(v1)) { - error = true; - break; - } - va[i] = parseInt(v1); - } - } - } - } - if (!error) { - defDom[pName] = va; - } - break; - case 'bool': - if (v === 'true') { - defDom[pName] = true; - } - break; - default: - defDom[pName] = v; - } - } - } - if (!v || v === '') { - if (defaultValues && defaultValues[i] !== null) { - defDom[pName] = defaultValues[i]; - } - else { - if (type === 'bool') { - if (dom.hasProp(p)) { - defDom[pName] = true; - } - else { - defDom[pName] = false; - } - } - else { - error = true; - } - } - } - dom.delProp(p); - if (error) { - throw new nodom.NodomError('config1', defDom.tagName, p); - } - } - } -} -class UIEventRegister { - static addEvent(eventName, moduleId, domKey, handler) { - if (!this.listeners.has(eventName)) { - this.listeners.set(eventName, []); - window.addEventListener(eventName, (e) => { - let target = e.target; - let key = target.getAttribute('key'); - let evts = this.listeners.get(eventName); - for (let evt of evts) { - let module = nodom.ModuleFactory.get(evt.module); - let dom = module.renderTree.query(evt.dom); - if (!dom) { - continue; - } - let inOrOut = dom.key === key || dom.query(key) ? true : false; - if (typeof evt.handler === 'function') { - evt.handler.apply(dom, [module, dom, inOrOut, e]); - } - } - }, false); - } - let arr = this.listeners.get(eventName); - let find = arr.find(item => item.dom === domKey); - if (find) { - return; - } - arr.push({ - module: moduleId, - dom: domKey, - handler: handler - }); - } -} -UIEventRegister.listeners = new Map(); -function request(cfg) { - return nodom.request(cfg); -} -class UIAccordion extends nodom.Plugin { - constructor(params) { - super(params); - this.tagName = 'UI-ACCORDION'; - let rootDom = new nodom.Element(); - if (params) { - if (params instanceof HTMLElement) { - nodom.Compiler.handleAttributes(rootDom, params); - nodom.Compiler.handleChildren(rootDom, params); - } - else if (typeof params === 'object') { - for (let o in params) { - if (o === 'children') { - if (Array.isArray(params[o])) { - for (let c of params[o]) { - if (typeof c !== 'object') { - continue; - } - let d = new nodom.Element(c.tagName || 'div'); - for (let p in c) { - if (p === 'tagName') { - continue; - } - d.setProp(p, c[p]); - } - rootDom.add(d); - } - } - } - else { - this[o] = params[o]; - } - } - } - this.generate(rootDom); - } - rootDom.tagName = 'div'; - rootDom.plugin = this; - this.element = rootDom; - } - generate(rootDom) { - rootDom.addClass('nd-accordion'); - let firstDom = new nodom.Element(); - let secondDom = new nodom.Element(); - firstDom.tagName = 'DIV'; - secondDom.tagName = 'DIV'; - firstDom.addClass('nd-accordion-item'); - let activeName1; - let activeName2; - for (let i = 0; i < rootDom.children.length; i++) { - let item = rootDom.children[i]; - if (!item.tagName) { - continue; - } - if (item.hasProp('first')) { - firstDom.addDirective(new nodom.Directive('repeat', item.getProp('data'), firstDom), true); - item.addClass('nd-accordion-first'); - let methodId = '$nodomGenMethod' + nodom.Util.genId(); - item.addEvent(new nodom.NodomEvent('click', methodId + ':delg')); - this.method1 = methodId; - activeName1 = item.getProp('activename') || 'active'; - this.active1 = activeName1; - firstDom.add(item); - let span = new nodom.Element('span'); - span.children = item.children; - item.children = [span]; - if (item.hasProp('icon')) { - span.addClass('nd-icon-' + item.getProp('icon')); - } - this.field1 = item.getProp('data'); - let icon = new nodom.Element('b'); - icon.addClass('nd-accordion-icon nd-icon-right'); - icon.directives.push(new nodom.Directive('class', "{'nd-accordion-open':'" + activeName1 + "'}", icon)); - item.add(icon); - item.delProp(['activename', 'first']); - } - else if (item.hasProp('second')) { - activeName2 = item.getProp('activename') || 'active'; - this.active2 = activeName2; - item.addDirective(new nodom.Directive('repeat', item.getProp('data'), item)); - this.field2 = item.getProp('data'); - item.addClass('nd-accordion-second'); - if (item.hasProp('itemclick')) { - item.addEvent(new nodom.NodomEvent('click', item.getProp('itemclick') + ':delg')); - } - item.addDirective(new nodom.Directive('class', "{'nd-accordion-selected':'" + activeName2 + "'}", item)); - secondDom.addClass('nd-accordion-secondct'); - secondDom.add(item); - secondDom.addDirective(new nodom.Directive('class', "{'nd-accordion-hide':'!" + activeName1 + "'}", secondDom), true); - } - item.delProp(['data', 'second']); - } - firstDom.add(secondDom); - rootDom.children = [firstDom]; - } - beforeRender(module, uidom) { - const me = this; - super.beforeRender(module, uidom); - if (this.needPreRender) { - module.methodFactory.add(this.method1, (dom, model, module, e) => { - let pmodel = module.modelFactory.get(uidom.modelId); - let data = pmodel.data[me.field1]; - let f = me.active1; - for (let d of data) { - if (d[f] === true) { - d[f] = false; - } - } - model.set(f, true); - }); - module.methodFactory.add(this.method2, (dom, model, module, e) => { - let pmodel = module.modelFactory.get(uidom.modelId); - let data = pmodel.data[me.field1]; - let f = me.active2; - for (let d of data) { - for (let d1 of d[me.field2]) { - if (d1[f] === true) { - d1[f] = false; - } - } - } - model.set(f, true); - }); - } - } -} -nodom.PluginManager.add('UI-ACCORDION', UIAccordion); -class UIButton extends nodom.Plugin { - constructor(params) { - super(params); - this.tagName = 'UI-BUTTON'; - let rootDom = new nodom.Element(); - if (params) { - if (params instanceof HTMLElement) { - nodom.Compiler.handleAttributes(rootDom, params); - nodom.Compiler.handleChildren(rootDom, params); - UITool.handleUIParam(rootDom, this, ['size', 'icon', 'iconpos', 'theme', 'nobg|bool'], ['size', 'icon', 'iconPos', 'theme', 'nobg'], ['normal', '', 'left', '', null]); - this.text = params.innerHTML.trim(); - } - else if (typeof params === 'object') { - for (let o in params) { - this[o] = params[o]; - } - } - this.generate(rootDom); - } - rootDom.tagName = 'button'; - rootDom.plugin = this; - this.element = rootDom; - } - generate(rootDom) { - let clsArr = ['nd-btn']; - clsArr.push('nd-btn-' + this.size); - if (this.icon !== '') { - clsArr.push('nd-btn-' + this.iconPos); - } - if (this.nobg) { - clsArr.push('nd-btn-nobg'); - } - else if (this.theme !== '') { - clsArr.push('nd-btn-' + this.theme); - } - if (this.text === '') { - clsArr.push('nd-btn-notext'); - } - rootDom.addClass(clsArr.join(' ')); - let txt = new nodom.Element(); - txt.textContent = this.text; - let children = [txt]; - if (this.icon !== '') { - let img = new nodom.Element('b'); - img.addClass('nd-icon-' + this.icon); - switch (this.iconPos) { - case 'left': - children.unshift(img); - break; - case 'top': - children.unshift(img); - img.addClass('nd-btn-vert'); - break; - case 'right': - children.push(img); - break; - case 'bottom': - children.push(img); - img.addClass('nd-btn-vert'); - break; - } - } - rootDom.children = children; - } -} -nodom.PluginManager.add('UI-BUTTON', UIButton); -class UIButtonGroup extends nodom.Plugin { - constructor(params) { - super(params); - this.tagName = 'UI-BUTTONGROUP'; - let rootDom = new nodom.Element(); - if (params) { - if (params instanceof HTMLElement) { - nodom.Compiler.handleAttributes(rootDom, params); - nodom.Compiler.handleChildren(rootDom, params); - } - else if (typeof params === 'object') { - for (let o in params) { - if (o === 'children') { - if (Array.isArray(params[o])) { - for (let c of params[o]) { - if (typeof c !== 'object') { - continue; - } - rootDom.add(new UIButton(c).element); - } - } - } - else { - this[o] = params[o]; - } - } - } - } - rootDom.addClass('nd-buttongroup'); - rootDom.tagName = 'div'; - rootDom.plugin = this; - this.element = rootDom; - } -} -nodom.PluginManager.add('UI-BUTTONGROUP', UIButtonGroup); -class UICheckbox extends nodom.Plugin { - constructor(params) { - super(params); - this.tagName = 'UI-CHECKBOX'; - let rootDom = new nodom.Element(); - if (params) { - if (params instanceof HTMLElement) { - nodom.Compiler.handleAttributes(rootDom, params); - nodom.Compiler.handleChildren(rootDom, params); - UITool.handleUIParam(rootDom, this, ['yesvalue', 'novalue'], ['yesValue', 'noValue'], ['true', 'false']); - } - else if (typeof params === 'object') { - for (let o in params) { - this[o] = params[o]; - } - } - this.generate(rootDom); - } - rootDom.tagName = 'span'; - rootDom.plugin = this; - this.element = rootDom; - } - generate(rootDom) { - const me = this; - let field = rootDom.getDirective('field'); - if (field) { - this.dataName = field.value; - rootDom.removeDirectives(['field']); - } - let icon = new nodom.Element('b'); - icon.addClass('nd-checkbox-uncheck'); - icon.addDirective(new nodom.Directive('class', "{'nd-checkbox-checked':'" + this.dataName + "==\"" + this.yesValue + "\"'}", icon)); - rootDom.children.unshift(icon); - rootDom.addEvent(new nodom.NodomEvent('click', (dom, model, module) => { - let v = model.data[me.dataName]; - if (v == me.yesValue) { - model.set(me.dataName, me.noValue); - } - else { - model.set(me.dataName, me.yesValue); - } - })); - } -} -nodom.PluginManager.add('UI-CHECKBOX', UICheckbox); -class UIDatetime extends nodom.Plugin { - constructor(params) { - super(params); - this.tagName = 'UI-DATETIME'; - let rootDom = new nodom.Element(); - if (params) { - if (params instanceof HTMLElement) { - nodom.Compiler.handleAttributes(rootDom, params); - nodom.Compiler.handleChildren(rootDom, params); - UITool.handleUIParam(rootDom, this, ['type'], ['type'], ['date']); - } - else if (typeof params === 'object') { - for (let o in params) { - this[o] = params[o]; - } - } - this.generate(rootDom); - } - rootDom.tagName = 'div'; - rootDom.plugin = this; - this.element = rootDom; - } - generate(rootDom) { - let me = this; - rootDom.addClass('nd-datetime'); - let fieldDom = new nodom.Element('div'); - fieldDom.addClass('nd-datetime-field'); - let dateIco = new nodom.Element('b'); - dateIco.addClass(this.type === 'time' ? 'nd-datetime-time' : 'nd-datetime-date'); - let directive = rootDom.getDirective('field'); - if (directive) { - this.dataName = directive.value; - rootDom.removeDirectives(['field']); - } - let input = new nodom.Element('input'); - if (this.dataName) { - input.addDirective(new nodom.Directive('field', this.dataName, input)); - input.setProp('value', new nodom.Expression(this.dataName), true); - } - fieldDom.add(input); - fieldDom.add(dateIco); - fieldDom.addEvent(new nodom.NodomEvent('click', (dom, model, module, e, el) => { - me.showPicker(dom, model, module, e, el); - })); - this.extraDataName = '$ui_datetime_' + nodom.Util.genId(); - let pickerDom = new nodom.Element('div'); - pickerDom.addClass('nd-datetime-picker'); - pickerDom.addDirective(new nodom.Directive('model', this.extraDataName, pickerDom)); - pickerDom.addDirective(new nodom.Directive('show', 'show', pickerDom)); - let tblCt = new nodom.Element('div'); - tblCt.addClass('nd-datetime-tbl'); - pickerDom.add(tblCt); - if (this.type === 'date' || this.type === 'datetime') { - tblCt.add(this.genDatePicker()); - } - if (this.type === 'time' || this.type === 'datetime') { - tblCt.add(this.genTimePicker()); - } - let btnCt = new nodom.Element('div'); - btnCt.addClass('nd-datetime-btnct'); - if (this.type === 'date') { - let btnToday = new nodom.Element('button'); - btnToday.assets.set('innerHTML', NUITipWords.buttons.today); - btnToday.addEvent(new nodom.NodomEvent('click', (dom, model, module, e) => { - e.preventDefault(); - let nda = new Date(); - me.setValue(module, nda.getFullYear() + '-' + (nda.getMonth() + 1) + '-' + nda.getDate()); - })); - btnCt.add(btnToday); - } - else if (this.type === 'datetime' || this.type === 'time') { - let btn = new nodom.Element('button'); - btn.assets.set('innerHTML', NUITipWords.buttons.now); - btn.addEvent(new nodom.NodomEvent('click', (dom, model, module, e) => { - e.preventDefault(); - let nda = new Date(); - me.setValue(module, nda.getFullYear() + '-' + (nda.getMonth() + 1) + '-' + nda.getDate() + ' ' - + nda.getHours() + ':' + nda.getMinutes() + ':' + nda.getSeconds()); - })); - btnCt.add(btn); - } - let btnOk = new nodom.Element('button'); - btnOk.addClass('nd-btn-active'); - btnOk.assets.set('innerHTML', NUITipWords.buttons.ok); - btnCt.add(btnOk); - btnOk.addEvent(new nodom.NodomEvent('click', (dom, model, module, e) => { - e.preventDefault(); - model.set('show', false); - let pmodel = module.modelFactory.get(me.modelId); - pmodel.set(this.dataName, me.genValueStr()); - })); - pickerDom.add(btnCt); - rootDom.children = [fieldDom, pickerDom]; - } - beforeRender(module, uidom) { - let me = this; - super.beforeRender(module, uidom); - this.listKey = uidom.children[1].key; - let model = module.modelFactory.get(uidom.modelId); - if (this.needPreRender) { - model.set(this.extraDataName, { - show: false, - year: 2020, - month: 1, - date: 1, - hour: 0, - minute: 0, - second: 0, - time: '00:00:00', - days: [] - }); - this.pickerModelId = model.get(this.extraDataName).id; - if (this.type === 'date') { - this.genDates(module); - } - else if (this.type === 'time') { - this.genTimes(module); - } - else { - this.genDates(module); - this.genTimes(module); - } - UIEventRegister.addEvent('click', module.id, uidom.children[1].key, (module, dom, inOrOut, e) => { - if (!inOrOut) { - model.query(me.extraDataName).show = false; - } - }); - } - else { - this.pickerModelId = model.get(this.extraDataName).id; - } - } - genDatePicker() { - let me = this; - let pickerDom = new nodom.Element('div'); - pickerDom.addClass('nd-datetime-datetbl'); - let ymDom = new nodom.Element('div'); - ymDom.addClass('nd-datetime-ymct'); - pickerDom.add(ymDom); - let leftDom1 = new nodom.Element('b'); - leftDom1.addClass('nd-datetime-leftarrow1'); - let leftDom = new nodom.Element('b'); - leftDom.addClass('nd-datetime-leftarrow'); - let rightDom = new nodom.Element('b'); - rightDom.addClass('nd-datetime-rightarrow'); - let rightDom1 = new nodom.Element('b'); - rightDom1.addClass('nd-datetime-rightarrow1'); - let contentDom = new nodom.Element('span'); - contentDom.addClass('nd-datetime-ym'); - let txtDom = new nodom.Element(); - txtDom.expressions = [new nodom.Expression('year'), '/', new nodom.Expression('month')]; - contentDom.add(txtDom); - leftDom1.addEvent(new nodom.NodomEvent('click', (dom, model, module) => { - me.changeMonth(module, -12); - })); - leftDom.addEvent(new nodom.NodomEvent('click', (dom, model, module) => { - me.changeMonth(module, -1); - })); - rightDom.addEvent(new nodom.NodomEvent('click', (dom, model, module) => { - me.changeMonth(module, 1); - })); - rightDom1.addEvent(new nodom.NodomEvent('click', (dom, model, module) => { - me.changeMonth(module, 12); - })); - ymDom.children = [leftDom1, leftDom, contentDom, rightDom, rightDom1]; - let weekDom = new nodom.Element('div'); - weekDom.addClass('nd-datetime-weekdays'); - let days = Object.getOwnPropertyNames(NUITipWords.weekday); - for (let d of days) { - let span = new nodom.Element('span'); - let txt = new nodom.Element(); - txt.textContent = NUITipWords.weekday[d]; - span.add(txt); - weekDom.add(span); - } - pickerDom.add(weekDom); - let dateDom = new nodom.Element('div'); - dateDom.addClass('nd-datetime-dates'); - let daySpan = new nodom.Element('span'); - daySpan.addDirective(new nodom.Directive('repeat', 'days', daySpan)); - daySpan.addDirective(new nodom.Directive('class', "{'nd-datetime-today':'today','nd-datetime-disable':'disable','nd-datetime-selected':'selected'}", daySpan)); - let txt = new nodom.Element(); - txt.expressions = [new nodom.Expression('date')]; - daySpan.add(txt); - daySpan.addEvent(new nodom.NodomEvent('click', ':delg', (dom, model, module) => { - let data = model.data; - if (data.disable) { - return; - } - me.selectDate(module, model); - })); - dateDom.add(daySpan); - pickerDom.add(dateDom); - return pickerDom; - } - genTimePicker() { - let me = this; - let pickerDom = new nodom.Element('div'); - pickerDom.addClass('nd-datetime-timetbl'); - let showDom = new nodom.Element('input'); - showDom.addClass('nd-datetime-timeinput'); - showDom.setProp('value', new nodom.Expression('time'), true); - pickerDom.add(showDom); - let itemCt = new nodom.Element('div'); - itemCt.addClass('nd-datetime-timect'); - pickerDom.add(itemCt); - let hourDom = new nodom.Element('div'); - let item = new nodom.Element('div'); - item.addClass('nd-datetime-timeitem'); - item.addDirective(new nodom.Directive('repeat', 'hours', item)); - item.addDirective(new nodom.Directive('class', "{'nd-datetime-itemselect':'selected'}", item)); - let txt = new nodom.Element(); - txt.expressions = [new nodom.Expression('v')]; - item.setProp('role', 'hour'); - item.add(txt); - hourDom.add(item); - item.addEvent(new nodom.NodomEvent('click', ':delg', (dom, model, module, e, el) => { - me.selectTime(module, dom, model); - })); - let minuteDom = hourDom.clone(true); - let secondDom = hourDom.clone(true); - minuteDom.children[0].getDirective('repeat').value = 'minutes'; - minuteDom.children[0].setProp('role', 'minute'); - secondDom.children[0].getDirective('repeat').value = 'seconds'; - secondDom.children[0].setProp('role', 'second'); - itemCt.children = [hourDom, minuteDom, secondDom]; - return pickerDom; - } - genDates(module, year, month) { - let cda = new Date(); - let cy = cda.getFullYear(); - let cm = cda.getMonth() + 1; - let cd = cda.getDate(); - if (!year || !month) { - year = cy; - month = cm; - } - let days = this.cacMonthDays(year, month); - let dayArr = []; - let date = new Date(year + '-' + month + '-1'); - let wd = date.getDay(); - let lastMonthDays = this.cacMonthDays(year, month, -1); - for (let d = lastMonthDays, i = 0; i < wd; i++, d--) { - dayArr.unshift({ - disable: true, - selected: false, - date: d - }); - } - for (let i = 1; i <= days; i++) { - dayArr.push({ - date: i, - selected: this.year === year && this.month === month && this.date === i, - today: cy === year && cm === month && cd === i - }); - } - date = new Date(year + '-' + month + '-' + days); - wd = date.getDay(); - for (let i = wd + 1; i <= 6; i++) { - dayArr.push({ - disable: true, - selected: false, - date: i - wd - }); - } - let model = module.modelFactory.get(this.pickerModelId); - model.set('year', year); - model.set('month', month); - model.set('days', dayArr); - } - genTimes(module) { - let model = module.modelFactory.get(this.pickerModelId); - let hours = []; - let minutes = []; - let seconds = []; - for (let i = 0; i < 60; i++) { - let selected = i === 0 ? true : false; - if (i < 24) { - hours.push({ - v: i < 10 ? '0' + i : i, - selected: selected, - }); - } - minutes.push({ - v: i < 10 ? '0' + i : i, - selected: selected - }); - seconds.push({ - v: i < 10 ? '0' + i : i, - selected: selected - }); - } - model.set('hours', hours); - model.set('minutes', minutes); - model.set('seconds', seconds); - } - cacMonthDays(year, month, disMonth) { - if (disMonth) { - month += disMonth; - } - if (month <= 0) { - year--; - month += 12; - } - else if (month > 12) { - year++; - month -= 12; - } - if ([1, 3, 5, 7, 8, 10, 12].includes(month)) { - return 31; - } - else if (month !== 2) { - return 30; - } - else if (year % 400 === 0 || year % 4 === 0 && year % 100 !== 0) { - return 29; - } - else { - return 28; - } - } - changeMonth(module, distance) { - let model = module.modelFactory.get(this.pickerModelId); - let year = model.query('year'); - let month = model.query('month'); - month += distance; - if (month <= 0) { - year--; - month += 12; - } - else if (month > 12) { - year++; - month -= 12; - } - if (month <= 0) { - year--; - month += 12; - } - else if (month > 12) { - year++; - month -= 12; - } - this.genDates(module, year, month); - } - setValue(module, str) { - if (str && str !== '') { - str = str.trim(); - if (str === '') { - return; - } - let model = module.modelFactory.get(this.modelId); - let model1 = module.modelFactory.get(this.pickerModelId); - if (this.type === 'date' || this.type === 'datetime') { - let date = new Date(str); - if (date.toTimeString() !== 'Invalid Date') { - this.year = date.getFullYear(); - this.month = date.getMonth() + 1; - this.date = date.getDate(); - this.genDates(module, this.year, this.month); - if (this.type === 'datetime') { - this.hour = date.getHours(); - this.minute = date.getMinutes(); - this.second = date.getSeconds(); - model1.set('time', this.genValueStr('time')); - this.setTimeSelect(module); - } - } - else { - model.set(this.dataName, this.genValueStr()); - } - } - else if (this.type === 'time') { - if (/^\d{1,2}:\d{1,2}(:\d{1,2})?$/.test(str)) { - let sa = str.split(':'); - this.hour = parseInt(sa[0]); - this.minute = parseInt(sa[1]); - this.second = sa.length > 2 ? parseInt(sa[2]) : 0; - model1.set('time', this.genValueStr('time')); - this.setTimeSelect(module); - } - } - } - } - selectDate(module, model) { - let pmodel = module.modelFactory.get(this.pickerModelId); - if (pmodel) { - let days = pmodel.query('days'); - for (let d of days) { - if (d.selected) { - d.selected = false; - break; - } - } - this.year = pmodel.query('year'); - this.month = pmodel.query('month'); - } - if (model) { - model.set('selected', true); - this.date = model.query('date'); - } - } - selectTime(module, dom, model) { - let pmodel = module.modelFactory.get(this.pickerModelId); - let role = dom.getProp('role'); - if (pmodel) { - let datas = pmodel.query(role + 's'); - for (let d of datas) { - if (d.selected) { - d.selected = false; - break; - } - } - } - if (!model) { - model = module.modelFactory.get(dom.modelId); - } - if (model) { - model.set('selected', true); - } - this[role] = parseInt(model.query('v')); - pmodel.set('time', this.genValueStr('time')); - } - showPicker(dom, model, module, e, el) { - let data = model.query(this.extraDataName); - if (data) { - if (data.show) { - return; - } - data.show = true; - } - let pDom = dom.tagName === 'input' ? dom.getParent(module) : dom; - this.setValue(module, model.query(this.dataName)); - model.set('show', true); - let height = el.offsetHeight; - let y = e.clientY + el.offsetHeight - e.offsetY; - UITool.adjustPosAndSize(module, this.listKey, e.clientX, y, height, null, false); - } - setTimeSelect(module) { - let me = this; - let model = module.modelFactory.get(this.pickerModelId); - let data = [this.hour, this.minute, this.second]; - ['hours', 'minutes', 'seconds'].forEach((item, i) => { - let datas = model.query(item); - for (let d of datas) { - if (d.selected) { - d.selected = false; - break; - } - } - datas[data[i]].selected = true; - }); - setTimeout(scroll, 0); - function scroll() { - let uidom = me.element; - let timeCt; - if (uidom.children.length === 1) { - setTimeout(scroll, 0); - return; - } - if (me.type === 'datetime') { - timeCt = uidom.children[1].children[0].children[1].children[1]; - } - else if (me.type === 'time') { - timeCt = uidom.children[1].children[0].children[0].children[1]; - } - data.forEach((item, i) => { - let el = module.container.querySelector("[key='" + timeCt.children[i].key + "']"); - el.scrollTo(0, data[i] * 30); - }); - } - } - genValueStr(type) { - if (!this.year) { - this.year = 2020; - } - if (!this.month) { - this.month = 1; - } - if (!this.date) { - this.date = 1; - } - if (!this.hour) { - this.hour = 0; - } - if (!this.minute) { - this.minute = 0; - } - if (!this.second) { - this.second = 0; - } - switch (type || this.type) { - case 'datetime': - return [this.year, this.month < 10 ? '0' + this.month : this.month, this.date < 10 ? '0' + this.date : this.date].join('-') + - ' ' + - [this.hour < 10 ? '0' + this.hour : this.hour, this.minute < 10 ? '0' + this.minute : this.minute, this.second < 10 ? '0' + this.second : this.second].join(':'); - case 'time': - return [this.hour < 10 ? '0' + this.hour : this.hour, this.minute < 10 ? '0' + this.minute : this.minute, this.second < 10 ? '0' + this.second : this.second].join(':'); - default: - return [this.year, this.month < 10 ? '0' + this.month : this.month, this.date < 10 ? '0' + this.date : this.date].join('-'); - } - } -} -nodom.PluginManager.add('UI-DATETIME', UIDatetime); -class UIDialog extends nodom.Plugin { - constructor(params) { - super(params); - this.tagName = 'UI-DIALOG'; - let rootDom = new nodom.Element(); - if (params) { - let panel = new UIPanel(params); - this.generate(rootDom, panel); - } - rootDom.tagName = 'div'; - rootDom.plugin = this; - this.element = rootDom; - } - generate(rootDom, panel) { - const me = this; - this.dataName = '$ui_dialog_' + nodom.Util.genId(); - rootDom.addClass('nd-dialog'); - let panelDom = panel.element; - rootDom.setProp('name', panelDom.getProp('name')); - this.autoOpen = panelDom.hasProp('autoopen'); - this.onClose = panelDom.getProp('onclose'); - this.onOpen = panelDom.getProp('onopen'); - panelDom.delProp(['name', 'autoopen']); - panel.addHeadBtn('close', () => { - me.close(); - }); - rootDom.addDirective(new nodom.Directive('show', this.dataName, rootDom)); - let dialogBody = new nodom.Element('div'); - dialogBody.addClass('nd-dialog-body'); - dialogBody.add(panelDom); - let coverDom = new nodom.Element('div'); - coverDom.addClass('nd-dialog-cover'); - rootDom.add(coverDom); - rootDom.add(dialogBody); - } - beforeRender(module, dom) { - super.beforeRender(module, dom); - if (this.needPreRender) { - if (this.autoOpen) { - this.open(); - } - } - } - open() { - let module = nodom.ModuleFactory.get(this.moduleId); - if (module) { - let model = module.modelFactory.get(this.modelId); - if (model) { - model.set(this.dataName, true); - } - if (this.onOpen) { - let foo = module.methodFactory.get(this.onOpen); - if (foo) { - nodom.Util.apply(foo, model, [model, module]); - } - } - } - } - close() { - let module = nodom.ModuleFactory.get(this.moduleId); - if (module) { - let model = module.modelFactory.get(this.modelId); - if (model) { - model.set(this.dataName, false); - } - if (this.onClose) { - let foo = module.methodFactory.get(this.onClose); - if (foo) { - nodom.Util.apply(foo, model, [model, module]); - } - } - } - } -} -nodom.PluginManager.add('UI-DIALOG', UIDialog); -class UIFile extends nodom.Plugin { - constructor(params) { - super(params); - this.tagName = 'UI-FILE'; - this.state = 0; - this.maxCount = 1; - this.count = 0; - let rootDom = new nodom.Element(); - if (params) { - if (params instanceof HTMLElement) { - nodom.Compiler.handleAttributes(rootDom, params); - UITool.handleUIParam(rootDom, this, ['valuefield', 'displayfield', 'multiple|bool', 'filetype', 'maxcount|number', 'uploadurl', 'deleteurl', 'uploadname'], ['valueField', 'displayField', 'multiple', 'fileType', 'maxCount', 'uploadUrl', 'deleteUrl', 'uploadName'], [null, null, null, '', 1, null, '', 'file']); - } - else if (typeof params === 'object') { - for (let o in params) { - this[o] = params[o]; - } - } - this.generate(rootDom); - } - rootDom.tagName = 'span'; - rootDom.plugin = this; - this.element = rootDom; - } - generate(rootDom) { - rootDom.addClass('nd-file'); - this.extraDataName = '$ui_file_' + nodom.Util.genId(); - let field = rootDom.getDirective('field'); - if (field) { - this.dataName = field.value; - rootDom.removeDirectives(['field']); - rootDom.events.delete('change'); - } - if (!this.multiple) { - this.maxCount = 1; - } - rootDom.children = [this.genShowDom(), this.genUploadDom()]; - rootDom.plugin = this; - return rootDom; - } - genUploadDom() { - const me = this; - let uploadDom = new nodom.Element('div'); - uploadDom.addClass('nd-file-uploadct'); - uploadDom.addDirective(new nodom.Directive('show', this.dataName + '.length<' + this.maxCount, uploadDom)); - let fDom = new nodom.Element('input'); - fDom.setProp('type', 'file'); - fDom.addClass('nd-file-input'); - fDom.addEvent(new nodom.NodomEvent('change', (dom, model, module, e, el) => { - if (!el.files) { - return; - } - model.set(me.extraDataName + '.state', 1); - model.set(me.extraDataName + '.uploading', NUITipWords.uploading); - let form = new FormData(); - for (let f of el.files) { - form.append(me.uploadName, f); - } - nodom.request({ - url: me.uploadUrl, - method: 'POST', - params: form, - header: { - 'Content-Type': 'multipart/form-data' - }, - type: 'json' - }).then((r) => { - model.set(me.extraDataName + '.state', 0); - model.query(me.dataName).push(r); - }); - })); - let uploadingDom = new nodom.Element('div'); - uploadingDom.addClass('nd-file-uploading'); - let span1 = new nodom.Element('span'); - span1.addClass('nd-file-add'); - span1.addDirective(new nodom.Directive('show', this.extraDataName + '.state==0', span1)); - uploadingDom.add(span1); - let span2 = new nodom.Element('span'); - span2.addClass('nd-file-progress'); - span2.addDirective(new nodom.Directive('show', this.extraDataName + '.state==1', span2)); - let txt = new nodom.Element(); - txt.expressions = [new nodom.Expression((this.extraDataName + '.uploading') || NUITipWords.uploading)]; - span2.add(txt); - uploadingDom.add(span2); - uploadDom.add(uploadingDom); - uploadDom.add(fDom); - return uploadDom; - } - genShowDom() { - const me = this; - let ctDom = new nodom.Element('div'); - ctDom.addClass('nd-file-showct'); - ctDom.addDirective(new nodom.Directive('repeat', this.dataName, ctDom)); - let showDom = new nodom.Element('a'); - showDom.addClass('nd-file-content'); - showDom.setProp('target', 'blank'); - let expr = new nodom.Expression(this.displayField); - showDom.setProp('href', expr, true); - if (this.fileType === 'image') { - let img = new nodom.Element('img'); - img.setProp('src', expr, true); - showDom.add(img); - } - else { - let txt = new nodom.Element(); - txt.expressions = [expr]; - showDom.add(txt); - } - ctDom.add(showDom); - let delDom = new nodom.Element('b'); - delDom.addClass('nd-file-del'); - ctDom.add(delDom); - delDom.addEvent(new nodom.NodomEvent('click', (dom, model, module, e) => { - let params = {}; - let id = model.query(me.valueField); - params[me.valueField] = id; - if (this.deleteUrl !== '') { - nodom.request({ - url: me.deleteUrl, - params: params - }).then((r) => { - me.removeFile(module, id); - }); - } - else { - me.removeFile(module, id); - } - })); - return ctDom; - } - removeFile(module, id) { - let pm = module.modelFactory.get(this.modelId); - let rows = pm.query(this.dataName); - if (Array.isArray(rows)) { - for (let i = 0; i < rows.length; i++) { - if (rows[i][this.valueField] === id) { - rows.splice(i, 1); - break; - } - } - } - } - beforeRender(module, dom) { - super.beforeRender(module, dom); - if (this.needPreRender) { - let model = module.modelFactory.get(dom.modelId); - if (model) { - model.set(this.extraDataName, { - state: 0, - uploading: false - }); - } - } - } -} -nodom.PluginManager.add('UI-FILE', UIFile); -class UIForm extends nodom.Plugin { - constructor(params) { - super(params); - this.tagName = 'UI-FORM'; - let rootDom = new nodom.Element(); - if (params) { - if (params instanceof HTMLElement) { - nodom.Compiler.handleAttributes(rootDom, params); - nodom.Compiler.handleChildren(rootDom, params); - UITool.handleUIParam(rootDom, this, ['labelwidth|number'], ['labelWidth'], [100]); - } - else if (typeof params === 'object') { - for (let o in params) { - this[o] = params[o]; - } - } - this.generate(rootDom); - } - rootDom.tagName = 'form'; - rootDom.plugin = this; - this.element = rootDom; - } - generate(rootDom) { - rootDom.addClass('nd-form'); - for (let c of rootDom.children) { - if (!c.tagName) { - continue; - } - c.addClass('nd-form-item'); - if (c.children) { - for (let c1 of c.children) { - if (c1.tagName === 'LABEL') { - c1.assets.set('style', 'width:' + this.labelWidth + 'px'); - break; - } - } - } - } - } -} -nodom.PluginManager.add('UI-FORM', UIForm); -class UIGrid extends nodom.Plugin { - constructor(params) { - super(params); - this.tagName = 'UI-GRID'; - this.fields = []; - let rootDom = new nodom.Element(); - if (params) { - if (params instanceof HTMLElement) { - nodom.Compiler.handleAttributes(rootDom, params); - nodom.Compiler.handleChildren(rootDom, params); - UITool.handleUIParam(rootDom, this, ['dataname', 'rowalt|bool', 'sortable|bool', 'gridline', 'fixhead|bool', 'hidehead|bool', 'dataurl'], ['dataName', 'rowAlt', 'sortable', 'gridLine', 'fixHead', 'hideHead', 'dataUrl'], ['rows', null, null, '', null, null, null, null]); - } - else if (typeof params === 'object') { - for (let o in params) { - this[o] = params[o]; - } - } - rootDom.tagName = 'div'; - rootDom = this.generate(rootDom); - } - rootDom.plugin = this; - this.element = rootDom; - } - generate(rootDom) { - rootDom.addClass('nd-grid'); - this.extraDataName = '$ui_grid_' + nodom.Util.genId(); - if (this.fixHead) { - rootDom.addClass('nd-grid-fixed'); - } - let thead; - if (!this.hideHead) { - thead = new nodom.Element('div'); - thead.addClass('nd-grid-head'); - } - let tbody = new nodom.Element('div'); - tbody.addClass('nd-grid-body'); - if (this.rowAlt) { - tbody.addClass('nd-grid-body-rowalt'); - } - let rowDom; - let subDom; - let pagination; - for (let c of rootDom.children) { - if (c.tagName === 'COLS') { - rowDom = c; - } - else if (c.tagName === 'SUB') { - subDom = c; - } - else if (c.plugin && c.plugin.tagName === 'UI-PAGINATION') { - pagination = c; - } - } - if (rowDom) { - this.rowDomKey = rowDom.key; - let filter; - if (pagination) { - this.selectPageMethodId = '$$nodom_method_gen_' + nodom.Util.genId(); - filter = new nodom.Filter('select:func:' + this.selectPageMethodId); - } - let directive = new nodom.Directive('repeat', this.extraDataName + '.' + this.dataName, rowDom); - if (filter) { - directive.filters = [filter]; - } - rowDom.addDirective(directive); - rowDom.tagName = 'div'; - let dataDom = new nodom.Element('div'); - dataDom.addClass('nd-grid-row'); - if (this.gridLine === 'col' || this.gridLine === 'both') { - dataDom.addClass('nd-grid-col-line'); - } - if (this.gridLine === 'row' || this.gridLine === 'both') { - dataDom.addClass('nd-grid-row-line'); - } - for (let i = 0; i < rowDom.children.length; i++) { - let c = rowDom.children[i]; - if (!c.tagName) { - rowDom.children.splice(i--, 1); - continue; - } - if (c.hasProp('hide')) { - c.delProp('hide'); - continue; - } - let field = c.getProp('field'); - if (field) { - field = field.trim(); - } - this.fields.push({ - title: c.getProp('title'), - field: field, - expressions: c.children[0].expressions - }); - this.addToHead(c, i, thead, field); - let tdIn = c.children[0]; - switch (c.getProp('type')) { - case 'img': - tdIn.tagName = 'img'; - tdIn.setProp('src', tdIn.expressions, true); - c.children = [tdIn]; - delete tdIn.expressions; - break; - } - c.tagName = 'div'; - c.addClass('nd-grid-row-item'); - if (c.hasProp('left')) { - c.addClass('nd-grid-row-item-left'); - } - if (c.hasProp('width') && nodom.Util.isNumberString(c.getProp('width'))) { - c.setProp('style', 'flex:' + c.getProp('width')); - } - dataDom.add(c); - c.delProp(['title', 'type', 'width', 'field', 'notsort', 'left']); - } - rowDom.children = [dataDom]; - rowDom.delProp('data'); - if (subDom) { - this.handleSub(subDom, thead, dataDom, rowDom); - } - tbody.add(rowDom); - } - if (thead) { - rootDom.children = [thead, tbody]; - if (this.gridLine === 'row' || this.gridLine === 'both') { - rootDom.addClass('nd-grid-ct-row-line'); - } - } - else { - rootDom.children = [tbody]; - } - if (this.gridLine === 'row' || this.gridLine === 'both') { - rootDom.addClass('nd-grid-ct-row-line'); - } - if (this.gridLine === 'col' || this.gridLine === 'both') { - rootDom.addClass('nd-grid-ct-col-line'); - } - if (pagination) { - let parentDom = new nodom.Element('div'); - parentDom.children = [rootDom, pagination]; - pagination.addClass('nd-grid-pager'); - this.handlePagination(pagination); - return parentDom; - } - return rootDom; - } - addToHead(col, index, thead, field) { - if (!thead) { - return; - } - if (thead.children.length === 0) { - let thCt = new nodom.Element('div'); - thCt.addClass('nd-grid-row'); - if (this.gridLine === 'col' || this.gridLine === 'both') { - thCt.addClass('nd-grid-col-line'); - } - if (this.gridLine === 'row' || this.gridLine === 'both') { - thCt.addClass('nd-grid-row-line'); - } - thead.add(thCt); - } - if (thead) { - let th = new nodom.Element('div'); - th.addClass('nd-grid-row-item'); - th.setProp('style', 'flex:' + col.getProp('width') || 0); - let span = new nodom.Element('span'); - span.assets.set('innerHTML', col.getProp('title')); - th.add(span); - if (this.sortable) { - if (col.getProp('type') !== 'img' && !col.hasProp('notsort') && field) { - th.add(this.addSortBtn(index)); - } - } - thead.children[0].add(th); - } - } - addSortBtn(index) { - let updown = new nodom.Element('span'); - updown.addClass('nd-grid-sort'); - let up = new nodom.Element('B'); - up.addClass('nd-grid-sort-raise'); - up.tmpData = { index: index }; - let down = new nodom.Element('B'); - down.addClass('nd-grid-sort-down'); - down.tmpData = { index: index }; - const plugin = this; - up.addEvent(new nodom.NodomEvent('click', (dom, model, module, e) => { - plugin.sort(parseInt(dom.tmpData['index']), 'asc', module); - })); - down.addEvent(new nodom.NodomEvent('click', (dom, model, module, e) => { - plugin.sort(parseInt(dom.tmpData['index']), 'desc', module); - })); - updown.add(up); - updown.add(down); - return updown; - } - handleSub(subDom, thead, dataDom, rowDom) { - let th = new nodom.Element('div'); - th.addClass('nd-grid-iconcol'); - let b = new nodom.Element('b'); - b.addClass('nd-grid-sub-btn'); - th.add(b); - if (thead) { - thead.children[0].children.unshift(th); - } - let td = new nodom.Element('div'); - td.addClass('nd-grid-iconcol'); - b = new nodom.Element('b'); - b.addClass('nd-grid-sub-btn'); - b.addDirective(new nodom.Directive('class', "{'nd-grid-showsub':'$showSub'}", b)); - b.addEvent(new nodom.NodomEvent('click', ':delg', (dom, model, module, e) => { - model.set('$showSub', !model.data['$showSub']); - })); - td.add(b); - dataDom.children.unshift(td); - subDom.tagName = 'div'; - rowDom.add(subDom); - subDom.addDirective(new nodom.Directive('show', '$showSub', subDom)); - subDom.addClass('nd-grid-sub'); - if (subDom.hasProp('auto')) { - subDom.children = []; - let lw = subDom.getProp('labelwidth') || 100; - let cols = subDom.hasProp('cols') ? parseInt(subDom.getProp('cols')) : 1; - if (cols > 4) { - cols = 4; - } - let cnt = 0; - let rowCt; - this.fields.forEach((item) => { - if (cnt++ % cols === 0) { - rowCt = new nodom.Element('div'); - rowCt.addClass('nd-grid-sub-row'); - subDom.add(rowCt); - } - let itemCt = new nodom.Element('div'); - itemCt.addClass('nd-grid-sub-item'); - let label = new nodom.Element('label'); - label.assets.set('innerHTML', item['title'] + ':'); - label.assets.set('style', 'width:' + lw + 'px'); - itemCt.add(label); - let span = new nodom.Element('span'); - span.addClass('nd-grid-sub-content'); - let txt = new nodom.Element(); - txt.expressions = item['expressions']; - span.add(txt); - itemCt.add(span); - rowCt.add(itemCt); - subDom.delProp(['auto', 'labelwidth']); - }); - } - } - sort(index, asc, module) { - let dom = module.virtualDom.query(this.rowDomKey); - let directive = dom.getDirective('repeat'); - if (!directive) { - return; - } - let f = this.fields[index]; - if (!f || !f['field']) { - return; - } - let arr = ['orderby', f['field'], asc]; - if (!directive.filters) { - directive.filters = []; - } - if (directive.filters.length <= 1) { - directive.filters.push(new nodom.Filter(arr)); - } - else { - directive.filters[1] = new nodom.Filter(arr); - } - nodom.Renderer.add(module); - } - beforeRender(module, uidom) { - let me = this; - super.beforeRender(module, uidom); - if (this.needPreRender) { - let model = module.modelFactory.get(uidom.modelId); - model.set(this.extraDataName, {}); - if (!this.pagination) { - this.doReq(module, this.pagination); - } - if (this.selectPageMethodId) { - module.methodFactory.add(this.selectPageMethodId, (arr) => { - let start = (me.currentPage - 1) * me.pageSize; - let end = start + me.pageSize; - return arr.slice(start, end); - }); - } - } - } - handlePagination(pagination) { - let me = this; - let df = pagination.plugin; - this.pagination = df; - df.dataUrl = this.dataUrl; - if (df.currentPage) { - this.currentPage = df.currentPage; - } - if (df.pageSize) { - this.pageSize = df.pageSize; - } - if (!df.onChange) { - df.onChange = (module) => { - me.doReq(module, df); - }; - } - } - doReq(module, pagination) { - const me = this; - let params = {}; - if (pagination) { - let reqName = pagination.requestName; - if (reqName.length === 2) { - params[reqName[0]] = pagination.currentPage; - params[reqName[1]] = pagination.pageSize; - } - } - nodom.request({ - url: me.dataUrl, - params: params, - type: 'json' - }).then(r => { - if (!r) { - return; - } - let model = module.modelFactory.get(me.modelId); - model.set(this.extraDataName, r); - if (pagination) { - if (pagination.pageSize) { - this.pageSize = pagination.pageSize; - } - model.set(pagination.extraDataName + '.total', r[pagination.totalName]); - pagination.changeParams(module); - } - }); - } - getData() { - let module = nodom.ModuleFactory.get(this.moduleId); - let model = module.modelFactory.get(this.modelId); - model = model.get(this.extraDataName); - let data = model.getData(); - if (data) { - return data[this.dataName]; - } - } -} -nodom.PluginManager.add('UI-GRID', UIGrid); -class UILayout extends nodom.Plugin { - constructor(params) { - super(params); - this.tagName = 'UI-LAYOUT'; - let rootDom = new nodom.Element(); - if (params) { - if (params instanceof HTMLElement) { - nodom.Compiler.handleAttributes(rootDom, params); - nodom.Compiler.handleChildren(rootDom, params); - } - else if (typeof params === 'object') { - for (let o in params) { - this[o] = params[o]; - } - } - this.generate(rootDom); - } - rootDom.tagName = 'div'; - rootDom.plugin = this; - this.element = rootDom; - } - generate(rootDom) { - rootDom.addClass('nd-layout'); - this.extraDataName = '$ui_layout_' + nodom.Util.genId(); - let middleCt = new nodom.Element(); - middleCt.addClass('nd-layout-middle'); - middleCt.tagName = 'DIV'; - let items = {}; - let locs = ['north', 'west', 'center', 'east', 'south']; - for (let i = 0; i < rootDom.children.length; i++) { - let item = rootDom.children[i]; - if (!item.tagName) { - continue; - } - for (let l of locs) { - if (item.hasProp(l)) { - item.addClass('nd-layout-' + l); - items[l] = item; - if (l === 'west') { - this.handleEastAndWest(item, 0); - } - else if (l === 'east') { - this.handleEastAndWest(item, 1); - } - break; - } - } - } - rootDom.children = []; - if (items['north']) { - rootDom.children.push(items['north']); - } - if (items['west']) { - middleCt.children.push(items['west']); - } - if (items['center']) { - middleCt.children.push(items['center']); - } - if (items['east']) { - middleCt.children.push(items['east']); - } - rootDom.children.push(middleCt); - if (items['south']) { - rootDom.children.push(items['south']); - } - } - beforeRender(module, dom) { - super.beforeRender(module, dom); - if (this.needPreRender) { - let model = module.modelFactory.get(dom.modelId); - model.set(this.extraDataName, { - openWest: true, - openEast: true, - westWidth: 0, - eastWidth: 0 - }); - } - } - handleEastAndWest(dom, loc) { - const me = this; - if (dom.hasProp('title') || dom.hasProp('allowmin')) { - let header = new nodom.Element('div'); - header.addClass('nd-layout-header'); - dom.children.unshift(header); - let title; - if (dom.hasProp('title')) { - title = new nodom.Element('div'); - title.addClass('nd-layout-title'); - let txt = new nodom.Element(); - txt.textContent = dom.getProp('title'); - title.add(txt); - header.add(title); - } - let icon; - if (dom.hasProp('allowmin')) { - icon = new nodom.Element('b'); - if (loc === 1) { - if (title) { - title.addDirective(new nodom.Directive('show', this.extraDataName + '.openEast', title)); - } - icon.addDirective(new nodom.Directive('class', "{'nd-icon-arrow-right':'" + this.extraDataName + ".openEast','nd-icon-arrow-left':'!" + this.extraDataName + ".openEast'}", icon)); - icon.addEvent(new nodom.NodomEvent('click', (dom, model, module, e, el) => { - let data = model.query(me.extraDataName); - let eastEl = el.parentNode.parentNode; - let compStyle = window.getComputedStyle(eastEl); - let width; - if (data.openEast) { - if (data.eastWidth === 0) { - data.eastWidth = compStyle.width; - } - width = '40px'; - } - else { - width = data.eastWidth; - } - eastEl.style.width = width; - data.openEast = !data.openEast; - })); - header.children.unshift(icon); - } - else { - if (title) { - title.addDirective(new nodom.Directive('show', this.extraDataName + '.openWest', title)); - } - icon.addDirective(new nodom.Directive('class', "{'nd-icon-arrow-left':'" + this.extraDataName + ".openWest','nd-icon-arrow-right':'!" + this.extraDataName + ".openWest'}", icon)); - icon.addEvent(new nodom.NodomEvent('click', (dom, model, module, e, el) => { - let data = model.query(me.extraDataName); - let westEl = el.parentNode.parentNode; - let compStyle = window.getComputedStyle(westEl); - let width; - if (data.openWest) { - if (data.westWidth === 0) { - data.westWidth = compStyle.width; - } - width = '40px'; - } - else { - width = data.westWidth; - } - westEl.style.width = width; - data.openWest = !data.openWest; - })); - header.add(icon); - } - } - } - } -} -nodom.PluginManager.add('UI-LAYOUT', UILayout); -class UIList extends nodom.Plugin { - constructor(params) { - super(params); - this.tagName = 'UI-LIST'; - let rootDom = new nodom.Element(); - if (params) { - if (params instanceof HTMLElement) { - nodom.Compiler.handleAttributes(rootDom, params); - nodom.Compiler.handleChildren(rootDom, params); - UITool.handleUIParam(rootDom, this, ['valuefield', 'displayfield', 'disablefield', 'listfield', 'type', 'itemclick', 'itemwidth|number', 'multiselect|bool'], ['valueField', 'displayField', 'disableName', 'listField', 'type', 'clickEvent', 'itemWidth', 'multiSelect'], ['', '', '', null, 'row', '', 0, null]); - } - else if (typeof params === 'object') { - for (let o in params) { - this[o] = params[o]; - } - } - this.generate(rootDom); - } - rootDom.tagName = 'div'; - rootDom.plugin = this; - this.element = rootDom; - } - generate(rootDom) { - let me = this; - this.extraDataName = '$ui_list_' + nodom.Util.genId(); - rootDom.addDirective(new nodom.Directive('model', this.extraDataName, rootDom)); - if (this.type === 'row') { - rootDom.addClass('nd-list'); - } - else { - rootDom.addClass('nd-list-horizontal'); - } - let field = rootDom.getDirective('field'); - if (field) { - this.dataName = field.value; - } - let itemDom; - for (let c of rootDom.children) { - if (!c.tagName) { - continue; - } - itemDom = c; - break; - } - if (!itemDom) { - itemDom = new nodom.Element('div'); - if (this.displayField !== '') { - let txt = new nodom.Element(); - txt.expressions = [new nodom.Expression(this.displayField)]; - itemDom.add(txt); - } - } - itemDom.addClass('nd-list-item'); - itemDom.addDirective(new nodom.Directive('repeat', 'datas', itemDom)); - itemDom.addEvent(new nodom.NodomEvent('click', (dom, model, module) => { - if (me.disableName !== '' && model.query(me.disableName)) { - return; - } - me.setValue(module, model); - })); - if (this.type === 'row') { - let item = new nodom.Element('div'); - item.children = itemDom.children; - item.addClass('nd-list-itemcontent'); - let icon = new nodom.Element('b'); - icon.addClass('nd-list-icon'); - itemDom.children = [item, icon]; - } - if (this.disableName !== '') { - itemDom.addDirective(new nodom.Directive('class', "{'nd-list-item-active':'selected','nd-list-item-disable':'" + this.disableName + "'}", itemDom)); - } - else { - itemDom.addDirective(new nodom.Directive('class', "{'nd-list-item-active':'selected'}", itemDom)); - } - if (this.clickEvent) { - itemDom.addEvent(new nodom.NodomEvent('click', this.clickEvent)); - } - rootDom.children = [itemDom]; - } - beforeRender(module, dom) { - super.beforeRender(module, dom); - let pmodel; - let model; - if (this.needPreRender) { - pmodel = module.modelFactory.get(this.modelId); - pmodel.set(this.extraDataName, { - datas: [] - }).id; - } - if (!pmodel) { - pmodel = module.modelFactory.get(this.modelId); - } - if (!model) { - model = pmodel.get(this.extraDataName); - } - let data = model.data; - if (this.listField && data.datas.length === 0 && pmodel.data[this.listField]) { - let valueArr; - if (this.dataName) { - let value = pmodel.query(this.dataName); - if (value && value !== '') { - valueArr = value.toString().split(','); - } - } - let rows = pmodel.query(this.listField); - if (rows && Array.isArray(rows)) { - rows = nodom.Util.clone(rows); - if (this.valueField !== '') { - for (let d of rows) { - if (valueArr && valueArr.includes(d[this.valueField] + '')) { - d.selected = true; - } - else { - d.selected = false; - } - } - } - model.set('datas', rows); - this.setValue(module); - } - } - } - setValue(module, model) { - let pmodel = module.modelFactory.get(this.modelId); - let model1 = pmodel.get(this.extraDataName); - let rows = model1.data['datas']; - let valArr = []; - if (this.multiSelect) { - if (model) { - model.set('selected', !model.data.selected); - } - if (this.valueField !== '' && this.dataName) { - for (let d of rows) { - if (d.selected) { - valArr.push(d[this.valueField]); - } - } - pmodel.set(this.dataName, valArr.join(',')); - } - } - else { - if (model) { - for (let d of rows) { - if (d.selected) { - d.selected = false; - break; - } - } - model.set('selected', !model.data.selected); - } - for (let d of rows) { - if (d.selected) { - if (this.valueField !== '' && this.dataName) { - pmodel.set(this.dataName, d[this.valueField]); - } - break; - } - } - } - } -} -nodom.PluginManager.add('UI-LIST', UIList); -class UIListTransfer extends nodom.Plugin { - constructor(params) { - super(params); - this.tagName = 'UI-LISTTRANSFER'; - let rootDom = new nodom.Element(); - if (params) { - if (params instanceof HTMLElement) { - nodom.Compiler.handleAttributes(rootDom, params); - nodom.Compiler.handleChildren(rootDom, params); - UITool.handleUIParam(rootDom, this, ['valuefield', 'displayfield', 'listfield'], ['valueField', 'displayField', 'listField']); - } - else if (typeof params === 'object') { - for (let o in params) { - this[o] = params[o]; - } - } - this.generate(rootDom); - } - rootDom.tagName = 'div'; - rootDom.plugin = this; - this.element = rootDom; - } - generate(rootDom) { - let me = this; - this.extraDataName = '$ui_listtransfer_' + nodom.Util.genId(); - rootDom.addDirective(new nodom.Directive('model', this.extraDataName, rootDom)); - rootDom.addClass('nd-listtransfer'); - let field = rootDom.getDirective('field'); - if (field) { - this.dataName = field.value; - } - let listDom = new nodom.Element('div'); - listDom.addClass('nd-list'); - let itemDom; - for (let c of rootDom.children) { - if (!c.tagName) { - continue; - } - itemDom = c; - break; - } - if (!itemDom) { - itemDom = new nodom.Element('div'); - let txt = new nodom.Element(); - txt.expressions = [new nodom.Expression(this.displayField)]; - itemDom.add(txt); - } - itemDom.addClass('nd-list-item'); - itemDom.addDirective(new nodom.Directive('repeat', 'datas', itemDom, "select:value:{isValue:false}")); - itemDom.addDirective(new nodom.Directive('class', "{'nd-list-item-active':'selected'}", itemDom)); - itemDom.addEvent(new nodom.NodomEvent('click', (dom, model, module) => { - model.set('selected', !model.data.selected); - })); - let item = new nodom.Element('div'); - item.children = itemDom.children; - item.addClass('nd-list-itemcontent'); - let icon = new nodom.Element('b'); - icon.addClass('nd-list-icon'); - itemDom.children = [item, icon]; - listDom.children = [itemDom]; - let listDom1 = listDom.clone(true); - listDom1.children[0].getDirective('repeat').filters = [new nodom.Filter("select:value:{isValue:true}")]; - let btnGrp = new nodom.Element('div'); - btnGrp.addClass('nd-listtransfer-btngrp'); - let btn1 = new nodom.Element('b'); - btn1.addClass('nd-listtransfer-right2'); - let btn2 = new nodom.Element('b'); - btn2.addClass('nd-listtransfer-right1'); - let btn3 = new nodom.Element('b'); - btn3.addClass('nd-listtransfer-left1'); - let btn4 = new nodom.Element('b'); - btn4.addClass('nd-listtransfer-left2'); - btnGrp.children = [btn1, btn2, btn3, btn4]; - btn1.addEvent(new nodom.NodomEvent('click', (dom, model, module, e) => { - me.transfer(module, 1, true); - })); - btn2.addEvent(new nodom.NodomEvent('click', (dom, model, module, e) => { - me.transfer(module, 1, false); - })); - btn3.addEvent(new nodom.NodomEvent('click', (dom, model, module, e) => { - me.transfer(module, 2, false); - })); - btn4.addEvent(new nodom.NodomEvent('click', (dom, model, module, e) => { - me.transfer(module, 2, true); - })); - rootDom.children = [listDom, btnGrp, listDom1]; - rootDom.plugin = this; - return rootDom; - } - beforeRender(module, dom) { - super.beforeRender(module, dom); - let pmodel; - if (this.needPreRender) { - pmodel = module.modelFactory.get(this.modelId); - let model = pmodel.set(this.extraDataName, { - datas: [] - }); - this.extraModelId = model.id; - let value = pmodel.query(this.dataName); - let datas = pmodel.query(this.listField); - let rows = []; - if (Array.isArray(datas)) { - let va = []; - if (value) { - va = value.split(','); - } - rows = nodom.Util.clone(datas); - for (let d of rows) { - d.selected = false; - d.isValue = false; - if (va && va.includes(d[this.valueField] + '')) { - d.isValue = true; - } - } - } - model.set('datas', rows); - } - } - transfer(module, direction, all) { - let model = module.modelFactory.get(this.extraModelId); - let datas = model.data.datas; - let isValue = direction === 1 ? true : false; - for (let d of datas) { - if (all) { - d.isValue = isValue; - } - else if (d.selected) { - d.isValue = isValue; - } - d.selected = false; - } - this.updateValue(module); - } - updateValue(module) { - let pmodel = module.modelFactory.get(this.modelId); - let model = module.modelFactory.get(this.extraModelId); - let a = []; - for (let d of model.data.datas) { - if (d.isValue) { - a.push(d[this.valueField]); - } - } - pmodel.set(this.dataName, a.join(',')); - } -} -nodom.PluginManager.add('UI-LISTTRANSFER', UIListTransfer); -class UIMenu extends nodom.Plugin { - constructor(params) { - super(params); - this.tagName = 'UI-MENU'; - this.menuHeight = 30; - this.direction = 0; - let rootDom = new nodom.Element(); - if (params) { - if (params instanceof HTMLElement) { - nodom.Compiler.handleAttributes(rootDom, params); - nodom.Compiler.handleChildren(rootDom, params); - UITool.handleUIParam(rootDom, this, ['popup|bool', 'position', 'listfield', 'maxlevel|number', 'menuwidth|number'], ['popupMenu', 'position', 'listField', 'maxLevel', 'menuWidth'], [null, 'top', null, 3, 150]); - } - else if (typeof params === 'object') { - for (let o in params) { - this[o] = params[o]; - } - } - this.generate(rootDom); - } - rootDom.tagName = 'div'; - rootDom.plugin = this; - this.element = rootDom; - } - generate(rootDom) { - let me = this; - this.activeName = '$nui_menu_' + nodom.Util.genId(); - this.menuStyleName = '$nui_menu_' + nodom.Util.genId(); - rootDom.addClass('nd-menu'); - if (this.position === 'left' || this.position === 'right') { - this.popupMenu = true; - } - let menuNode; - for (let i = 0; i < rootDom.children.length; i++) { - if (rootDom.children[i].tagName) { - menuNode = rootDom.children[i]; - menuNode.addClass('nd-menu-node'); - let b = new nodom.Element('b'); - menuNode.children.unshift(b); - if (menuNode.hasProp('icon')) { - b.setProp('class', ['nd-icon-', new nodom.Expression(menuNode.getProp('icon'))], true); - menuNode.delProp('icon'); - } - break; - } - } - rootDom.children = []; - let parentCt = new nodom.Element('div'); - parentCt.addClass('nd-menu-subct'); - if (this.popupMenu) { - if (this.position === 'left' || this.position === 'right') { - rootDom.addClass('nd-menu-left'); - rootDom.addEvent(new nodom.NodomEvent('mouseleave', (dom, model, module, e) => { - dom.assets.set('style', 'width:30px'); - })); - parentCt.addEvent(new nodom.NodomEvent('mouseenter', (dom, model, module, e) => { - dom.assets.set('style', 'width:' + me.menuWidth + 'px'); - })); - } - else { - rootDom.addClass('nd-menu-popup'); - parentCt.addClass('nd-menu-first'); - parentCt.setProp('style', new nodom.Expression(this.menuStyleName), true); - parentCt.addEvent(new nodom.NodomEvent('mouseleave', (dom, model, module, e) => { - let parent = dom.getParent(module); - let pmodel = module.modelFactory.get(parent.modelId); - pmodel.set(me.activeName, false); - if (dom.hasClass('nd-menu-first')) { - this.direction = 0; - } - })); - parentCt.addDirective(new nodom.Directive('show', this.activeName, parentCt)); - } - } - else { - parentCt.addClass('nd-menu-first-nopop'); - } - rootDom.add(parentCt); - for (let i = 0; i < this.maxLevel; i++) { - parentCt.tmpData = { level: i + 1 }; - let itemCt = new nodom.Element('div'); - itemCt.directives.push(new nodom.Directive('repeat', this.listField, itemCt)); - itemCt.addClass('nd-menu-nodect'); - let item = menuNode.clone(true); - itemCt.add(item); - itemCt.tmpData = { level: (i + 1) }; - if (this.popupMenu || i > 0) { - let icon1 = new nodom.Element('b'); - icon1.addDirective(new nodom.Directive('class', "{'nd-menu-subicon':'" + this.listField + "&&" + this.listField + ".length>0'}", icon1)); - item.add(icon1); - } - let openClose = this.initOpenAndClose(); - itemCt.addEvent(openClose[0]); - itemCt.addEvent(openClose[1]); - parentCt.add(itemCt); - let subCt = new nodom.Element('div'); - subCt.addClass('nd-menu-subct'); - subCt.addEvent(new nodom.NodomEvent('mouseleave', (dom, model, module, e) => { - let parent = dom.getParent(module); - let pmodel = module.modelFactory.get(parent.modelId); - pmodel.set(me.activeName, false); - })); - subCt.setProp('style', new nodom.Expression(this.menuStyleName), true); - subCt.addDirective(new nodom.Directive('show', this.activeName, subCt)); - itemCt.add(subCt); - parentCt = subCt; - } - rootDom.delProp(['listField', 'width', , 'maxlevels']); - } - beforeRender(module, uidom) { - let me = this; - super.beforeRender(module, uidom); - if (this.needPreRender && this.popupMenu && this.position !== 'left' && this.position !== 'right') { - UIEventRegister.addEvent('mousedown', module.id, uidom.key, (module, dom, inOrOut, e) => { - if (e.button !== 2) { - return; - } - let x = e.clientX; - let w = me.menuWidth; - let model = module.modelFactory.get(uidom.modelId); - let rows = model.query(me.listField); - if (rows && rows.length > 0) { - let h = rows.length * me.menuHeight; - let loc = this.cacPos(null, e.clientX, e.clientY, this.menuWidth, h); - model.set(me.menuStyleName, 'width:' + me.menuWidth + 'px;left:' + loc[0] + 'px;top:' + loc[1] + 'px'); - model.set(me.activeName, true); - } - }); - } - } - initOpenAndClose() { - let me = this; - let openEvent = new nodom.NodomEvent('mouseenter', (dom, model, module, e, el) => { - if (model) { - let rows = model.query(this.listField); - if (!rows || rows.length === 0) { - return; - } - let firstNopop = dom.tmpData.level === 1 && !me.popupMenu; - let h = rows.length * this.menuHeight; - let w = this.menuWidth; - let x, y; - if (firstNopop) { - x = e.clientX - e.offsetX; - y = e.clientY - e.offsetY + h; - } - else { - x = e.clientX - e.offsetX + w; - y = e.clientY - e.offsetY; - } - let loc = this.cacPos(dom, x, y, w, h, el); - model.set(this.menuStyleName, 'width:' + me.menuWidth + 'px;left:' + loc[0] + 'px;top:' + loc[1] + 'px'); - model.set(this.activeName, true); - } - }); - let closeEvent = new nodom.NodomEvent('mouseleave', (dom, model, module, e, el) => { - if (model) { - let rows = model.query(this.listField); - if (rows && rows.length > 0) { - model.set(me.activeName, false); - if (this.direction === 1) { - if (me.popupMenu) { - if (dom.tmpData['level'] === 2) { - this.direction = 0; - } - } - else if (dom.tmpData['level'] === 1) { - this.direction = 0; - } - } - } - } - }); - return [openEvent, closeEvent]; - } - cacPos(dom, x, y, w, h, el) { - let firstNopop = dom && !this.popupMenu && dom.tmpData['level'] === 1; - let widthOut = x + w > window.innerWidth; - let heightOut = y + h > window.innerHeight; - let top = dom ? 0 : y; - let left = dom ? 0 : x; - if (firstNopop) { - top = this.menuHeight; - } - else if (heightOut) { - if (dom) { - top = -h + this.menuHeight; - } - else { - top = window.innerHeight - h; - } - } - if (widthOut) { - this.direction = 1; - } - if (this.direction === 1) { - if (firstNopop) { - if (widthOut) { - left = el.offsetWidth - w; - } - } - else if (dom) { - left -= w + 1; - } - else if (widthOut) { - left -= w + 3; - } - } - else { - if (dom && !firstNopop) { - left = w; - } - } - return [left, top + 1]; - } -} -nodom.PluginManager.add('UI-MENU', UIMenu); -class UIPagination extends nodom.Plugin { - constructor(params) { - super(params); - this.tagName = 'UI-PAGINATION'; - this.minPage = 1; - this.maxPage = 1; - let rootDom = new nodom.Element(); - if (params) { - if (params instanceof HTMLElement) { - nodom.Compiler.handleAttributes(rootDom, params); - nodom.Compiler.handleChildren(rootDom, params); - UITool.handleUIParam(rootDom, this, ['totalname', 'pagesize|number', 'currentpage|number', 'showtotal|bool', 'showgo|bool', 'shownum|number', 'sizechange|array|number', 'steps|number', 'onchange', 'requestname|array|2', 'dataurl'], ['totalName', 'pageSize', 'currentPage', 'showTotal', 'showGo', 'showNum', 'pageSizeData', 'steps', 'onChange', 'requestName', 'dataUrl'], ['total', 10, 1, null, null, 10, [], 5, '', [], '']); - } - else if (typeof params === 'object') { - for (let o in params) { - this[o] = params[o]; - } - } - this.generate(rootDom); - } - rootDom.tagName = 'div'; - rootDom.plugin = this; - this.element = rootDom; - } - generate(rootDom) { - let me = this; - rootDom.addClass('nd-pagination'); - rootDom.children = []; - this.extraDataName = '$ui_pagination_' + nodom.Util.genId(); - rootDom.addDirective(new nodom.Directive('model', this.extraDataName, rootDom)); - if (this.showTotal) { - let totalDom = new nodom.Element('div'); - let txt = new nodom.Element(); - txt.textContent = NUITipWords.total; - totalDom.add(txt); - let span = new nodom.Element('span'); - span.addClass('nd-pagination-total'); - txt = new nodom.Element(); - txt.expressions = [new nodom.Expression('total')]; - span.add(txt); - totalDom.add(span); - txt = new nodom.Element(); - txt.textContent = NUITipWords.record; - totalDom.add(txt); - rootDom.add(totalDom); - } - if (this.pageSizeData && this.pageSizeData.length > 0) { - let datas = []; - for (let d of this.pageSizeData) { - datas.push({ - value: d, - text: d + NUITipWords.record + '/' + NUITipWords.page - }); - } - this.pageSizeDatas = datas; - rootDom.add(new UISelect({ - dataName: 'pageSize', - listField: 'sizeData', - displayField: 'text', - valueField: 'value', - onChange: (model, module, newValue, oldValue) => { - me.changeParams(module); - me.update(module); - } - }).element); - } - let pageCt = new nodom.Element('div'); - pageCt.addClass('nd-pagination-pagect'); - let left1 = new nodom.Element('b'); - left1.addClass('nd-pagination-leftarrow1'); - left1.addDirective(new nodom.Directive('class', "{'nd-pagination-disable':'[1,3,5,7,9,11,13,15].includes(btnAllow)'}", left1)); - pageCt.add(left1); - let left = new nodom.Element('b'); - left.addClass('nd-pagination-leftarrow'); - left.addDirective(new nodom.Directive('class', "{'nd-pagination-disable':'[2,3,6,7,10,11,15].includes(btnAllow)'}", left)); - pageCt.add(left); - let page = new nodom.Element('span'); - page.addClass('nd-pagination-page'); - page.addDirective(new nodom.Directive('repeat', 'pages', page)); - page.addDirective(new nodom.Directive('class', "{'nd-pagination-active':'active'}", page), true); - let txt = new nodom.Element(); - txt.expressions = [new nodom.Expression('no')]; - page.add(txt); - pageCt.add(page); - let right = new nodom.Element('b'); - right.addClass('nd-pagination-rightarrow'); - right.addDirective(new nodom.Directive('class', "{'nd-pagination-disable':'[4,5,6,7,12,13,15].includes(btnAllow)'}", right)); - pageCt.add(right); - let right1 = new nodom.Element('b'); - right1.addClass('nd-pagination-rightarrow1'); - right1.addDirective(new nodom.Directive('class', "{'nd-pagination-disable':'[8,9,10,11,12,13,15].includes(btnAllow)'}", right1)); - pageCt.add(right1); - rootDom.add(pageCt); - page.addEvent(new nodom.NodomEvent('click', (dom, model, module) => { - me.changeParams(module, model.data['no']); - me.update(module); - })); - left.addEvent(new nodom.NodomEvent('click', (dom, model, module) => { - if (dom.hasClass('nd-pagination-disable')) { - return; - } - me.changeParams(module, -1, true); - me.update(module); - })); - right.addEvent(new nodom.NodomEvent('click', (dom, model, module) => { - if (dom.hasClass('nd-pagination-disable')) { - return; - } - me.changeParams(module, 1, true); - me.update(module); - })); - left1.addEvent(new nodom.NodomEvent('click', (dom, model, module) => { - if (dom.hasClass('nd-pagination-disable')) { - return; - } - me.changeParams(module, -me.steps, true); - me.update(module); - })); - right1.addEvent(new nodom.NodomEvent('click', (dom, model, module) => { - if (dom.hasClass('nd-pagination-disable')) { - return; - } - me.changeParams(module, me.steps, true); - me.update(module); - })); - if (this.showGo) { - let goDom = new nodom.Element('div'); - goDom.addClass('nd-pagination-go'); - let txt = new nodom.Element(); - txt.textContent = NUITipWords.NO; - goDom.add(txt); - let input = new nodom.Element('input'); - input.setProp('type', 'number'); - input.addDirective(new nodom.Directive('field', 'pageNo', input)); - input.setProp('value', new nodom.Expression('pageNo'), true); - goDom.add(input); - txt = new nodom.Element(); - txt.textContent = NUITipWords.page; - goDom.add(txt); - rootDom.add(goDom); - } - rootDom.plugin = this; - return rootDom; - } - beforeRender(module, uidom) { - super.beforeRender(module, uidom); - this.handleInit(uidom, module); - } - update(module, current, isStep) { - if (this.onChange !== '') { - let foo; - if (typeof this.onChange === 'string') { - foo = module.methodFactory.get(this.onChange); - } - else if (nodom.Util.isFunction(this.onChange)) { - foo = this.onChange; - } - if (foo) { - foo.apply(this, [module, this.currentPage, this.pageSize]); - } - } - } - changeParams(module, current, isStep) { - let model = module.modelFactory.get(this.modelId); - let data = model.query(this.extraDataName); - let total = data.total; - if (!total) { - let data1 = model.data; - if (data1 && data1[this.totalName]) { - total = data1[this.totalName]; - } - if (total) { - data.total = total; - } - } - if (isStep) { - current = this.currentPage + current; - } - if (!total) { - return; - } - model = model.get(this.extraDataName); - let pageSize = model.data['pageSize']; - if (!current) { - let d = model.query('pageNo'); - if (typeof d === 'string' && d !== '') { - d = parseInt(d); - } - current = d || 1; - } - let pageCount = Math.ceil(total / pageSize); - if (current > pageCount) { - current = pageCount; - } - else if (current < 1) { - current = 1; - } - let min = 1; - let max; - let btnAllow = 0; - if (pageCount > this.showNum) { - let center = (this.showNum + 1) / 2 | 0; - if (current - center + 1 > 0) { - min = current - center + 1; - } - if (min < 1) { - min = 1; - } - else if (min + this.showNum - 1 > pageCount) { - min = pageCount - this.showNum + 1; - } - max = min + this.showNum - 1; - if (min === 1) { - btnAllow += 1; - } - if (max === pageCount) { - btnAllow += 8; - } - } - else { - min = 1; - max = pageCount; - btnAllow = 9; - } - if (current === pageCount) { - btnAllow += 4; - } - if (current === 1) { - btnAllow += 2; - } - if (model.query('pageSize') === this.pageSize && current === this.currentPage && min === this.minPage && max === this.maxPage) { - return; - } - let pageArr = []; - for (let i = min; i <= max; i++) { - let active = i === current ? true : false; - pageArr.push({ - no: i, - active: active - }); - } - this.currentPage = current; - this.minPage = min; - this.maxPage = max; - this.pageSize = model.data['pageSize']; - model.set('pages', pageArr); - model.set('pageSize', this.pageSize); - model.set('pageNo', current); - model.set('btnAllow', btnAllow); - } - handleInit(dom, module) { - if (!this.needPreRender) { - return; - } - let model = module.modelFactory.get(dom.modelId); - let model1 = model.set(this.extraDataName, { - total: 0, - pageNum: 0, - pageNo: this.currentPage || 1, - pageSize: this.pageSize, - btnAllow: 0, - pages: [], - sizeData: this.pageSizeDatas || [10, 20, 30, 50] - }); - this.extraModelId = model1.id; - this.changeParams(module, 1); - } -} -nodom.PluginManager.add('UI-PAGINATION', UIPagination); -class UIPanel extends nodom.Plugin { - constructor(params) { - super(params); - this.tagName = 'UI-PANEL'; - let rootDom = new nodom.Element(); - if (params) { - if (params instanceof HTMLElement) { - nodom.Compiler.handleAttributes(rootDom, params); - nodom.Compiler.handleChildren(rootDom, params); - UITool.handleUIParam(rootDom, this, ['title', 'buttons|array'], ['title', 'buttons'], ['Panel', []]); - } - else if (typeof params === 'object') { - for (let o in params) { - this[o] = params[o]; - } - } - this.generate(rootDom); - } - rootDom.tagName = 'div'; - rootDom.plugin = this; - this.element = rootDom; - } - generate(rootDom) { - let me = this; - rootDom.addClass('nd-panel'); - this.handleBody(rootDom); - let headerDom = new nodom.Element('div'); - headerDom.addClass('nd-panel-header'); - if (this.title) { - let titleCt = new nodom.Element('span'); - titleCt.addClass('nd-panel-title'); - titleCt.assets.set('innerHTML', this.title); - headerDom.add(titleCt); - } - let headbarDom = new nodom.Element('div'); - headbarDom.addClass('nd-panel-header-bar'); - this.headerBtnDom = headbarDom; - headerDom.add(headbarDom); - rootDom.children.unshift(headerDom); - for (let btn of this.buttons) { - let a = btn.split('|'); - this.addHeadBtn(a[0], a[1]); - } - } - handleBody(panelDom) { - let bodyDom = new nodom.Element('div'); - bodyDom.addClass('nd-panel-body'); - let tbar; - let btnGrp; - for (let i = 0; i < panelDom.children.length; i++) { - let item = panelDom.children[i]; - if (item.plugin) { - if (item.plugin.tagName === 'UI-TOOLBAR') { - tbar = item; - } - else if (item.plugin.tagName === 'UI-BUTTONGROUP') { - btnGrp = item; - } - } - else { - bodyDom.add(item); - } - } - panelDom.children = []; - if (tbar) { - panelDom.add(tbar); - } - panelDom.add(bodyDom); - if (btnGrp) { - panelDom.add(btnGrp); - } - } - addHeadBtn(icon, handler) { - let btn = new nodom.Element('b'); - btn.addClass('nd-icon-' + icon); - btn.addClass('nd-canclick'); - this.headerBtnDom.add(btn); - if (handler) { - btn.addEvent(new nodom.NodomEvent('click', handler)); - } - } -} -nodom.PluginManager.add('UI-PANEL', UIPanel); -class UIRadio extends nodom.Plugin { - constructor(params) { - super(params); - this.tagName = 'UI-RADIO'; - let rootDom = new nodom.Element(); - if (params) { - if (params instanceof HTMLElement) { - nodom.Compiler.handleAttributes(rootDom, params); - nodom.Compiler.handleChildren(rootDom, params); - } - else if (typeof params === 'object') { - for (let o in params) { - this[o] = params[o]; - } - } - this.generate(rootDom); - } - rootDom.tagName = 'span'; - rootDom.plugin = this; - this.element = rootDom; - } - generate(rootDom) { - rootDom.addClass('nd-radio'); - let field = rootDom.getDirective('field'); - if (field) { - this.dataName = field.value; - rootDom.removeDirectives(['field']); - } - for (let c of rootDom.children) { - if (c.tagName) { - let icon = new nodom.Element('b'); - icon.addClass('nd-radio-unactive'); - icon.addDirective(new nodom.Directive('class', "{'nd-radio-active':'" + this.dataName + "==\"" + c.getProp('value') + "\"'}", icon)); - c.children.unshift(icon); - c.addEvent(new nodom.NodomEvent('click', (dom, model, module) => { - let v = model.data[this.dataName]; - model.set(this.dataName, dom.getProp('value')); - })); - } - } - } -} -nodom.PluginManager.add('UI-RADIO', UIRadio); -class UIRelationMap extends nodom.Plugin { - constructor(params) { - super(params); - this.tagName = 'UI-RELATIONMAP'; - let rootDom = new nodom.Element(); - if (params) { - if (params instanceof HTMLElement) { - nodom.Compiler.handleAttributes(rootDom, params); - UITool.handleUIParam(rootDom, this, ['valuefield|array|1', 'displayfield|array|2', 'listfield|array|2'], ['valueField', 'displayField', 'listField'], [null, null, null]); - } - else if (typeof params === 'object') { - for (let o in params) { - this[o] = params[o]; - } - } - this.generate(rootDom); - } - rootDom.tagName = 'table'; - rootDom.plugin = this; - this.element = rootDom; - } - generate(rootDom) { - let me = this; - rootDom.addClass('nd-relationmap'); - this.mapName = '$ui_relationmap_' + nodom.Util.genId(); - let field = rootDom.getDirective('field'); - if (field) { - this.dataName = field.value; - rootDom.removeDirectives(['field']); - } - let rowHead = new nodom.Element('tr'); - rowHead.addClass('nd-relationmap-head'); - rootDom.add(rowHead); - let td = new nodom.Element('td'); - rowHead.add(td); - td = new nodom.Element('td'); - td.addDirective(new nodom.Directive('repeat', this.listField[0], td)); - let txt = new nodom.Element(); - txt.expressions = [new nodom.Expression(this.displayField[0])]; - td.add(txt); - rowHead.add(td); - let tr = new nodom.Element('tr'); - tr.addDirective(new nodom.Directive('repeat', '$$' + this.mapName, tr)); - tr.addClass('nd-relationmap-row'); - td = new nodom.Element('td'); - td.addClass('nd-relationmap-head'); - txt = new nodom.Element(); - txt.expressions = [new nodom.Expression('title')]; - td.add(txt); - tr.add(td); - td = new nodom.Element('td'); - td.addDirective(new nodom.Directive('repeat', 'cols', td)); - td.addEvent(new nodom.NodomEvent('click', (dom, model, module) => { - me.switchValue(module, dom, model); - })); - let b = new nodom.Element('b'); - b.addDirective(new nodom.Directive('class', "{'nd-relationmap-active':'active'}", b)); - td.add(b); - tr.add(td); - rootDom.children = [rowHead, tr]; - } - beforeRender(module, uidom) { - super.beforeRender(module, uidom); - let model = module.modelFactory.get(uidom.modelId); - let rowData = model.query(this.listField[1]); - let colData = model.query(this.listField[0]); - let data = model.query(this.dataName); - let idRow = this.valueField[1]; - let idCol = this.valueField[0]; - if (!module.model.query(this.mapName)) { - let mapData = []; - let title; - for (let d of rowData) { - let a1 = []; - let id1 = d[idRow]; - title = d[this.displayField[1]]; - for (let d1 of colData) { - let active = false; - if (data && data.length > 0) { - for (let da of data) { - if (da[idRow] === id1 && da[idCol] === d1[idCol]) { - active = true; - break; - } - } - } - a1.push({ - id1: id1, - id2: d1[idCol], - active: active - }); - } - mapData.push({ title: title, cols: a1 }); - } - module.model.set(this.mapName, mapData); - } - } - switchValue(module, dom, model) { - let pmodel = module.modelFactory.get(this.modelId); - let data = pmodel.query(this.dataName); - let id1 = model.data['id1']; - let id2 = model.data['id2']; - let active = model.data['active']; - let o = {}; - o[this.valueField[0]] = id2; - o[this.valueField[1]] = id1; - if (!data) { - if (!active) { - pmodel.set(this.dataName, [o]); - } - } - else { - if (!active) { - data.push(o); - } - else { - for (let i = 0; i < data.length; i++) { - let d = data[i]; - if (d[this.valueField[0]] === id2 && d[this.valueField[1]] === id1) { - data.splice(i, 1); - break; - } - } - } - } - model.set('active', !active); - } -} -nodom.PluginManager.add('UI-RELATIONMAP', UIRelationMap); -class UISelect extends nodom.Plugin { - constructor(params) { - super(params); - this.tagName = 'UI-SELECT'; - let rootDom = new nodom.Element(); - if (params) { - if (params instanceof HTMLElement) { - nodom.Compiler.handleAttributes(rootDom, params); - nodom.Compiler.handleChildren(rootDom, params); - UITool.handleUIParam(rootDom, this, ['valuefield', 'displayfield', 'multiselect|bool', 'listfield', 'listwidth|number', 'allowfilter|bool', 'onchange'], ['valueField', 'displayField', 'multiSelect', 'listField', 'listWidth', 'allowFilter', 'onChange'], [null, null, null, null, 0, null, '']); - } - else if (typeof params === 'object') { - for (let o in params) { - this[o] = params[o]; - } - } - this.generate(rootDom); - } - rootDom.tagName = 'div'; - rootDom.plugin = this; - this.element = rootDom; - } - generate(rootDom) { - let me = this; - this.extraDataName = '$ui_select_' + nodom.Util.genId(); - rootDom.addClass('nd-select'); - let field = rootDom.getDirective('field'); - if (field) { - this.dataName = field.value; - rootDom.removeDirectives(['field']); - rootDom.events.delete('change'); - } - rootDom.addDirective(new nodom.Directive('model', this.extraDataName, rootDom)); - let listDom = new nodom.Element('div'); - listDom.addClass('nd-select-list'); - if (this.listWidth) { - listDom.assets.set('style', 'width:' + this.listWidth + 'px'); - } - listDom.addDirective(new nodom.Directive('show', 'show', listDom)); - let itemDom; - for (let c of rootDom.children) { - if (!c.tagName) { - continue; - } - itemDom = c; - break; - } - if (!itemDom) { - itemDom = new nodom.Element('div'); - let txt = new nodom.Element(); - txt.expressions = [new nodom.Expression(this.displayField)]; - itemDom.add(txt); - } - let item = new nodom.Element('div'); - item.children = itemDom.children; - item.addClass('nd-select-itemcontent'); - itemDom.addClass('nd-select-item'); - let directive = new nodom.Directive('repeat', 'datas', itemDom); - itemDom.addDirective(directive); - itemDom.addDirective(new nodom.Directive('class', "{'nd-select-selected':'selected'}", itemDom)); - let icon = new nodom.Element('b'); - icon.addClass('nd-select-itemicon'); - itemDom.children = [item, icon]; - itemDom.addEvent(new nodom.NodomEvent('click', (dom, model, module) => { - me.setValue(module, model); - })); - let showDom = new nodom.Element('div'); - showDom.addClass('nd-select-inputct'); - let input = new nodom.Element('input'); - input.addClass('nd-select-show'); - if (this.multiSelect) { - input.setProp('readonly', true); - } - input.setProp('value', new nodom.Expression('display'), true); - showDom.add(input); - icon = new nodom.Element('b'); - showDom.addEvent(new nodom.NodomEvent('click', (dom, model, module, e, el) => { - if (model.data.show) { - me.hideList(module, model); - } - else { - model.set('show', true); - let height = el.offsetHeight; - let y = e.clientY + el.offsetHeight - e.offsetY; - UITool.adjustPosAndSize(module, this.listKey, e.clientX, y, height, null, true); - } - })); - if (this.allowFilter) { - this.filterMethodId = '$$nodom_method_' + nodom.Util.genId(); - let filter = new nodom.Filter(['select', 'func', this.filterMethodId]); - directive.filters = [filter]; - input.assets.set('readonly', 'true'); - let queryDom = new nodom.Element('input'); - queryDom.addClass('nd-select-search'); - queryDom.addDirective(new nodom.Directive('field', 'query', queryDom)); - queryDom.addDirective(new nodom.Directive('class', "{'nd-select-search-active':'show'}", queryDom)); - showDom.add(queryDom); - } - showDom.add(icon); - listDom.children = [itemDom]; - rootDom.children = [showDom, listDom]; - } - beforeRender(module, dom) { - let me = this; - super.beforeRender(module, dom); - this.listKey = dom.children[1].key; - let pmodel; - let model; - if (this.needPreRender) { - pmodel = module.modelFactory.get(this.modelId); - let model = pmodel.set(this.extraDataName, { - show: false, - display: '', - query: '', - datas: [] - }); - this.extraModelId = model.id; - module.methodFactory.add(this.filterMethodId, function () { - let model = this.modelFactory.get(me.extraModelId); - let rows = model.query('datas'); - if (rows) { - return rows.filter((item) => { - return model.data.query === '' || item[me.displayField].indexOf(model.data.query) !== -1; - }); - } - return []; - }); - UIEventRegister.addEvent('click', module.id, dom.key, (module, dom, inOrout, e) => { - let model = module.modelFactory.get(me.extraModelId); - if (!inOrout && model.data.show) { - me.hideList(module, model); - } - }); - model = module.modelFactory.get(this.extraModelId); - } - if (!pmodel) { - pmodel = module.modelFactory.get(this.modelId); - } - if (!model) { - model = module.modelFactory.get(this.extraModelId); - } - let data = model.data; - if (this.listField && data.datas.length === 0 && pmodel.data[this.listField]) { - let valueArr; - if (this.dataName) { - let value = pmodel.query(this.dataName); - if (value && value !== '') { - valueArr = value.toString().split(','); - } - } - let txtArr = []; - let rows = pmodel.query(this.listField); - if (rows && Array.isArray(rows)) { - rows = nodom.Util.clone(rows); - for (let d of rows) { - if (valueArr && valueArr.includes(d[this.valueField] + '')) { - d.selected = true; - txtArr.push(d[this.displayField]); - } - else { - d.selected = false; - } - } - model.set('datas', rows); - this.setValue(module); - } - } - } - setValue(module, model) { - let pmodel = module.modelFactory.get(this.modelId); - let model1 = module.modelFactory.get(this.extraModelId); - let rows = model1.data['datas']; - let txtArr = []; - let valArr = []; - let value; - if (this.multiSelect) { - if (model) { - model.set('selected', !model.data.selected); - } - for (let d of rows) { - if (d.selected) { - valArr.push(d[this.valueField]); - txtArr.push(d[this.displayField]); - } - } - if (this.dataName) { - value = valArr.join(','); - } - model1.set('display', txtArr.join(',')); - } - else { - if (model) { - for (let d of rows) { - if (d.selected) { - d.selected = false; - break; - } - } - model.set('selected', !model.data.selected); - } - for (let d of rows) { - if (d.selected) { - if (this.dataName) { - value = d[this.valueField]; - } - model1.set('display', d[this.displayField]); - this.hideList(module, model1); - break; - } - } - } - if (value !== this.value) { - pmodel.set(this.dataName, value); - if (this.onChange !== '') { - let foo; - if (typeof this.onChange === 'string') { - foo = module.methodFactory.get(this.onChange); - } - else { - foo = this.onChange; - } - if (nodom.Util.isFunction(foo)) { - foo.apply(null, [model, module, value, this.value]); - } - } - this.value = value; - } - } - hideList(module, model) { - if (!model) { - model = module.modelFactory.get(this.extraModelId); - } - model.set('show', false); - model.set('query', ''); - } -} -nodom.PluginManager.add('UI-SELECT', UISelect); -class UITab extends nodom.Plugin { - constructor(params) { - super(params); - this.tagName = 'UI-TAB'; - this.tabs = []; - let rootDom = new nodom.Element(); - if (params) { - if (params instanceof HTMLElement) { - nodom.Compiler.handleAttributes(rootDom, params); - nodom.Compiler.handleChildren(rootDom, params); - UITool.handleUIParam(rootDom, this, ['position', 'allowclose|bool', 'listField', 'height|number'], ['position', 'allowClose', 'listField', 'bodyHeight'], ['top', null, '', 0]); - } - else if (typeof params === 'object') { - for (let o in params) { - this[o] = params[o]; - } - } - this.generate(rootDom); - } - rootDom.tagName = 'div'; - rootDom.plugin = this; - this.element = rootDom; - } - generate(rootDom) { - let me = this; - this.extraDataName = '$ui_tab_' + nodom.Util.genId(); - this.name = rootDom.getProp('name'); - rootDom.addClass('nd-tab'); - if (this.position === 'left' || this.position === 'right') { - rootDom.addClass('nd-tab-horizontal'); - } - let headDom = new nodom.Element('div'); - headDom.addClass('nd-tab-head'); - let bodyDom = new nodom.Element('div'); - this.bodyKey = bodyDom.key; - bodyDom.addClass('nd-tab-body'); - if (this.bodyHeight > 0) { - bodyDom.assets.set('style', 'height:' + this.bodyHeight + 'px'); - } - let index = 1; - let activeIndex = 0; - let itemDom; - for (let c of rootDom.children) { - if (!c.tagName) { - continue; - } - let tabName = 'Tab' + index++; - let title = c.getProp('title') || tabName; - let active = c.getProp('active') || false; - if (active) { - activeIndex = index; - } - this.tabs.push({ title: title, name: tabName, active: active }); - let contentDom = new nodom.Element('div'); - contentDom.children = c.children; - contentDom.addDirective(new nodom.Directive('show', this.extraDataName + '.' + tabName, contentDom)); - bodyDom.add(contentDom); - if (itemDom) { - continue; - } - c.tagName = 'div'; - c.delProp(['title', 'active', 'name']); - c.addClass('nd-tab-item'); - let txt = new nodom.Element(); - txt.expressions = [new nodom.Expression('title')]; - c.children = [txt]; - if (this.allowClose) { - let b = new nodom.Element('b'); - b.addClass('nd-tab-close'); - b.addEvent(new nodom.NodomEvent('click', ':nopopo', (dom, model, module) => { - me.delTab(model.data.name, module); - })); - c.add(b); - } - c.addDirective(new nodom.Directive('repeat', this.extraDataName + '.datas', c)); - c.addDirective(new nodom.Directive('class', "{'nd-tab-item-active':'active'}", c)); - c.addEvent(new nodom.NodomEvent('click', (dom, model, module) => { - me.setActive(model.data.name, module); - })); - itemDom = c; - } - headDom.add(itemDom); - if (activeIndex === 0 && this.tabs.length > 0) { - this.tabs[0].active = true; - } - if (this.position === 'top' || this.position === 'left') { - rootDom.children = [headDom, bodyDom]; - } - else { - rootDom.children = [bodyDom, headDom]; - } - } - beforeRender(module, dom) { - super.beforeRender(module, dom); - let pmodel; - if (this.needPreRender) { - pmodel = module.modelFactory.get(this.modelId); - let data = { - datas: this.tabs - }; - for (let d of this.tabs) { - data[d.name] = d.active; - } - this.bodyKey = dom.children[1].key; - this.extraModelId = pmodel.set(this.extraDataName, data).id; - } - } - addTab(cfg) { - let module = nodom.ModuleFactory.get(this.moduleId); - if (!module) { - return; - } - let model = module.modelFactory.get(this.extraModelId); - let index = nodom.Util.isNumber(cfg.index) ? cfg.index : model.data.datas.length; - let tabName = cfg.name || ('Tab' + nodom.Util.genId()); - model.data.datas.splice(index, 0, { - title: cfg.title, - name: tabName, - active: false - }); - model.set(tabName, false); - let bodyDom = module.virtualDom.query(this.bodyKey); - let dom; - if (cfg.content) { - dom = nodom.Compiler.compile(cfg.content); - } - else if (cfg.module) { - dom = new nodom.Element('div'); - let mdlStr = cfg.module; - if (cfg.moduleName) { - mdlStr += '|' + cfg.moduleName; - } - dom.addDirective(new nodom.Directive('module', mdlStr, dom)); - if (cfg.data) { - dom.setProp('data', cfg.data); - } - } - dom.addDirective(new nodom.Directive('show', this.extraDataName + '.' + tabName, dom)); - bodyDom.children.splice(index, 0, dom); - if (cfg.active) { - this.setActive(tabName, module); - } - } - delTab(tabName, module) { - if (!module) { - module = nodom.ModuleFactory.get(this.moduleId); - } - let pmodel = module.modelFactory.get(this.extraModelId); - let datas = pmodel.data.datas; - let activeIndex; - if (datas.length === 1) { - return; - } - for (let i = 0; i < datas.length; i++) { - if (datas[i].name === tabName) { - if (datas[i].active) { - if (i < datas.length - 1) { - activeIndex = i; - } - else { - activeIndex = 0; - } - } - datas.splice(i, 1); - pmodel.del(tabName); - let bodyDom = module.virtualDom.query(this.bodyKey); - bodyDom.children.splice(i, 1); - break; - } - } - if (activeIndex !== undefined) { - this.setActive(datas[activeIndex].name, module); - } - } - setActive(tabName, module) { - if (!module) { - module = nodom.ModuleFactory.get(this.moduleId); - } - let pmodel = module.modelFactory.get(this.extraModelId); - let datas = pmodel.data.datas; - let activeData; - for (let o of datas) { - if (o.active) { - pmodel.data[o.name] = false; - o.active = false; - } - if (o.name === tabName) { - activeData = o; - } - } - activeData.active = true; - pmodel.data[tabName] = true; - } -} -nodom.PluginManager.add('UI-TAB', UITab); -class UITip extends nodom.Plugin { - constructor(params) { - super(params); - this.tagName = 'UI-TIP'; - this.needCheck = false; - this.containers = { - top: undefined, - right: undefined, - bottom: undefined, - left: undefined - }; - let rootDom = new nodom.Element(); - if (params) { - if (params instanceof HTMLElement) { - nodom.Compiler.handleAttributes(rootDom, params); - } - else if (typeof params === 'object') { - for (let o in params) { - this[o] = params[o]; - } - } - this.generate(rootDom); - } - rootDom.tagName = 'div'; - rootDom.plugin = this; - this.element = rootDom; - } - generate(rootDom) { - rootDom.tagName = 'div'; - this.extraDataName = '$ui_tip_manager'; - rootDom.setProp('name', this.extraDataName); - rootDom.addDirective(new nodom.Directive('model', this.extraDataName, rootDom)); - for (let loc of ['top', 'right', 'bottom', 'left']) { - let ct = new nodom.Element('div'); - ct.addClass('nd-tip nd-tip-' + loc); - ct.add(this.createTipDom(loc)); - rootDom.add(ct); - } - } - beforeRender(module, dom) { - super.beforeRender(module, dom); - if (this.needPreRender) { - let model = module.model; - if (!model.get(this.extraDataName)) { - let mdl = model.set(this.extraDataName, { - top: [], - left: [], - bottom: [], - right: [] - }); - this.modelId = mdl.id; - } - } - } - createTipDom(loc) { - let me = this; - let dom = new nodom.Element('div'); - dom.addDirective(new nodom.Directive('repeat', loc, dom)); - dom.setProp('class', new nodom.Expression("'nd-tip-item nd-box-' + theme"), true); - let close = new nodom.Element('b'); - close.addClass('nd-tip-close'); - close.addDirective(new nodom.Directive('show', 'allowClose', close)); - close.addEvent(new nodom.NodomEvent('click', (dom, model, module, e) => { - model.set('close', true); - me.check(true); - })); - let contentDom = new nodom.Element('div'); - contentDom.addClass('nd-tip-content'); - let icon = new nodom.Element('b'); - icon.setProp('class', new nodom.Expression("'nd-icon-' + icon"), true); - icon.addDirective(new nodom.Directive('show', 'icon', icon)); - let txt = new nodom.Element(); - txt.expressions = [new nodom.Expression('content')]; - contentDom.children = [txt]; - dom.children = [icon, contentDom, close]; - return dom; - } - check(force) { - let me = this; - if (force) { - this.needCheck = true; - } - if (!this.needCheck || !this.modelId) { - return; - } - let needCheck = false; - let model = nodom.ModuleFactory.getMain().modelFactory.get(this.modelId); - let ct = new Date().getTime(); - for (let loc of ['top', 'right', 'bottom', 'left']) { - let data = model.data[loc]; - for (let i = 0; i < data.length; i++) { - let d = data[i]; - if (d.close || !d.allowClose && d.start + d.time <= ct) { - data.splice(i--, 1); - } - else if (!d.allowClose && d.start + d.time > ct) { - needCheck = true; - } - } - } - this.needCheck = needCheck; - if (this.needCheck) { - setTimeout(() => { me.check(); }, 100); - } - } - show(config) { - if (!nodom.Util.isObject(config)) { - return; - } - let model = nodom.ModuleFactory.getMain().model.get(this.extraDataName); - if (!model) { - return; - } - let loc = config.loc || 'top'; - let allowClose = config.allowClose || false; - let datas = model.data[loc]; - let data = { - content: config.content || 'message', - time: config.time || 3000, - start: new Date().getTime(), - allowClose: allowClose, - icon: config.icon, - theme: config.theme || 'black' - }; - if (config.exclusive) { - for (let d of datas) { - datas.pop(); - } - datas.push(data); - } - else { - datas.push(data); - } - if (!allowClose) { - this.check(true); - } - } -} -nodom.PluginManager.add('UI-TIP', UITip); -var nodom; -(function (nodom) { - function tip(config) { - let module = nodom.ModuleFactory.getMain(); - if (!module) { - return null; - } - let manager = module.getPlugin('$ui_tip_manager'); - if (manager) { - manager.show(config); - } - } - nodom.tip = tip; -})(nodom || (nodom = {})); -class UIToolbar extends nodom.Plugin { - constructor(params) { - super(params); - this.tagName = 'UI-TOOLBAR'; - let rootDom = new nodom.Element(); - if (params) { - if (params instanceof HTMLElement) { - nodom.Compiler.handleAttributes(rootDom, params); - nodom.Compiler.handleChildren(rootDom, params); - } - else if (typeof params === 'object') { - for (let o in params) { - this[o] = params[o]; - } - } - } - rootDom.tagName = 'div'; - rootDom.addClass('nd-toolbar'); - rootDom.plugin = this; - this.element = rootDom; - } -} -nodom.PluginManager.add('UI-TOOLBAR', UIToolbar); -class UITree extends nodom.Plugin { - constructor(params) { - super(params); - this.tagName = 'UI-TREE'; - let rootDom = new nodom.Element(); - if (params) { - if (params instanceof HTMLElement) { - nodom.Compiler.handleAttributes(rootDom, params); - UITool.handleUIParam(rootDom, this, ['valuefield', 'displayfield', 'listfield', 'itemclick', 'checkname', 'maxlevel|number', 'icons|array|2'], ['valueField', 'displayField', 'listField', 'itemClick', 'checkName', 'maxLevel', 'iconArr'], ['', null, null, '', '', 3, []]); - } - else if (typeof params === 'object') { - for (let o in params) { - this[o] = params[o]; - } - } - this.generate(rootDom); - } - rootDom.tagName = 'div'; - rootDom.plugin = this; - this.element = rootDom; - } - generate(rootDom) { - const me = this; - rootDom.addClass('nd-tree'); - this.activeName = '$ui_tree_' + nodom.Util.genId(); - this.checkedChdNumName = '$ui_tree_' + nodom.Util.genId(); - let methodId = '$nodomGenMethod' + nodom.Util.genId(); - this.arrowClickId = methodId; - let closeOpenEvent = new nodom.NodomEvent('click', methodId + ':delg'); - let itemClickEvent; - if (this.itemClick !== '') { - itemClickEvent = new nodom.NodomEvent('click', this.itemClick + ':delg'); - } - let parentCt = rootDom; - let item; - for (let i = 0; i < this.maxLevel; i++) { - let itemCt = new nodom.Element(); - itemCt.tagName = 'div'; - itemCt.directives.push(new nodom.Directive('repeat', this.listField, itemCt)); - itemCt.addClass('nd-tree-nodect'); - item = new nodom.Element(); - item.addClass('nd-tree-node'); - item.tagName = 'DIV'; - if (itemClickEvent) { - item.addEvent(itemClickEvent); - } - let icon1 = new nodom.Element(); - icon1.tagName = 'SPAN'; - icon1.addClass('nd-tree-icon'); - icon1.addDirective(new nodom.Directive('class', "{'nd-tree-node-open':'" + this.activeName + "'," + - "'nd-icon-right':'" + this.listField + "&&" + this.listField + ".length>0'}", icon1)); - icon1.addEvent(closeOpenEvent); - itemCt.add(icon1); - if (this.iconArr.length > 0) { - let a = []; - a.push("'nd-icon-" + this.iconArr[0] + "':'" + this.listField + "&&" + this.listField + ".length>0'"); - if (this.iconArr.length > 1) { - a.push("'nd-icon-" + this.iconArr[1] + "':'!" + this.listField + "||" + this.listField + ".length===0'"); - } - let icon = new nodom.Element(); - icon.tagName = 'SPAN'; - icon.addClass('nd-tree-icon'); - let cls = '{' + a.join(',') + '}'; - icon.directives.push(new nodom.Directive('class', cls, icon)); - itemCt.add(icon); - } - if (this.checkName !== '') { - let cb = new nodom.Element('b'); - cb.addClass('nd-tree-uncheck'); - cb.addDirective(new nodom.Directive('class', "{'nd-tree-checked':'" + this.checkName + "'}", cb)); - itemCt.add(cb); - cb.addEvent(new nodom.NodomEvent('click', (dom, model, module, e) => { - me.handleCheck(model, module); - })); - } - itemCt.add(item); - let txt = new nodom.Element(); - txt.expressions = [new nodom.Expression(this.displayField)]; - item.add(txt); - let subCt = new nodom.Element(); - subCt.addClass('nd-tree-subct'); - subCt.tagName = 'DIV'; - subCt.addDirective(new nodom.Directive('class', "{'nd-tree-show':'" + this.activeName + "'}", subCt)); - itemCt.add(subCt); - parentCt.add(itemCt); - parentCt = subCt; - } - rootDom.plugin = this; - return rootDom; - } - beforeRender(module, uidom) { - const me = this; - super.beforeRender(module, uidom); - if (this.needPreRender) { - module.methodFactory.add(me.arrowClickId, (dom, model, module, e) => { - let pmodel = module.modelFactory.get(dom.modelId); - let rows = pmodel.data[me.listField]; - if (!rows || rows.length === 0) { - return; - } - model.set(me.activeName, !model.data[me.activeName]); - }); - } - } - handleCheck(model, module) { - let checked = !model.data[this.checkName]; - model.set(this.checkName, checked); - this.handleSubCheck(model, module, checked); - this.handleParentCheck(model, module, checked); - } - handleSubCheck(model, module, checked) { - let rows = model.data[this.listField]; - if (!rows) { - return; - } - if (checked) { - model.set(this.checkedChdNumName, rows.length); - } - else { - model.set(this.checkedChdNumName, 0); - } - for (let d of rows) { - let m = module.modelFactory.get(d.$modelId); - m.set(this.checkName, checked); - this.handleSubCheck(m, module, checked); - } - } - handleParentCheck(model, module, checked) { - let pmodel = model.parent; - if (!pmodel || pmodel === module.model) { - return; - } - pmodel = pmodel.parent; - if (!pmodel || pmodel === module.model) { - return; - } - let data = pmodel.data; - if (data[this.checkedChdNumName] === undefined) { - pmodel.set(this.checkedChdNumName, 0); - } - if (checked) { - data[this.checkedChdNumName]++; - } - else { - data[this.checkedChdNumName]--; - } - let chk = data[this.checkName]; - if (data[this.checkedChdNumName] === 0) { - pmodel.set(this.checkName, false); - } - else { - pmodel.set(this.checkName, true); - } - if (chk !== data[this.checkName]) { - this.handleParentCheck(pmodel, module, checked); - } - } - getValue() { - const me = this; - if (this.valueField === '') { - return; - } - let va = []; - let module = nodom.ModuleFactory.get(this.moduleId); - let model = module.modelFactory.get(this.modelId); - getChecked(model.data[this.listField]); - return va; - function getChecked(rows) { - if (Array.isArray(rows)) { - for (let d of rows) { - if (d[me.checkName] === true) { - va.push(d[me.valueField]); - } - getChecked(d[me.listField]); - } - } - } - } -} -nodom.PluginManager.add('UI-TREE', UITree); \ No newline at end of file diff --git a/test/pages/js/jpg1.base b/test/pages/js/jpg1.base deleted file mode 100644 index 889c2f64a41d3ea261c2082c18480d9d1b12b72b..0000000000000000000000000000000000000000 --- a/test/pages/js/jpg1.base +++ /dev/null @@ -1 +0,0 @@ -aGVsbG8= \ No newline at end of file diff --git a/test/pages/js/nodom.js b/test/pages/js/nodom.js deleted file mode 100644 index 313cff9dcf125d6e5a2168ce73661df8c35f0fb0..0000000000000000000000000000000000000000 --- a/test/pages/js/nodom.js +++ /dev/null @@ -1,4788 +0,0 @@ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var nodom; -(function (nodom) { - function newApp(config) { - return __awaiter(this, void 0, void 0, function* () { - if (window['NodomConfig']) { - config = nodom.Util.merge({}, window['NodomConfig'], config); - } - let lang = config && config.language; - if (!lang) { - lang = navigator.language ? navigator.language.substr(0, 2) : 'zh'; - } - nodom.TipMsg = eval('(nodom.TipMsg_' + lang + ')'); - if (!config || !config.module) { - throw new nodom.NodomError('config', nodom.TipMsg.TipWords['application']); - } - nodom.Application.setPath(config.path); - if (config.modules) { - yield nodom.ModuleFactory.addModules(config.modules); - } - nodom.Scheduler.addTask(nodom.MessageQueue.handleQueue, nodom.MessageQueue); - nodom.Scheduler.addTask(nodom.Renderer.render, nodom.Renderer); - nodom.Scheduler.start(config.scheduleCircle); - let module; - if (config.module.class) { - module = yield nodom.ModuleFactory.getInstance(config.module.class, config.module.name, config.module.data); - module.setSelector(config.module.el); - } - else { - module = new nodom.Module(config.module); - } - nodom.ModuleFactory.setMain(module); - yield module.active(); - if (config.routes) { - this.createRoute(config.routes); - } - return module; - }); - } - nodom.newApp = newApp; - function createRoute(config) { - if (nodom.Util.isArray(config)) { - for (let item of config) { - new nodom.Route(item); - } - } - else { - return new nodom.Route(config); - } - } - nodom.createRoute = createRoute; - function createDirective(name, priority, init, handler) { - return nodom.DirectiveManager.addType(name, priority, init, handler); - } - nodom.createDirective = createDirective; - function addModules(modules) { - nodom.ModuleFactory.addModules(modules); - } - nodom.addModules = addModules; - function request(config) { - return new Promise((resolve, reject) => { - if (typeof config === 'string') { - config = { - url: config - }; - } - config.params = config.params || {}; - if (config.rand) { - config.params.$rand = Math.random(); - } - let url = config.url; - const async = config.async === false ? false : true; - const req = new XMLHttpRequest(); - req.withCredentials = config.withCredentials; - const method = (config.method || 'GET').toUpperCase(); - req.timeout = async ? config.timeout : 0; - req.onload = () => { - if (req.status === 200) { - let r = req.responseText; - if (config.type === 'json') { - try { - r = JSON.parse(r); - } - catch (e) { - reject({ type: "jsonparse" }); - } - } - resolve(r); - } - else { - reject({ type: 'error', url: url }); - } - }; - req.ontimeout = () => reject({ type: 'timeout' }); - req.onerror = () => reject({ type: 'error', url: url }); - let data = null; - switch (method) { - case 'GET': - let pa; - if (nodom.Util.isObject(config.params)) { - let ar = []; - nodom.Util.getOwnProps(config.params).forEach(function (key) { - ar.push(key + '=' + config.params[key]); - }); - pa = ar.join('&'); - } - if (pa !== undefined) { - if (url.indexOf('?') !== -1) { - url += '&' + pa; - } - else { - url += '?' + pa; - } - } - break; - case 'POST': - if (config.params instanceof FormData) { - data = config.params; - } - else { - let fd = new FormData(); - for (let o in config.params) { - fd.append(o, config.params[o]); - } - data = fd; - } - break; - } - req.open(method, url, async, config.user, config.pwd); - if (config.header) { - nodom.Util.getOwnProps(config.header).forEach((item) => { - req.setRequestHeader(item, config.header[item]); - }); - } - req.send(data); - }).catch((re) => { - switch (re.type) { - case "error": - throw new nodom.NodomError("notexist1", nodom.TipMsg.TipWords['resource'], re.url); - case "timeout": - throw new nodom.NodomError("timeout"); - case "jsonparse": - throw new nodom.NodomError("jsonparse"); - } - }); - } - nodom.request = request; - function a(params) { - return newApp(params); - } - nodom.a = a; -})(nodom || (nodom = {})); -var $ = nodom; -var nodom; -(function (nodom) { - let Util = (() => { - class Util { - static genId() { - return this.generatedId++; - } - static clone(srcObj, expKey, extra) { - let me = this; - let map = new WeakMap(); - return clone(srcObj, expKey, extra); - function clone(src, expKey, extra) { - if (!src || typeof src !== 'object' || Util.isFunction(src)) { - return src; - } - let dst; - if (src.clone && Util.isFunction(src.clone)) { - return src.clone(extra); - } - else if (me.isObject(src)) { - dst = new Object(); - map.set(src, dst); - Object.getOwnPropertyNames(src).forEach((prop) => { - if (expKey) { - if (expKey.constructor === RegExp && expKey.test(prop) - || Util.isArray(expKey) && expKey.includes(prop)) { - return; - } - } - dst[prop] = getCloneObj(src[prop], expKey, extra); - }); - } - else if (me.isMap(src)) { - dst = new Map(); - src.forEach((value, key) => { - if (expKey) { - if (expKey.constructor === RegExp && expKey.test(key) - || expKey.includes(key)) { - return; - } - } - dst.set(key, getCloneObj(value, expKey, extra)); - }); - } - else if (me.isArray(src)) { - dst = new Array(); - src.forEach(function (item, i) { - dst[i] = getCloneObj(item, expKey, extra); - }); - } - return dst; - } - function getCloneObj(value, expKey, extra) { - if (typeof value === 'object' && !Util.isFunction(value)) { - let co = null; - if (!map.has(value)) { - co = clone(value, expKey, extra); - } - else { - co = map.get(value); - } - return co; - } - return value; - } - } - static merge(o1, o2, o3, o4, o5, o6) { - let me = this; - for (let i = 0; i < arguments.length; i++) { - if (!this.isObject(arguments[i])) { - throw new nodom.NodomError('invoke', 'Util.merge', i + '', 'object'); - } - } - let retObj = Object.assign.apply(null, arguments); - subObj(retObj); - return retObj; - function subObj(obj) { - for (let o in obj) { - if (me.isObject(obj[o]) || me.isArray(obj[o])) { - retObj[o] = me.clone(retObj[o]); - } - } - } - } - static assign(obj1, obj2) { - if (Object.assign) { - Object.assign(obj1, obj2); - } - else { - this.getOwnProps(obj2).forEach(function (p) { - obj1[p] = obj2[p]; - }); - } - return obj1; - } - static getOwnProps(obj) { - if (!obj) { - return []; - } - return Object.getOwnPropertyNames(obj); - } - static isFunction(foo) { - return foo !== undefined && foo !== null && foo.constructor === Function; - } - static isArray(obj) { - return Array.isArray(obj); - } - static isMap(obj) { - return obj !== null && obj !== undefined && obj.constructor === Map; - } - static isObject(obj) { - return obj !== null && obj !== undefined && obj.constructor === Object; - } - static isInt(v) { - return Number.isInteger(v); - } - static isNumber(v) { - return typeof v === 'number'; - } - static isBoolean(v) { - return typeof v === 'boolean'; - } - static isString(v) { - return typeof v === 'string'; - } - static isNumberString(v) { - return /^\d+\.?\d*$/.test(v); - } - static isEmpty(obj) { - if (obj === null || obj === undefined) - return true; - let tp = typeof obj; - if (this.isObject(obj)) { - let keys = Object.keys(obj); - if (keys !== undefined) { - return keys.length === 0; - } - } - else if (tp === 'string') { - return obj === ''; - } - return false; - } - static findObjByProps(obj, props, one) { - if (!this.isObject(obj)) { - throw new nodom.NodomError('invoke', 'this.findObjByProps', '0', 'Object'); - } - one = one || false; - let ps = this.getOwnProps(props); - let find = false; - if (one === false) { - find = true; - for (let i = 0; i < ps.length; i++) { - let p = ps[i]; - if (obj[p] !== props[p]) { - find = false; - break; - } - } - } - else { - for (let i = 0; i < ps.length; i++) { - let p = ps[i]; - if (obj[p] === props[p]) { - find = true; - break; - } - } - } - if (find) { - return obj; - } - for (let p in obj) { - let o = obj[p]; - if (o !== null) { - if (this.isObject(o)) { - let oprops = this.getOwnProps(o); - for (let i = 0; i < oprops.length; i++) { - let item = o[oprops[i]]; - if (item !== null && this.isObject(item)) { - let r = this.findObjByProps(item, props, one); - if (r !== null) { - return r; - } - } - } - } - else if (this.isArray(o)) { - for (let i = 0; i < o.length; i++) { - let item = o[i]; - if (item !== null && this.isObject(item)) { - let r = this.findObjByProps(item, props, one); - if (r !== null) { - return r; - } - } - } - } - } - } - return null; - } - static get(selector, findAll, pview) { - pview = pview || document; - if (findAll === true) { - return pview.querySelectorAll(selector); - } - return pview.querySelector(selector); - } - static isEl(el) { - return el instanceof HTMLElement || el instanceof SVGElement; - } - static isNode(node) { - return node !== undefined && node !== null && (node.nodeType === Node.TEXT_NODE || node.nodeType === Node.ELEMENT_NODE || node.nodeType === Node.DOCUMENT_FRAGMENT_NODE); - } - static newEl(tagName, config, text) { - if (!this.isString(tagName) || this.isEmpty(tagName)) { - throw new nodom.NodomError('invoke', 'this.newEl', '0', 'string'); - } - let el = document.createElement(tagName); - if (this.isObject(config)) { - this.attr(el, config); - } - else if (this.isString(text)) { - el.innerHTML = text; - } - return el; - } - static newSvgEl(tagName, config) { - let el = document.createElementNS("http://www.w3.org/2000/svg", tagName); - if (this.isObject(config)) { - this.attr(el, config); - } - return el; - } - static replaceNode(srcNode, nodes) { - if (!this.isNode(srcNode)) { - throw new nodom.NodomError('invoke', 'this.replaceNode', '0', 'Node'); - } - if (!this.isNode(nodes) && !this.isArray(nodes)) { - throw new nodom.NodomError('invoke1', 'this.replaceNode', '1', 'Node', 'Node Array'); - } - let pnode = srcNode.parentNode; - let bnode = srcNode.nextSibling; - if (pnode === null) { - return; - } - pnode.removeChild(srcNode); - const nodeArr = this.isArray(nodes) ? nodes : [nodes]; - nodeArr.forEach(function (node) { - if (bnode === undefined || bnode === null) { - pnode.appendChild(node); - } - else { - pnode.insertBefore(node, bnode); - } - }); - } - static empty(el) { - const me = this; - if (!me.isEl(el)) { - throw new nodom.NodomError('invoke', 'this.empty', '0', 'Element'); - } - let nodes = el.childNodes; - for (let i = nodes.length - 1; i >= 0; i--) { - el.removeChild(nodes[i]); - } - } - static remove(node) { - const me = this; - if (!me.isNode(node)) { - throw new nodom.NodomError('invoke', 'this.remove', '0', 'Node'); - } - if (node.parentNode !== null) { - node.parentNode.removeChild(node); - } - } - static attr(el, param, value) { - const me = this; - if (!me.isEl(el)) { - throw new nodom.NodomError('invoke', 'this.attr', '0', 'Element'); - } - if (this.isEmpty(param)) { - throw new nodom.NodomError('invoke', 'this.attr', '1', 'string', 'object'); - } - if (value === undefined || value === null) { - if (this.isObject(param)) { - this.getOwnProps(param).forEach(function (k) { - if (k === 'value') { - el[k] = param[k]; - } - else { - el.setAttribute(k, param[k]); - } - }); - } - else if (this.isString(param)) { - if (param === 'value') { - return param[value]; - } - return el.getAttribute(param); - } - } - else { - if (param === 'value') { - el[param] = value; - } - else { - el.setAttribute(param, value); - } - } - } - static formatDate(srcDate, format) { - let timeStamp; - if (this.isString(srcDate)) { - let reg = new RegExp(/^\d+$/); - if (reg.test(srcDate) === true) { - timeStamp = parseInt(srcDate); - } - } - else if (this.isNumber(srcDate)) { - timeStamp = srcDate; - } - else { - throw new nodom.NodomError('invoke', 'this.formatDate', '0', 'date string', 'date'); - } - let date = new Date(timeStamp); - if (isNaN(date.getDay())) { - return ''; - } - let o = { - "M+": date.getMonth() + 1, - "d+": date.getDate(), - "h+": date.getHours() % 12 === 0 ? 12 : date.getHours() % 12, - "H+": date.getHours(), - "m+": date.getMinutes(), - "s+": date.getSeconds(), - "q+": Math.floor((date.getMonth() + 3) / 3), - "S": date.getMilliseconds() - }; - let week = { - "0": "日", - "1": "一", - "2": "二", - "3": "三", - "4": "四", - "5": "五", - "6": "六" - }; - if (/(y+)/.test(format)) { - format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length)); - } - this.getOwnProps(o).forEach(function (k) { - if (new RegExp("(" + k + ")").test(format)) { - format = format.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); - } - }); - if (/(E+)/.test(format)) { - format = format.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "/u661f/u671f" : "/u5468") : "") + week[date.getDay() + ""]); - } - return format; - } - static compileStr(src, p1, p2, p3, p4, p5) { - let reg; - let args = arguments; - let index = 0; - for (;;) { - if (src.indexOf('\{' + index + '\}') !== -1) { - reg = new RegExp('\\{' + index + '\\}', 'g'); - src = src.replace(reg, args[index + 1]); - index++; - } - else { - break; - } - } - return src; - } - static apply(foo, obj, args) { - if (!foo) { - return; - } - return Reflect.apply(foo, obj || null, args); - } - static mergePath(paths) { - return paths.join('/').replace(/(\/{2,})|\\\//g, '\/'); - } - } - Util.generatedId = 1; - return Util; - })(); - nodom.Util = Util; -})(nodom || (nodom = {})); -var nodom; -(function (nodom) { - class Application { - static getPath(type) { - if (!this.path) { - return ''; - } - let appPath = this.path.app || ''; - if (type === 'app') { - return appPath; - } - else if (type === 'route') { - return this.path.route || ''; - } - else { - let p = this.path[type] || ''; - if (appPath !== '') { - if (p !== '') { - return appPath + '/' + p; - } - else { - return appPath; - } - } - return p; - } - } - static setPath(pathObj) { - this.path = pathObj; - } - } - nodom.Application = Application; -})(nodom || (nodom = {})); -var nodom; -(function (nodom) { - class Factory { - constructor(module) { - this.items = new Map(); - if (module !== undefined) { - this.moduleId = module.id; - } - } - add(name, item) { - this.items.set(name, item); - } - get(name) { - return this.items.get(name); - } - remove(name) { - this.items.delete(name); - } - has(name) { - return this.items.has(name); - } - } - nodom.Factory = Factory; -})(nodom || (nodom = {})); -var nodom; -(function (nodom) { - class Compiler { - static compile(elementStr) { - const div = nodom.Util.newEl('div'); - try { - div.innerHTML = elementStr; - } - catch (e) { } - let oe = new nodom.Element('div'); - this.handleChildren(oe, div); - return oe; - } - static compileDom(ele) { - let oe; - let isComment = false; - switch (ele.nodeType) { - case Node.ELEMENT_NODE: - let el = ele; - oe = this.handleDefineEl(el); - if (!oe) { - oe = this.handleEl(el); - } - break; - case Node.TEXT_NODE: - oe = new nodom.Element(); - let txt = ele.textContent; - let expA = this.compileExpression(txt); - if (typeof expA === 'string') { - oe.textContent = expA; - } - else { - oe.expressions = expA; - } - break; - case Node.COMMENT_NODE: - isComment = true; - break; - } - if (!isComment) { - return oe; - } - } - static handleEl(el) { - let oe = new nodom.Element(el.tagName); - this.handleAttributes(oe, el); - this.handleChildren(oe, el); - return oe; - } - static handleDefineEl(el) { - let de = nodom.PluginManager.get(el.tagName); - if (!de) { - return; - } - return Reflect.construct(de, [el]).element; - } - static handleAttributes(oe, el) { - let directives = []; - for (let i = 0; i < el.attributes.length; i++) { - let attr = el.attributes[i]; - if (attr.name.startsWith('x-')) { - directives.push(attr); - } - else if (attr.name.startsWith('e-')) { - let en = attr.name.substr(2); - oe.addEvent(new nodom.NodomEvent(en, attr.value.trim())); - } - else { - let isExpr = false; - let v = attr.value.trim(); - if (v !== '') { - let ra = this.compileExpression(v); - if (nodom.Util.isArray(ra)) { - oe.setProp(attr.name, ra, true); - isExpr = true; - } - } - if (!isExpr) { - oe.setProp(attr.name, v); - } - } - } - for (let attr of directives) { - new nodom.Directive(attr.name.substr(2), attr.value.trim(), oe, null, true); - } - if (directives.length > 1) { - oe.directives.sort((a, b) => { - return a.type.prio - b.type.prio; - }); - } - } - static handleChildren(oe, el) { - el.childNodes.forEach((nd) => { - let o = this.compileDom(nd); - if (o) { - if (o.tagName && oe.isSvgNode) { - o.isSvgNode = true; - } - oe.children.push(o); - } - }); - } - static compileExpression(exprStr) { - if (/\{\{.+?\}\}/.test(exprStr) === false) { - return exprStr; - } - let reg = /\{\{.+?\}\}/g; - let retA = new Array(); - let re; - let oIndex = 0; - while ((re = reg.exec(exprStr)) !== null) { - let ind = re.index; - if (ind > oIndex) { - let s = exprStr.substring(oIndex, ind); - retA.push(s); - } - let exp = new nodom.Expression(re[0].substring(2, re[0].length - 2)); - retA.push(exp); - oIndex = ind + re[0].length; - } - if (oIndex < exprStr.length - 1) { - retA.push(exprStr.substr(oIndex)); - } - return retA; - } - } - nodom.Compiler = Compiler; -})(nodom || (nodom = {})); -var nodom; -(function (nodom) { - class Directive { - constructor(type, value, dom, filters, notSort) { - this.id = nodom.Util.genId(); - this.type = nodom.DirectiveManager.getType(type); - if (nodom.Util.isString(value)) { - value = value.trim(); - } - this.value = value; - if (filters) { - this.filters = []; - if (typeof filters === 'string') { - let fa = filters.split('|'); - for (let f of fa) { - this.filters.push(new nodom.Filter(f)); - } - } - else if (nodom.Util.isArray(filters)) { - for (let f of filters) { - if (typeof f === 'string') { - this.filters.push(new nodom.Filter(f)); - } - else if (f instanceof nodom.Filter) { - this.filters.push(f); - } - } - } - } - if (type !== undefined && dom) { - nodom.DirectiveManager.init(this, dom); - dom.addDirective(this, !notSort); - } - } - exec(module, dom, parent) { - return __awaiter(this, void 0, void 0, function* () { - return nodom.DirectiveManager.exec(this, dom, module, parent); - }); - } - clone(dst) { - let dir = new Directive(this.type.name, this.value); - if (this.filters) { - dir.filters = []; - for (let f of this.filters) { - dir.filters.push(f.clone()); - } - } - if (this.params) { - dir.params = nodom.Util.clone(this.params); - } - if (this.extra) { - dir.extra = nodom.Util.clone(this.extra); - } - nodom.DirectiveManager.init(dir, dst); - return dir; - } - } - nodom.Directive = Directive; -})(nodom || (nodom = {})); -var nodom; -(function (nodom) { - class DirectiveType { - constructor(name, prio, init, handle) { - this.name = name; - this.prio = prio || 10; - this.init = init; - this.handle = handle; - } - } - nodom.DirectiveType = DirectiveType; -})(nodom || (nodom = {})); -var nodom; -(function (nodom) { - let DirectiveManager = (() => { - class DirectiveManager { - static addType(name, prio, init, handle) { - this.directiveTypes.set(name, new nodom.DirectiveType(name, prio, init, handle)); - } - static removeType(name) { - this.directiveTypes.delete(name); - } - static getType(name) { - return this.directiveTypes.get(name); - } - static hasType(name) { - return this.directiveTypes.has(name); - } - static init(directive, dom) { - let dt = directive.type; - if (dt) { - return dt.init(directive, dom); - } - } - static exec(directive, dom, module, parent) { - return nodom.Util.apply(directive.type.handle, null, [directive, dom, module, parent]); - } - } - DirectiveManager.directiveTypes = new Map(); - return DirectiveManager; - })(); - nodom.DirectiveManager = DirectiveManager; -})(nodom || (nodom = {})); -var nodom; -(function (nodom) { - class ChangedDom { - constructor(node, type, parent, index) { - this.node = node; - this.type = type; - this.parent = parent; - this.index = index; - } - } - nodom.ChangedDom = ChangedDom; - class Element { - constructor(tag) { - this.directives = []; - this.assets = new Map(); - this.props = {}; - this.exprProps = {}; - this.events = new Map(); - this.expressions = []; - this.children = []; - this.dontRender = false; - this.dontRenderSelf = false; - this.tagName = tag; - if (tag && tag.toLowerCase() === 'svg') { - this.isSvgNode = true; - } - this.key = nodom.Util.genId() + ''; - } - render(module, parent) { - if (this.dontRender) { - this.doDontRender(); - return; - } - if (parent) { - if (!this.modelId) { - this.modelId = parent.modelId; - } - this.parent = parent; - this.parentKey = parent.key; - } - if (this.plugin) { - this.plugin.beforeRender(module, this); - } - if (this.tagName !== undefined) { - this.handleProps(module); - this.handleDirectives(module); - } - else { - this.handleTextContent(module); - } - if (this.dontRender) { - this.doDontRender(); - return; - } - if (!this.hasDirective('module')) { - for (let i = 0; i < this.children.length; i++) { - let item = this.children[i]; - item.render(module, this); - if (item.dontRender) { - item.doDontRender(); - this.children.splice(i--, 1); - } - } - } - if (this.plugin) { - this.plugin.afterRender(module, this); - } - delete this.parent; - } - renderToHtml(module, params) { - let el; - let el1; - let type = params.type; - let parent = params.parent; - this.dontRender = false; - if (type === 'fresh' || type === 'add' || type === 'text') { - if (parent) { - el = module.getNode(parent.key); - } - else { - el = module.getContainer(); - } - } - else if (this.tagName !== undefined) { - el = module.getNode(this.key); - this.handleAssets(el); - } - if (!el) { - return; - } - switch (type) { - case 'fresh': - if (this.tagName) { - el1 = newEl(this, null, el); - genSub(el1, this); - } - else { - el1 = newText(this.textContent, this); - } - el.appendChild(el1); - break; - case 'text': - if (!parent || !parent.children) { - break; - } - let ind = parent.children.indexOf(this); - if (ind !== -1) { - if (this.type === 'html') { - let div = document.querySelector("[key='" + this.key + "']"); - if (div !== null) { - div.innerHTML = ''; - div.appendChild(this.textContent); - } - else { - let div = newText(this.textContent); - nodom.Util.replaceNode(el.childNodes[ind], div); - } - } - else { - el.childNodes[ind].textContent = this.textContent; - } - } - break; - case 'upd': - if (params.removeProps) { - params.removeProps.forEach((p) => { - el.removeAttribute(p); - }); - } - if (params.changeProps) { - params.changeProps.forEach((p) => { - el.setAttribute(p['k'], p['v']); - }); - } - break; - case 'rep': - el1 = newEl(this, parent); - nodom.Util.replaceNode(el, el1); - break; - case 'add': - if (this.tagName) { - el1 = newEl(this, parent, el); - genSub(el1, this); - } - else { - el1 = newText(this.textContent); - } - if (params.index === el.childNodes.length) { - el.appendChild(el1); - } - else { - el.insertBefore(el1, el.childNodes[params.index]); - } - } - function newEl(vdom, parent, parentEl) { - let el; - if (vdom.isSvgNode) { - el = nodom.Util.newSvgEl(vdom.tagName); - } - else { - el = nodom.Util.newEl(vdom.tagName); - } - nodom.Util.getOwnProps(vdom.props).forEach((k) => { - el.setAttribute(k, vdom.props[k]); - }); - el.setAttribute('key', vdom.key); - vdom.handleEvents(module, el, parent, parentEl); - vdom.handleAssets(el); - return el; - } - function newText(text, dom) { - if (text === undefined) { - text = ''; - dom = null; - } - if (dom && 'html' === dom.type) { - let div = nodom.Util.newEl('div'); - div.setAttribute('key', dom.key); - div.appendChild(text); - return div; - } - else { - return document.createTextNode(text); - } - } - function genSub(pEl, vNode) { - if (vNode.children && vNode.children.length > 0) { - vNode.children.forEach((item) => { - let el1; - if (item.tagName) { - el1 = newEl(item, vNode, pEl); - genSub(el1, item); - } - else { - el1 = newText(item.textContent, item); - } - pEl.appendChild(el1); - }); - } - } - } - clone(changeKey) { - let dst = new Element(); - let notCopyProps = ['parent', 'directives', 'children']; - nodom.Util.getOwnProps(this).forEach((p) => { - if (notCopyProps.includes(p)) { - return; - } - if (typeof this[p] === 'object') { - dst[p] = nodom.Util.clone(this[p]); - } - else { - dst[p] = this[p]; - } - }); - if (changeKey) { - dst.key = nodom.Util.genId() + ''; - } - if (this.plugin) { - if (changeKey) { - dst.plugin = this.plugin.clone(dst); - } - else { - dst.plugin = this.plugin; - } - } - for (let d of this.directives) { - if (changeKey) { - d = d.clone(dst); - } - dst.directives.push(d); - } - for (let c of this.children) { - dst.add(c.clone(changeKey)); - } - return dst; - } - handleDirectives(module) { - if (this.dontRender) { - return; - } - for (let d of this.directives.values()) { - if (this.dontRender) { - return; - } - d.exec(module, this, this.parent); - } - } - handleExpression(exprArr, module) { - if (this.dontRender) { - return; - } - let model = module.getModel(this.modelId); - let value = ''; - exprArr.forEach((v) => { - if (v instanceof nodom.Expression) { - let v1 = v.val(model); - value += v1 !== undefined ? v1 : ''; - } - else { - value += v; - } - }); - return value; - } - handleProps(module) { - if (this.dontRender) { - return; - } - for (let k of nodom.Util.getOwnProps(this.exprProps)) { - if (this.dontRender) { - return; - } - if (nodom.Util.isArray(this.exprProps[k])) { - let pv = this.handleExpression(this.exprProps[k], module); - if (k === 'class') { - this.addClass(pv); - } - else { - this.props[k] = pv; - } - } - else if (this.exprProps[k] instanceof nodom.Expression) { - this.props[k] = this.exprProps[k].val(module.getModel(this.modelId)); - } - } - } - handleAssets(el) { - if (!this.tagName && !el) { - return; - } - for (let key of this.assets) { - el[key[0]] = key[1]; - } - } - handleTextContent(module) { - if (this.dontRender) { - return; - } - if (this.expressions !== undefined && this.expressions.length > 0) { - let v = this.handleExpression(this.expressions, module) || ''; - this.textContent = this.handleExpression(this.expressions, module); - } - } - handleEvents(module, el, parent, parentEl) { - if (this.events.size === 0) { - return; - } - for (let evt of this.events.values()) { - if (nodom.Util.isArray(evt)) { - for (let evo of evt) { - evo.bind(module, this, el, parent, parentEl); - } - } - else { - evt.bind(module, this, el, parent, parentEl); - } - } - } - removeDirectives(directives) { - for (let i = 0; i < this.directives.length; i++) { - if (directives.length === 0) { - break; - } - for (let j = 0; j < directives.length; j++) { - if (directives[j].includes(this.directives[i].type.name)) { - this.directives.splice(i--, 1); - directives.splice(j--, 1); - break; - } - } - } - } - addDirective(directive, sort) { - let finded = false; - for (let i = 0; i < this.directives.length; i++) { - if (this.directives[i].type === directive.type) { - this.directives[i] = directive; - finded = true; - break; - } - } - if (!finded) { - this.directives.push(directive); - } - if (sort) { - if (this.directives.length > 1) { - this.directives.sort((a, b) => { - return a.type.prio - b.type.prio; - }); - } - } - } - hasDirective(directiveType) { - return this.directives.findIndex(item => item.type.name === directiveType) !== -1; - } - getDirective(directiveType) { - return this.directives.find(item => item.type.name === directiveType); - } - add(dom) { - dom.parentKey = this.key; - this.children.push(dom); - } - remove(module, delHtml) { - let parent = this.getParent(module); - if (parent) { - parent.removeChild(this); - } - if (delHtml && module) { - let el = module.getNode(this.key); - if (el !== null) { - nodom.Util.remove(el); - } - } - } - removeFromHtml(module) { - let el = module.getNode(this.key); - if (el !== null) { - nodom.Util.remove(el); - } - } - removeChild(dom) { - let ind; - if (nodom.Util.isArray(this.children) && (ind = this.children.indexOf(dom)) !== -1) { - this.children.splice(ind, 1); - } - } - getParent(module) { - if (!module) { - throw new nodom.NodomError('invoke', 'Element.getParent', '0', 'Module'); - } - if (this.parent) { - return this.parent; - } - if (this.parentKey) { - return module.getElement(this.parentKey); - } - } - replace(dst) { - if (!dst.parent) { - return false; - } - let ind = dst.parent.children.indexOf(dst); - if (ind === -1) { - return false; - } - dst.parent.children.splice(ind, 1, this); - return true; - } - contains(dom) { - for (; dom !== undefined && dom !== this; dom = dom.parent) - ; - return dom !== undefined; - } - hasClass(cls) { - let clazz = this.props['class']; - if (!clazz) { - return false; - } - else { - return clazz.trim().split(/\s+/).includes(cls); - } - } - addClass(cls) { - let clazz = this.props['class']; - if (!clazz) { - this.props['class'] = cls; - } - else { - let sa = clazz.trim().split(/\s+/); - if (!sa.includes(cls)) { - sa.push(cls); - clazz = sa.join(' '); - this.props['class'] = clazz; - } - } - } - removeClass(cls) { - let clazz = this.props['class']; - if (!clazz) { - return; - } - else { - let sa = clazz.trim().split(/\s+/); - let index; - if ((index = sa.indexOf(cls)) !== -1) { - sa.splice(index, 1); - clazz = sa.join(' '); - } - } - this.props['class'] = clazz; - } - hasProp(propName) { - return this.props.hasOwnProperty(propName) || this.exprProps.hasOwnProperty(propName); - } - getProp(propName) { - let prop = this.props[propName]; - if (prop === undefined) { - prop = this.exprProps[propName]; - } - return prop; - } - setProp(propName, v, isExpr) { - if (isExpr) { - this.exprProps[propName] = v; - } - else { - this.props[propName] = v; - } - } - delProp(props) { - if (nodom.Util.isArray(props)) { - for (let p of props) { - delete this.exprProps[p]; - } - for (let p of props) { - delete this.props[p]; - } - } - else { - delete this.exprProps[props]; - delete this.props[props]; - } - } - query(key) { - if (this.key === key) { - return this; - } - for (let i = 0; i < this.children.length; i++) { - let dom = this.children[i].query(key); - if (dom) { - return dom; - } - } - } - compare(dst, retArr, parentNode) { - if (!dst) { - return; - } - let re = new ChangedDom(); - let change = false; - let findedMap = new Map(); - if (this.tagName === undefined) { - if (dst.tagName === undefined) { - if (this.textContent !== dst.textContent) { - re.type = 'text'; - change = true; - } - } - else { - re.type = 'rep'; - change = true; - } - } - else { - if (this.tagName !== dst.tagName) { - re.type = 'rep'; - change = true; - } - else { - re.changeProps = []; - re.removeProps = []; - nodom.Util.getOwnProps(dst.props).forEach((k) => { - if (!this.hasProp(k)) { - re.removeProps.push(k); - } - }); - nodom.Util.getOwnProps(this.props).forEach((k) => { - let v1 = dst.props[k]; - if (this.props[k] !== v1) { - re.changeProps.push({ k: k, v: this.props[k] }); - } - }); - if (re.changeProps.length > 0 || re.removeProps.length > 0) { - change = true; - re.type = 'upd'; - } - } - } - if (change) { - re.node = this; - if (parentNode) { - re.parent = parentNode; - } - retArr.push(re); - } - if (!this.children || this.children.length === 0) { - if (dst.children && dst.children.length > 0) { - dst.children.forEach((item) => { - retArr.push(new ChangedDom(item, 'del')); - }); - } - } - else { - if (!dst.children || dst.children.length === 0) { - this.children.forEach((item) => { - retArr.push(new ChangedDom(item, 'add', this)); - }); - } - else { - this.children.forEach((dom1, ind) => { - let dom2 = dst.children[ind]; - if (!dom2 || dom1.key !== dom2.key) { - dom2 = undefined; - for (let i = 0; i < dst.children.length; i++) { - if (dom1.key === dst.children[i].key) { - dom2 = dst.children[i]; - break; - } - } - } - if (dom2 !== undefined) { - dom1.compare(dom2, retArr, this); - findedMap.set(dom2.key, true); - } - else { - retArr.push(new ChangedDom(dom1, 'add', this, ind)); - } - }); - if (dst.children && dst.children.length > 0) { - dst.children.forEach((item) => { - if (!findedMap.has(item.key)) { - retArr.push(new ChangedDom(item, 'del', dst)); - } - }); - } - } - } - } - addEvent(event) { - if (this.events.has(event.name)) { - let ev = this.events.get(event.name); - let evs; - if (nodom.Util.isArray(ev)) { - evs = ev; - } - else { - evs = [ev]; - } - evs.push(event); - this.events.set(event.name, evs); - } - else { - this.events.set(event.name, event); - } - } - doDontRender() { - if (this.hasDirective('module')) { - let d = this.getDirective('module'); - if (d.extra && d.extra.moduleId) { - let mdl = nodom.ModuleFactory.get(d.extra.moduleId); - if (mdl) { - mdl.unactive(); - } - } - } - for (let c of this.children) { - c.doDontRender(); - } - } - } - nodom.Element = Element; -})(nodom || (nodom = {})); -var nodom; -(function (nodom) { - let Expression = (() => { - class Expression { - constructor(exprStr) { - this.replaceMap = new Map(); - this.fields = []; - this.id = nodom.Util.genId(); - let execStr; - if (exprStr) { - execStr = this.compile(exprStr); - } - if (execStr) { - let v = this.fields.length > 0 ? ',' + this.fields.join(',') : ''; - execStr = 'function($module' + v + '){return ' + execStr + '}'; - this.execFunc = eval('(' + execStr + ')'); - } - } - clone() { - return this; - } - compile(exprStr) { - let stringReg = [/\".*?\"/, /'.*?'/, /`.*?`/]; - let quotReg = [/\\"/g, /\\'/g, /\\`/g]; - let quotStr = ['$$$$NODOM_QUOT1', '$$$$NODOM_QUOT2', '$$$$NODOM_QUOT3']; - let srcStr = exprStr; - let replaceIndex = 0; - for (let i = 0; i < 3; i++) { - srcStr = srcStr.replace(quotReg[i], quotStr[i]); - } - for (;;) { - let r; - for (let reg of stringReg) { - let r1 = reg.exec(srcStr); - if (!r1) { - continue; - } - if (!r || r.index > r1.index) { - r = r1; - } - } - if (!r) { - break; - } - let sTmp = Expression.REP_STR + replaceIndex++; - this.replaceMap.set(sTmp, r[0]); - srcStr = srcStr.substr(0, r.index) + sTmp + srcStr.substr(r.index + r[0].length); - } - srcStr = srcStr.replace(/\s+/g, ''); - let arrOperator = srcStr.split(/[\(\)\!\|\*\/\+\-><=&%]/); - let arrOperand = []; - let index = 0; - for (let sp of arrOperator) { - index += sp.length; - let ch = srcStr.charAt(index++); - if (ch !== '') { - arrOperand.push(ch); - } - } - return this.genExecStr(arrOperator, arrOperand); - } - genExecStr(arrOperator, arrOperand) { - let retStr = ''; - for (; arrOperator.length > 1;) { - let opr = arrOperator.pop(); - let opd = arrOperand.pop(); - let r; - let handled = false; - if (opd === '(') { - r = this.judgeAndHandleFunc(arrOperator); - if (r !== undefined) { - if (r.startsWith('$module')) { - opd = ''; - } - if (opr !== '' && !this.addField(opr)) { - opr = this.recoveryString(opr); - } - retStr = r + opd + opr + retStr; - if (arrOperand.length > 0) { - retStr = arrOperand.pop() + retStr; - } - handled = true; - } - } - else if (opd === '|') { - r = this.judgeAndHandleFilter(arrOperator, arrOperand, opr); - if (r !== undefined) { - retStr = (arrOperand.length > 0 ? arrOperand.pop() : '') + r + retStr; - handled = true; - } - } - if (!handled) { - if (!this.addField(opr)) { - opr = this.recoveryString(opr); - } - retStr = opd + opr + retStr; - } - } - if (arrOperator.length > 0) { - let opr = arrOperator.pop(); - if (opr !== '') { - if (!this.addField(opr)) { - opr = this.recoveryString(opr); - } - retStr = opr + retStr; - } - } - return retStr; - } - recoveryString(str) { - if (str.startsWith(Expression.REP_STR)) { - if (this.replaceMap.has(str)) { - str = this.replaceMap.get(str); - str = str.replace(/\$\$NODOM_QUOT1/g, '\\"'); - str = str.replace(/\$\$NODOM_QUOT2/g, "\\'"); - str = str.replace(/\$\$NODOM_QUOT3/g, '\\`'); - } - } - return str; - } - judgeAndHandleFunc(arrOperator) { - let sp = arrOperator[arrOperator.length - 1]; - if (sp && sp !== '') { - arrOperator.pop(); - if (sp.startsWith('$')) { - return '$module.methodFactory.get("' + sp.substr(1) + '").call($module,'; - } - else { - return sp; - } - } - } - judgeAndHandleFilter(arrOperator, arrOperand, srcOp) { - if (srcOp.startsWith(Expression.REP_STR) || nodom.Util.isNumberString(srcOp)) { - return; - } - let sa = nodom.FilterManager.explain(srcOp); - if (sa.length > 1 || nodom.FilterManager.hasType(sa[0])) { - let ftype = sa[0]; - sa.shift(); - sa.forEach((v, i) => { - v = this.recoveryString(v); - if (!nodom.Util.isNumberString(v)) { - sa[i] = '"' + v.replace(/"/g, '\\"') + '"'; - } - }); - let paramStr = sa.length > 0 ? ',' + sa.join(',') : ''; - let filterValue = ''; - let opr = arrOperator[arrOperator.length - 1]; - if (opr !== '') { - if (!this.addField(opr)) { - opr = this.recoveryString(opr); - } - filterValue = opr; - arrOperator.pop(); - } - else if (arrOperand.length > 2 && arrOperand[arrOperand.length - 1] === ')') { - let quotNum = 1; - let a1 = [arrOperator.pop()]; - let a2 = [arrOperand.pop()]; - for (let i = arrOperand.length - 1; i >= 0; i--) { - if (arrOperand[i] === '(') { - quotNum--; - } - else if (arrOperand[i] === ')') { - quotNum++; - } - a1.unshift(arrOperator.pop()); - a2.unshift(arrOperand.pop()); - if (quotNum === 0) { - a1.unshift(arrOperator.pop()); - break; - } - } - filterValue = this.genExecStr(a1, a2); - } - return 'nodom.FilterManager.exec($module,"' + ftype + '",' + filterValue + paramStr + ')'; - } - } - val(model) { - if (!model || !model.data) { - return ''; - } - let module = nodom.ModuleFactory.get(model.moduleId); - let fieldObj = model.data; - let valueArr = []; - this.fields.forEach((field) => { - valueArr.push(getFieldValue(module, fieldObj, field)); - }); - valueArr.unshift(module); - let v; - try { - v = this.execFunc.apply(null, valueArr); - } - catch (e) { - } - return v === undefined || v === null ? '' : v; - function getFieldValue(module, dataObj, field) { - if (dataObj.hasOwnProperty(field)) { - return dataObj[field]; - } - if (field.startsWith('$$')) { - return module.model.query(field.substr(2)); - } - } - } - addField(field) { - const jsKeyWords = ['true', 'false', 'undefined', 'null', 'typeof', - 'Object', 'Function', 'Array', 'Number', 'Date', - 'instanceof', 'NaN']; - if (field === '' || jsKeyWords.includes(field) || field.startsWith(Expression.REP_STR) || nodom.Util.isNumberString(field)) { - return false; - } - let ind; - if ((ind = field.indexOf('.')) !== -1) { - field = field.substr(0, ind); - } - if (!this.fields.includes(field)) { - this.fields.push(field); - } - return true; - } - } - Expression.REP_STR = '$$NODOM_TMPSTR'; - return Expression; - })(); - nodom.Expression = Expression; -})(nodom || (nodom = {})); -var nodom; -(function (nodom) { - class Filter { - constructor(src) { - if (src) { - let arr = nodom.Util.isString(src) ? nodom.FilterManager.explain(src) : src; - if (arr) { - this.type = arr[0]; - this.params = arr.slice(1); - } - } - } - exec(value, module) { - let args = [module, this.type, value].concat(this.params); - return nodom.Util.apply(nodom.FilterManager.exec, module, args); - } - clone() { - let filter = new Filter(); - filter.type = this.type; - if (this.params) { - filter.params = nodom.Util.clone(this.params); - } - return filter; - } - } - nodom.Filter = Filter; -})(nodom || (nodom = {})); -var nodom; -(function (nodom) { - let FilterManager = (() => { - class FilterManager { - static addType(name, handler) { - if (!/^[a-zA-Z]+$/.test(name)) { - throw new nodom.NodomError('namedinvalid', nodom.TipMsg.TipWords['filterType'], name); - } - if (this.filterTypes.has(name)) { - throw new nodom.NodomError('exist1', nodom.TipMsg.TipWords['filterType'], name); - } - if (!nodom.Util.isFunction(handler)) { - throw new nodom.NodomError('invoke', 'FilterManager.addType', '1', 'Function'); - } - this.filterTypes.set(name, handler); - } - static removeType(name) { - if (!this.filterTypes.has(name)) { - throw new nodom.NodomError('notexist1', nodom.TipMsg.TipWords['filterType'], name); - } - this.filterTypes.delete(name); - } - static hasType(name) { - return this.filterTypes.has(name); - } - static exec(module, type) { - let params = new Array(); - for (let i = 2; i < arguments.length; i++) { - params.push(arguments[i]); - } - if (!FilterManager.filterTypes.has(type)) { - throw new nodom.NodomError('notexist1', nodom.TipMsg.TipWords['filterType'], type); - } - return nodom.Util.apply(FilterManager.filterTypes.get(type), module, params); - } - static explain(src) { - let startStr; - let startObj = false; - let strings = "\"'`"; - let splitCh = ':'; - let retArr = new Array(); - let tmp = ''; - for (let i = 0; i < src.length; i++) { - let ch = src[i]; - if (strings.indexOf(ch) !== -1) { - if (ch === startStr) { - startStr = undefined; - } - else { - startStr = ch; - } - } - else if (startStr === undefined) { - if (ch === '}' && startObj) { - startObj = false; - } - else if (ch === '{') { - startObj = true; - } - } - if (ch === splitCh && startStr === undefined && !startObj && tmp !== '') { - retArr.push(handleObj(tmp)); - tmp = ''; - continue; - } - tmp += ch; - } - if (tmp !== '') { - retArr.push(handleObj(tmp)); - } - return retArr; - function handleObj(s) { - s = s.trim(); - if (s.charAt(0) === '{') { - s = eval('(' + s + ')'); - } - return s; - } - } - } - FilterManager.filterTypes = new Map(); - return FilterManager; - })(); - nodom.FilterManager = FilterManager; -})(nodom || (nodom = {})); -var nodom; -(function (nodom) { - let ResourceManager = (() => { - class ResourceManager { - static getResources(reqs) { - return __awaiter(this, void 0, void 0, function* () { - let me = this; - this.preHandle(reqs); - if (reqs.length === 0) { - return []; - } - let taskId = nodom.Util.genId(); - let resArr = []; - for (let item of reqs) { - resArr.push(item.url); - } - this.loadingTasks.set(taskId, resArr); - return new Promise((res, rej) => __awaiter(this, void 0, void 0, function* () { - for (let item of reqs) { - let url = item.url; - if (this.resources.has(url)) { - let r = me.awake(taskId); - if (r) { - res(r); - } - } - else if (this.waitList.has(url)) { - this.waitList.get(url).push(taskId); - } - else { - this.waitList.set(url, [taskId]); - let content = yield nodom.request({ url: url }); - let rObj = { type: item.type, content: content }; - this.handleOne(url, rObj); - this.resources.set(url, rObj); - let arr = this.waitList.get(url); - this.waitList.delete(url); - for (let tid of arr) { - let r = me.awake(tid); - if (r) { - res(r); - } - } - } - } - })); - }); - } - static awake(taskId) { - if (!this.loadingTasks.has(taskId)) { - return; - } - let resArr = this.loadingTasks.get(taskId); - let finish = true; - let contents = []; - for (let url of resArr) { - if (!this.resources.has(url)) { - finish = false; - break; - } - contents.push(this.resources.get(url)); - } - if (finish) { - this.loadingTasks.delete(taskId); - return contents; - } - } - static getType(url) { - let ind = -1; - let type; - if ((ind = url.lastIndexOf('.')) !== -1) { - type = url.substr(ind + 1); - if (type === 'htm' || type === 'html') { - type = 'template'; - } - } - return type || 'text'; - } - static handleOne(url, rObj) { - switch (rObj.type) { - case 'js': - let head = document.querySelector('head'); - let script = nodom.Util.newEl('script'); - script.innerHTML = rObj.content; - head.appendChild(script); - head.removeChild(script); - delete rObj.content; - break; - case 'template': - rObj.content = nodom.Compiler.compile(rObj.content); - break; - case 'nd': - rObj.content = nodom.Serializer.deserialize(rObj.content); - break; - case 'data': - try { - rObj.content = JSON.parse(rObj.content); - } - catch (e) { - console.log(e); - } - } - this.resources.set(url, rObj); - } - static preHandle(reqs) { - let head = document.querySelector('head'); - for (let i = 0; i < reqs.length; i++) { - if (typeof reqs[i] === 'string') { - reqs[i] = { - url: reqs[i] - }; - } - reqs[i].type = reqs[i].type || this.getType(reqs[i].url); - if (reqs[i].type === 'css') { - let css = nodom.Util.newEl('link'); - css.type = 'text/css'; - css.rel = 'stylesheet'; - css.href = reqs[i].url; - head.appendChild(css); - reqs.splice(i--, 1); - } - } - return reqs; - } - } - ResourceManager.resources = new Map(); - ResourceManager.loadingTasks = new Map(); - ResourceManager.waitList = new Map(); - return ResourceManager; - })(); - nodom.ResourceManager = ResourceManager; -})(nodom || (nodom = {})); -var nodom; -(function (nodom) { - class Message { - constructor(fromModule, toModule, content, parentId) { - this.fromModule = fromModule; - this.toModule = toModule; - this.content = content; - this.parentId = parentId; - } - } - nodom.Message = Message; - let MessageQueue = (() => { - class MessageQueue { - static add(from, to, data, parentId) { - if (parentId) { - this.noOwnerMessages.push(new Message(from, to, data, parentId)); - } - else { - this.messages.push(new Message(from, to, data)); - } - } - static move(moduleName, moduleId, parentId) { - let index = this.noOwnerMessages.findIndex(item => item.parentId === parentId && moduleName === item.toModule); - if (index === -1) { - return; - } - let msg = this.noOwnerMessages[index]; - this.noOwnerMessages.splice(index, 1); - msg.toModule = moduleId; - delete msg.parentId; - this.messages.push(msg); - } - static handleQueue() { - for (let i = 0; i < this.messages.length; i++) { - let msg = this.messages[i]; - let module = nodom.ModuleFactory.get(msg.toModule); - if (module && module.state >= 2) { - module.receive(msg.fromModule, msg.content); - MessageQueue.messages.splice(i--, 1); - } - } - } - } - MessageQueue.messages = []; - MessageQueue.noOwnerMessages = []; - return MessageQueue; - })(); - nodom.MessageQueue = MessageQueue; -})(nodom || (nodom = {})); -var nodom; -(function (nodom) { - class MethodFactory extends nodom.Factory { - invoke(name, params) { - const foo = this.get(name); - if (!nodom.Util.isFunction(foo)) { - throw new nodom.NodomError(nodom.TipMsg.ErrorMsgs['notexist1'], nodom.TipMsg.TipWords['method'], name); - } - return nodom.Util.apply(foo, this.module.model, params); - } - } - nodom.MethodFactory = MethodFactory; -})(nodom || (nodom = {})); -var nodom; -(function (nodom) { - class Model { - constructor(data, module, parent, key) { - this.fields = {}; - this.fields = {}; - this.id = nodom.Util.genId(); - if (module) { - this.moduleId = module.id; - module.setModel(this.id, this); - } - if (!data || !nodom.Util.isObject(data) && !nodom.Util.isArray(data)) { - data = {}; - } - data['$modelId'] = this.id; - this.data = data; - this.addSetterGetter(data); - if (parent) { - this.parent = parent; - if (nodom.Util.isArray(parent.data)) { - if (!parent.children) { - parent.children = []; - } - parent.children.push(this); - } - else if (key) { - if (!parent.children) { - parent.children = {}; - } - parent.children[key] = this; - } - } - } - set(key, value) { - if (value === undefined) { - if (typeof key === 'object') { - this.addSetterGetter(key); - for (let o in key) { - this.data[o] = key[o]; - } - return; - } - } - let fn; - let index = key.lastIndexOf('.'); - let model; - if (index !== -1) { - fn = key.substr(index + 1); - key = key.substr(0, index); - model = this.get(key); - } - else { - fn = key; - model = this; - } - if (!model) { - throw new nodom.NodomError('notexist1', nodom.TipMsg.TipWords['dataItem'], key); - } - let retMdl; - let data = model.data; - if (data[fn] !== value) { - let module = nodom.ModuleFactory.get(this.moduleId); - if (nodom.Util.isObject(value) || nodom.Util.isArray(value)) { - retMdl = new Model(value, module, model, fn); - } - let ds = Object.getOwnPropertyDescriptor(data, fn); - if (ds === undefined || ds['writable']) { - model.defineProp(data, fn); - } - model.update(fn, value); - data[fn] = value; - } - return retMdl || model; - } - get(key) { - if (typeof key === 'number') { - if (nodom.Util.isArray(this.children)) { - let arr = this.children; - if (arr.length > key) { - return arr[key]; - } - } - } - else { - let arr = key.split('.'); - let mdl = this; - for (let i = 0; i < arr.length && mdl; i++) { - if (mdl.children) { - mdl = mdl.children[arr[i]]; - } - else { - return; - } - } - return mdl; - } - } - del(key) { - let fn; - let mdl; - if (typeof key === 'number') { - if (nodom.Util.isArray(this.children)) { - this.children.splice(key, 1); - this.data.splice(key, 1); - } - } - else { - let k1 = key; - let index = k1.lastIndexOf('.'); - if (index === -1) { - mdl = this; - fn = k1; - } - else { - mdl = this.get(k1.substr(0, index)); - fn = k1.substr(index + 1); - } - delete mdl.children[fn]; - delete this.data[fn]; - } - } - update(field, value) { - let change = false; - let module = nodom.ModuleFactory.get(this.moduleId); - if (nodom.Util.isString(field)) { - let fieldObj = this.fields[field]; - if (!fieldObj) { - fieldObj = {}; - this.fields[field] = fieldObj; - } - if (fieldObj.value !== value) { - fieldObj.value = value; - if (fieldObj.handlers && fieldObj.handlers.length > 0) { - for (let f of fieldObj.handlers) { - if (nodom.Util.isFunction(f)) { - nodom.Util.apply(f, this, [module, field, value]); - } - else if (nodom.Util.isString(f)) { - let foo = module.getMethod(f); - if (nodom.Util.isFunction(foo)) { - nodom.Util.apply(foo, this, [module, field, value]); - } - } - } - } - change = true; - } - } - if (change) { - module.dataChange(); - } - } - query(key) { - if (typeof key === 'number') { - if (nodom.Util.isArray(this.data)) { - return this.data[key]; - } - } - else { - let k1 = key; - let index = k1.lastIndexOf('.'); - let mdl; - let fn; - if (index === -1) { - mdl = this; - fn = k1; - } - else { - mdl = this.get(k1.substr(0, index)); - fn = k1.substr(index + 1); - } - if (mdl && fn) { - return mdl.data[fn]; - } - } - } - getData(dirty) { - if (dirty) { - return this.data; - } - return nodom.Util.clone(this.data, /^\$\S+/); - } - watch(key, operate, cancel) { - let fieldObj = this.fields[key]; - if (!fieldObj) { - fieldObj = {}; - this.fields[key] = fieldObj; - } - if (!fieldObj.handlers) { - fieldObj.handlers = []; - } - ; - let ind = fieldObj.handlers.indexOf(operate); - if (cancel) { - if (ind !== -1) { - fieldObj.handlers.splice(ind, 1); - } - } - else { - if (ind === -1) { - fieldObj.handlers.push(operate); - } - } - } - addSetterGetter(data) { - let me = this; - let module = nodom.ModuleFactory.get(this.moduleId); - if (nodom.Util.isObject(data)) { - nodom.Util.getOwnProps(data).forEach((p) => { - let v = data[p]; - if (nodom.Util.isObject(v) || nodom.Util.isArray(v)) { - new Model(v, module, this, p); - } - else { - this.update(p, v); - this.defineProp(data, p); - } - }); - } - else if (nodom.Util.isArray(data)) { - let watcher = ['push', 'unshift', 'splice', 'pop', 'shift', 'reverse', 'sort']; - watcher.forEach((item) => { - data[item] = function () { - let args = []; - switch (item) { - case 'push': - for (let i = 0; i < arguments.length; i++) { - args.push(arguments[i]); - } - break; - case 'unshift': - for (let i = 0; i < arguments.length; i++) { - args.push(arguments[i]); - } - break; - case 'splice': - if (arguments.length > 2) { - for (let i = 2; i < arguments.length; i++) { - args.push(arguments[i]); - } - } - break; - case 'pop': - break; - case 'shift': - break; - } - Array.prototype[item].apply(data, arguments); - args.forEach((arg) => { - if (nodom.Util.isObject(arg) || nodom.Util.isArray(arg)) { - new Model(arg, module, me); - } - }); - nodom.Renderer.add(nodom.ModuleFactory.get(me.moduleId)); - }; - }); - data.forEach((item) => { - if (nodom.Util.isObject(item) || nodom.Util.isArray(item)) { - new Model(item, module, me); - } - }); - } - } - defineProp(data, p) { - Object.defineProperty(data, p, { - configurable: true, - set: (v) => { - if (this.fields[p] && this.fields[p].value === v) { - return; - } - this.update(p, v); - data[p] = v; - }, - get: () => { - if (this.fields[p] !== undefined) { - return this.fields[p].value; - } - } - }); - } - } - nodom.Model = Model; -})(nodom || (nodom = {})); -var nodom; -(function (nodom) { - class ModelFactory extends nodom.Factory { - } - nodom.ModelFactory = ModelFactory; -})(nodom || (nodom = {})); -var nodom; -(function (nodom) { - class Module { - constructor(config) { - this.firstRender = true; - this.children = []; - this.createOps = []; - this.state = 0; - this.loadNewData = false; - this.modelFactory = new nodom.ModelFactory(); - this.renderDoms = []; - this.container = null; - this.moduleMap = new Map(); - this.plugins = new Map(); - this.id = nodom.Util.genId(); - if (config && config.name) { - this.name = config.name; - } - else { - this.name = 'Module' + this.id; - } - nodom.ModuleFactory.add(this); - this.methodFactory = new nodom.MethodFactory(this); - this.modelFactory = new nodom.ModelFactory(this); - for (let foo of this.createOps) { - foo.call(this); - } - this.doModuleEvent('onCreate'); - if (!config) { - return; - } - this.initConfig = config; - this.selector = config.el; - if (nodom.Util.isObject(config.methods)) { - nodom.Util.getOwnProps(config.methods).forEach((item) => { - this.methodFactory.add(item, config.methods[item]); - }); - } - if (this.getContainer()) { - this.template = this.container.innerHTML.trim(); - this.container.innerHTML = ''; - } - } - init() { - return __awaiter(this, void 0, void 0, function* () { - let config = this.initConfig; - let urlArr = []; - let cssPath = nodom.Application.getPath('css'); - let templatePath = nodom.Application.getPath('template'); - let jsPath = nodom.Application.getPath('js'); - if (config && nodom.Util.isArray(config.requires) && config.requires.length > 0) { - config.requires.forEach((item) => { - let type; - let url = ''; - if (nodom.Util.isObject(item)) { - type = item['type'] || 'js'; - url = item['url']; - } - else { - type = 'js'; - url = item; - } - let path = type === 'js' ? jsPath : cssPath; - urlArr.push({ url: nodom.Util.mergePath([path, url]), type: type }); - }); - } - let templateStr = this.template; - if (config.template) { - config.template = config.template.trim(); - if (config.template.startsWith('<')) { - templateStr = config.template; - } - else { - urlArr.push({ - url: nodom.Util.mergePath([templatePath, config.template]), - type: config.template.endsWith('.nd') ? 'nd' : 'template' - }); - } - } - delete this.template; - if (!nodom.Util.isEmpty(templateStr)) { - this.virtualDom = nodom.Compiler.compile(templateStr); - } - if (config.data) { - if (nodom.Util.isObject(config.data)) { - this.model = new nodom.Model(config.data, this); - } - else { - urlArr.push({ - url: config.data, - type: 'data' - }); - this.dataUrl = config.data; - } - } - else { - this.model = new nodom.Model({}, this); - } - if (urlArr.length > 0) { - let rets = yield nodom.ResourceManager.getResources(urlArr); - for (let r of rets) { - if (r.type === 'template' || r.type === 'nd') { - this.virtualDom = r.content; - } - else if (r.type === 'data') { - this.model = new nodom.Model(r.content, this); - } - } - } - if (this.initConfig.modules) { - for (let cfg of this.initConfig.modules) { - let mdl = new Module(cfg); - mdl.parentId = this.id; - this.addChild(mdl.id); - } - } - changeState(this); - delete this.initConfig; - function changeState(mod) { - if (mod.isMain) { - mod.state = 3; - nodom.Renderer.add(mod); - } - else if (mod.parentId) { - mod.state = nodom.ModuleFactory.get(mod.parentId).state; - } - else { - mod.state = 1; - } - } - }); - } - render() { - if (this.state !== 3 || !this.virtualDom || !this.getContainer()) { - return false; - } - let root = this.virtualDom.clone(); - if (this.firstRender) { - if (this.loadNewData && this.dataUrl) { - nodom.request({ - url: this.dataUrl, - type: 'json' - }).then((r) => { - this.model = new nodom.Model(r, this); - this.doFirstRender(root); - this.loadNewData = false; - }); - } - else { - this.doFirstRender(root); - } - } - else { - this.doModuleEvent('onBeforeRender'); - if (this.model) { - root.modelId = this.model.id; - let oldTree = this.renderTree; - this.renderTree = root; - root.render(this, null); - this.clearDontRender(root); - this.doModuleEvent('onBeforeRenderToHtml'); - root.compare(oldTree, this.renderDoms); - for (let i = this.renderDoms.length - 1; i >= 0; i--) { - let item = this.renderDoms[i]; - if (item.type === 'del') { - item.node.removeFromHtml(this); - this.renderDoms.splice(i, 1); - } - } - this.renderDoms.forEach((item) => { - item.node.renderToHtml(this, item); - }); - } - this.doModuleEvent('onRender'); - } - this.renderDoms = []; - return true; - } - doFirstRender(root) { - this.doModuleEvent('onBeforeFirstRender'); - this.renderTree = root; - if (this.model) { - root.modelId = this.model.id; - } - root.render(this, null); - this.clearDontRender(root); - this.doModuleEvent('onBeforeFirstRenderToHTML'); - nodom.Util.empty(this.container); - root.renderToHtml(this, { type: 'fresh' }); - delete this.firstRender; - this.doModuleEvent('onFirstRender'); - } - clone(moduleName) { - let me = this; - let m = new Module({ name: moduleName }); - let excludes = ['id', 'name', 'model', 'virtualDom', 'container', 'containerKey', 'modelFactory', 'plugins']; - Object.getOwnPropertyNames(this).forEach((item) => { - if (excludes.includes(item)) { - return; - } - m[item] = me[item]; - }); - if (this.model) { - let d = this.model.getData(); - m.model = new nodom.Model(nodom.Util.clone(d), m); - } - m.virtualDom = this.virtualDom.clone(true); - return m; - } - getContainer() { - if (this.selector) { - this.container = document.querySelector(this.selector); - } - else { - this.container = document.querySelector("[key='" + this.containerKey + "']"); - } - return this.container; - } - setContainerKey(key) { - this.containerKey = key; - } - getContainerKey() { - return (this.containerKey); - } - dataChange() { - nodom.Renderer.add(this); - } - addChild(moduleId) { - if (!this.children.includes(moduleId)) { - this.children.push(moduleId); - let m = nodom.ModuleFactory.get(moduleId); - if (m) { - m.parentId = this.id; - } - this.moduleMap.set(m.name, moduleId); - nodom.MessageQueue.move(m.name, moduleId, this.id); - } - } - send(toName, data, type) { - if (typeof toName === 'number') { - nodom.MessageQueue.add(this.id, toName, data); - return; - } - let toId; - let parentId; - let m; - switch (type) { - case 1: - m = this.getChild(toName); - if (m) { - toId = m.id; - } - parentId = this.id; - break; - case 2: - toId = this.parentId || 0; - default: - parentId = this.parentId || 0; - m = nodom.ModuleFactory.get(parentId); - if (m) { - m = m.getChild(toName); - if (m) { - toId = m.id; - } - } - } - if (toId) { - nodom.MessageQueue.add(this.id, toId, data); - } - else { - nodom.MessageQueue.add(this.id, toName, data, parentId); - } - } - broadcast(data) { - if (this.parentId) { - let pmod = nodom.ModuleFactory.get(this.parentId); - if (pmod) { - this.send(this.parentId, data); - if (pmod.children) { - pmod.children.forEach((item) => { - if (item === this.id) { - return; - } - let m = nodom.ModuleFactory.get(item); - this.send(m.id, data); - }); - } - } - } - if (this.children !== undefined) { - this.children.forEach((item) => { - let m = nodom.ModuleFactory.get(item); - this.send(m.id, data); - }); - } - } - receive(fromName, data) { - this.doModuleEvent('onReceive', [fromName, data]); - } - active() { - return __awaiter(this, void 0, void 0, function* () { - if (this.state === 3) { - return; - } - if (this.state === 0) { - yield this.init(); - } - this.state = 3; - nodom.Renderer.add(this); - if (nodom.Util.isArray(this.children)) { - this.children.forEach((item) => __awaiter(this, void 0, void 0, function* () { - let m = nodom.ModuleFactory.get(item); - if (m) { - yield m.active(); - } - })); - } - }); - } - unactive() { - if (this.isMain || this.state === 2) { - return; - } - this.state = 2; - this.firstRender = true; - if (nodom.Util.isArray(this.children)) { - this.children.forEach((item) => { - let m = nodom.ModuleFactory.get(item); - if (m) { - m.unactive(); - } - }); - } - } - destroy() { - if (nodom.Util.isArray(this.children)) { - this.children.forEach((item) => { - let m = nodom.ModuleFactory.get(item); - if (m) { - m.destroy(); - } - }); - } - nodom.ModuleFactory.remove(this.id); - } - doModuleEvent(eventName, param) { - const foo = this.methodFactory.get(eventName); - if (!foo) { - return; - } - if (!param) { - param = [this.model]; - } - else { - param.unshift(this.model); - } - nodom.Util.apply(foo, this, param); - } - addCreateOperation(foo) { - if (!nodom.Util.isFunction(foo)) { - return; - } - if (!this.createOps.includes(foo)) { - this.createOps.push(foo); - } - } - clearDontRender(dom) { - for (let i = 0; i < dom.children.length; i++) { - let item = dom.children[i]; - if (item.dontRender) { - dom.children.splice(i, 1); - return; - } - if (item.dontRenderSelf) { - let arr = []; - for (let d of item.children) { - d.parent = dom.parent; - d.parentKey = dom.parentKey; - arr.push(d); - } - dom.children.splice.apply(dom.children, [i, 1].concat(arr)); - continue; - } - this.clearDontRender(item); - } - } - getChild(name, descendant) { - if (this.moduleMap.has(name)) { - let mid = this.moduleMap.get(name); - return nodom.ModuleFactory.get(mid); - } - else if (descendant) { - for (let id of this.children) { - let m = nodom.ModuleFactory.get(id); - if (m) { - let m1 = m.getChild(name, descendant); - if (m1) { - return m1; - } - } - } - } - return null; - } - getMethod(name) { - return this.methodFactory.get(name); - } - addMethod(name, foo) { - this.methodFactory.add(name, foo); - } - removeMethod(name) { - this.methodFactory.remove(name); - } - addPlugin(name, plugin) { - if (name) { - this.plugins.set(name, plugin); - } - } - getPlugin(name) { - return this.plugins.get(name); - } - getModel(modelId) { - return modelId ? this.modelFactory.get(modelId) : this.model; - } - setModel(modelId, model) { - this.modelFactory.add(modelId, model); - } - setDataUrl(url) { - this.dataUrl = url; - this.loadNewData = true; - } - getNode(key, notNull) { - let keyName; - let value; - if (typeof key === 'string') { - keyName = 'key'; - value = key; - } - else { - keyName = Object.getOwnPropertyNames(key)[0]; - value = key[keyName]; - } - let qs = "[" + keyName + "='" + value + "']"; - let el = this.container ? this.container.querySelector(qs) : null; - if (!el && notNull) { - return this.container; - } - return el; - } - getElement(key, fromVirtualDom) { - let tree = fromVirtualDom ? this.virtualDom : this.renderTree; - return tree.query(key); - } - isContainerKey(key) { - return this.containerKey === key; - } - setFirstRender(flag) { - this.firstRender = flag; - } - setMain() { - this.isMain = true; - } - setSelector(selector) { - this.selector = selector; - } - } - nodom.Module = Module; -})(nodom || (nodom = {})); -var nodom; -(function (nodom) { - let ModuleFactory = (() => { - class ModuleFactory { - static add(item) { - this.modules.set(item.id, item); - } - static get(id) { - return this.modules.get(id); - } - static getInstance(className, moduleName, data) { - return __awaiter(this, void 0, void 0, function* () { - if (!this.classes.has(className)) { - throw new nodom.NodomError('notexist1', nodom.TipMsg.TipWords['moduleClass'], className); - } - let cfg = this.classes.get(className); - if (moduleName) { - cfg.name = moduleName; - } - if (!cfg.instance) { - let id = nodom.Util.genId(); - if (!cfg.initing) { - cfg.initing = true; - this.initModule(cfg); - } - return new Promise((res, rej) => { - check(); - function check() { - if (!cfg.initing) { - res(get(cfg)); - } - else { - setTimeout(check, 0); - } - } - }); - } - else { - return get(cfg); - } - function get(cfg) { - if (cfg.singleton) { - return cfg.instance; - } - else { - let mdl = cfg.instance.clone(moduleName); - if (data) { - if (typeof data === 'string') { - mdl.setDataUrl(data); - } - else { - mdl.model = new nodom.Model(data, mdl); - } - } - return mdl; - } - } - }); - } - static remove(id) { - this.modules.delete(id); - } - static setMain(m) { - this.mainModule = m; - m.setMain(); - } - static getMain() { - return this.mainModule; - } - static addModules(modules) { - return __awaiter(this, void 0, void 0, function* () { - for (let cfg of modules) { - if (!cfg.path) { - throw new nodom.NodomError("paramException", 'modules', 'path'); - } - if (!cfg.class) { - throw new nodom.NodomError("paramException", 'modules', 'class'); - } - if (cfg.lazy === undefined) { - cfg.lazy = true; - } - if (cfg.singleton === undefined) { - cfg.singleton = true; - } - if (!cfg.lazy) { - yield this.initModule(cfg); - } - this.classes.set(cfg.class, cfg); - } - }); - } - static initModule(cfg) { - return __awaiter(this, void 0, void 0, function* () { - let path = cfg.path; - if (!path.endsWith('.js')) { - path += '.js'; - } - let url = nodom.Util.mergePath([nodom.Application.getPath('module'), path]); - yield nodom.ResourceManager.getResources([{ url: url, type: 'js' }]); - let cls = eval(cfg.class); - if (cls) { - let instance = Reflect.construct(cls, [{ - name: cfg.name, - data: cfg.data, - lazy: cfg.lazy - }]); - yield instance.init(); - cfg.instance = instance; - if (cfg.singleton) { - this.modules.set(instance.id, instance); - } - cfg.initing = false; - } - else { - throw new nodom.NodomError('notexist1', nodom.TipMsg.TipWords['moduleClass'], cfg.class); - } - }); - } - } - ModuleFactory.modules = new Map(); - ModuleFactory.classes = new Map(); - return ModuleFactory; - })(); - nodom.ModuleFactory = ModuleFactory; -})(nodom || (nodom = {})); -var nodom; -(function (nodom) { - class NodomError extends Error { - constructor(errorName, p1, p2, p3, p4) { - super(errorName); - let msg = nodom.TipMsg.ErrorMsgs[errorName]; - if (msg === undefined) { - this.message = "未知错误"; - return; - } - let params = [msg]; - if (p1) { - params.push(p1); - } - if (p2) { - params.push(p2); - } - if (p3) { - params.push(p3); - } - if (p4) { - params.push(p4); - } - this.message = nodom.Util.compileStr.apply(null, params); - } - } - nodom.NodomError = NodomError; - ; -})(nodom || (nodom = {})); -var nodom; -(function (nodom) { - class NodomEvent { - constructor(eventName, eventStr, handler) { - this.id = nodom.Util.genId(); - this.name = eventName; - if (eventStr) { - let tp = typeof eventStr; - if (tp === 'string') { - let eStr = eventStr.trim(); - eStr.split(':').forEach((item, i) => { - item = item.trim(); - if (i === 0) { - this.handler = item; - } - else { - switch (item) { - case 'delg': - this.delg = true; - break; - case 'nopopo': - this.nopopo = true; - break; - case 'once': - this.once = true; - break; - case 'capture': - this.capture = true; - break; - } - } - }); - } - else if (tp === 'function') { - handler = eventStr; - } - } - if (handler) { - this.handler = handler; - } - let dtype = 'ontouchend' in document ? 1 : 2; - if (dtype === 1) { - switch (this.name) { - case 'click': - this.name = 'tap'; - break; - case 'mousedown': - this.name = 'touchstart'; - break; - case 'mouseup': - this.name = 'touchend'; - break; - case 'mousemove': - this.name = 'touchmove'; - break; - } - } - else { - switch (this.name) { - case 'tap': - this.name = 'click'; - break; - case 'touchstart': - this.name = 'mousedown'; - break; - case 'touchend': - this.name = 'mouseup'; - break; - case 'touchmove': - this.name = 'mousemove'; - break; - } - } - } - fire(e, el) { - const module = nodom.ModuleFactory.get(this.moduleId); - if (!module.getContainer()) { - return; - } - let dom = module.getElement(this.domKey); - const model = module.getModel(dom.modelId); - if (this.capture) { - handleSelf(this, e, model, module, dom, el); - handleDelg(this, e, dom); - } - else { - if (handleDelg(this, e, dom)) { - handleSelf(this, e, model, module, dom, el); - } - } - if (this.events !== undefined && - this.events.has(this.name) && - this.events.get(this.name).length === 0 && - this.handler === undefined) { - if (!el) { - el = module.getNode(this.domKey); - } - if (ExternalEvent.touches[this.name]) { - ExternalEvent.unregist(this, el); - } - else { - if (el !== null) { - el.removeEventListener(this.name, this.handleListener); - } - } - } - function handleDelg(eObj, e, dom) { - if (eObj.events === undefined) { - return true; - } - let eKey = e.target.getAttribute('key'); - let arr = eObj.events.get(eObj.name); - if (nodom.Util.isArray(arr)) { - if (arr.length > 0) { - for (let i = 0; i < arr.length; i++) { - let sdom = dom.query(arr[i].domKey); - if (!sdom) { - continue; - } - if (eKey === sdom.key || sdom.query(eKey)) { - arr[i].fire(e); - if (arr[i].once) { - eObj.removeChild(arr[i]); - } - if (arr[i].nopopo) { - return false; - } - } - } - } - else { - eObj.events.delete(eObj.name); - } - } - return true; - } - function handleSelf(eObj, e, model, module, dom, el) { - if (typeof eObj.handler === 'string') { - eObj.handler = module.getMethod(eObj.handler); - } - if (!eObj.handler) { - return; - } - if (eObj.nopopo) { - e.stopPropagation(); - } - nodom.Util.apply(eObj.handler, eObj, [dom, model, module, e, el]); - if (eObj.once) { - delete eObj.handler; - } - } - } - bind(module, dom, el, parent, parentEl) { - this.moduleId = module.id; - this.domKey = dom.key; - if (this.delg && parent) { - this.delegateTo(module, dom, el, parent, parentEl); - } - else { - this.bindTo(el); - } - } - bindTo(el) { - if (ExternalEvent.touches[this.name]) { - ExternalEvent.regist(this, el); - } - else { - this.handleListener = (e) => { - this.fire(e, el); - }; - el.addEventListener(this.name, this.handleListener, this.capture); - } - } - delegateTo(module, vdom, el, parent, parentEl) { - this.domKey = vdom.key; - this.moduleId = module.id; - if (!parentEl) { - parentEl = document.body; - } - if (!parent.events.has(this.name)) { - let ev = new NodomEvent(this.name); - ev.bindTo(parentEl); - parent.events.set(this.name, ev); - } - let evt = parent.events.get(this.name); - let ev; - if (nodom.Util.isArray(evt) && evt.length > 0) { - ev = evt[0]; - } - else { - ev = evt; - } - if (ev) { - ev.addChild(this); - } - } - addChild(ev) { - if (!this.events) { - this.events = new Map(); - } - if (!this.events.has(this.name)) { - this.events.set(this.name, new Array()); - } - this.events.get(this.name).push(ev); - } - removeChild(ev) { - if (this.events === undefined || this.events[ev.name] === undefined) { - return; - } - let ind = this.events[ev.name].indexOf(ev); - if (ind !== -1) { - this.events[ev.name].splice(ind, 1); - if (this.events[ev.name].length === 0) { - this.events.delete(ev.name); - } - } - } - clone() { - let evt = new NodomEvent(this.name); - let arr = ['delg', 'once', 'nopopo', 'capture', 'handler']; - arr.forEach((item) => { - evt[item] = this[item]; - }); - return evt; - } - getDomKey() { - return this.domKey; - } - setExtraParam(key, value) { - if (!this.extraParamMap) { - this.extraParamMap = new Map(); - } - this.extraParamMap.set(key, value); - } - getExtraParam(key) { - return this.extraParamMap.get(key); - } - } - nodom.NodomEvent = NodomEvent; - let ExternalEvent = (() => { - class ExternalEvent { - static regist(evtObj, el) { - let touchEvts = ExternalEvent.touches[evtObj.name]; - if (!nodom.Util.isEmpty(evtObj.touchListeners)) { - this.unregist(evtObj); - } - if (!el) { - const module = nodom.ModuleFactory.get(evtObj.moduleId); - el = module.getNode(evtObj.getDomKey()); - } - evtObj.touchListeners = new Map(); - if (touchEvts && el !== null) { - nodom.Util.getOwnProps(touchEvts).forEach(function (ev) { - evtObj.touchListeners[ev] = function (e) { - touchEvts[ev](e, evtObj); - }; - el.addEventListener(ev, evtObj.touchListeners[ev], evtObj.capture); - }); - } - } - static unregist(evtObj, el) { - const evt = ExternalEvent.touches[evtObj.name]; - if (!el) { - const module = nodom.ModuleFactory.get(evtObj.moduleId); - el = module.getNode(evtObj.getDomKey()); - } - if (evt) { - if (el !== null) { - nodom.Util.getOwnProps(evtObj.touchListeners).forEach(function (ev) { - el.removeEventListener(ev, evtObj.touchListeners[ev]); - }); - } - } - } - } - ExternalEvent.touches = {}; - return ExternalEvent; - })(); - nodom.ExternalEvent = ExternalEvent; - ExternalEvent.touches = { - tap: { - touchstart: function (e, evtObj) { - let tch = e.touches[0]; - evtObj.setExtraParam('pos', { sx: tch.pageX, sy: tch.pageY, t: Date.now() }); - }, - touchmove: function (e, evtObj) { - let pos = evtObj.getExtraParam('pos'); - let tch = e.touches[0]; - let dx = tch.pageX - pos.sx; - let dy = tch.pageY - pos.sy; - if (Math.abs(dx) > 5 || Math.abs(dy) > 5) { - pos.move = true; - } - }, - touchend: function (e, evtObj) { - let pos = evtObj.getExtraParam('pos'); - let dt = Date.now() - pos.t; - if (pos.move === true || dt > 200) { - return; - } - evtObj.fire(e); - } - }, - swipe: { - touchstart: function (e, evtObj) { - let tch = e.touches[0]; - let t = Date.now(); - evtObj.setExtraParam('swipe', { - oldTime: [t, t], - speedLoc: [{ x: tch.pageX, y: tch.pageY }, { x: tch.pageX, y: tch.pageY }], - oldLoc: { x: tch.pageX, y: tch.pageY } - }); - }, - touchmove: function (e, evtObj) { - let nt = Date.now(); - let tch = e.touches[0]; - let mv = evtObj.getExtraParam('swipe'); - if (nt - mv.oldTime > 50) { - mv.speedLoc[0] = { x: mv.speedLoc[1].x, y: mv.speedLoc[1].y }; - mv.speedLoc[1] = { x: tch.pageX, y: tch.pageY }; - mv.oldTime[0] = mv.oldTime[1]; - mv.oldTime[1] = nt; - } - mv.oldLoc = { x: tch.pageX, y: tch.pageY }; - }, - touchend: function (e, evtObj) { - let mv = evtObj.getExtraParam('swipe'); - let nt = Date.now(); - let ind = (nt - mv.oldTime[1] < 30) ? 0 : 1; - let dx = mv.oldLoc.x - mv.speedLoc[ind].x; - let dy = mv.oldLoc.y - mv.speedLoc[ind].y; - let s = Math.sqrt(dx * dx + dy * dy); - let dt = nt - mv.oldTime[ind]; - if (dt > 300 || s < 10) { - return; - } - let v0 = s / dt; - if (v0 > 0.05) { - let sname = ''; - if (dx < 0 && Math.abs(dy / dx) < 1) { - e.v0 = v0; - sname = 'swipeleft'; - } - if (dx > 0 && Math.abs(dy / dx) < 1) { - e.v0 = v0; - sname = 'swiperight'; - } - if (dy > 0 && Math.abs(dx / dy) < 1) { - e.v0 = v0; - sname = 'swipedown'; - } - if (dy < 0 && Math.abs(dx / dy) < 1) { - e.v0 = v0; - sname = 'swipeup'; - } - if (evtObj.name === sname) { - evtObj.fire(e); - } - } - } - } - }; - ExternalEvent.touches['swipeleft'] = ExternalEvent.touches['swipe']; - ExternalEvent.touches['swiperight'] = ExternalEvent.touches['swipe']; - ExternalEvent.touches['swipeup'] = ExternalEvent.touches['swipe']; - ExternalEvent.touches['swipedown'] = ExternalEvent.touches['swipe']; -})(nodom || (nodom = {})); -var nodom; -(function (nodom) { - let Renderer = (() => { - class Renderer { - static add(module) { - if (module.state !== 3) { - return; - } - if (!this.waitList.includes(module.id)) { - this.waitList.push(module.id); - } - } - static remove(module) { - let ind; - if ((ind = this.waitList.indexOf(module.id)) !== -1) { - this.waitList.splice(ind, 1); - } - } - static render() { - for (let i = 0; i < this.waitList.length; i++) { - let m = nodom.ModuleFactory.get(this.waitList[i]); - if (!m || m.render()) { - this.waitList.shift(); - i--; - } - } - } - } - Renderer.waitList = []; - return Renderer; - })(); - nodom.Renderer = Renderer; -})(nodom || (nodom = {})); -var nodom; -(function (nodom) { - let Router = (() => { - class Router { - static go(path) { - return __awaiter(this, void 0, void 0, function* () { - for (let i = 0; i < this.waitList.length; i++) { - let li = this.waitList[i]; - if (li === path) { - return; - } - if (li.indexOf(path) === 0 && li.substr(path.length + 1, 1) === '/') { - return; - } - } - this.waitList.push(path); - this.load(); - }); - } - static load() { - return __awaiter(this, void 0, void 0, function* () { - if (this.loading || this.waitList.length === 0) { - return; - } - let path = this.waitList.shift(); - this.loading = true; - yield this.start(path); - this.loading = false; - this.load(); - }); - } - static start(path) { - return __awaiter(this, void 0, void 0, function* () { - let diff = this.compare(this.currentPath, path); - let parentModule; - if (diff[0] === null) { - parentModule = findParentModule(); - } - else { - if (typeof diff[0].module === 'string') { - parentModule = yield nodom.ModuleFactory.getInstance(diff[0].module, diff[0].moduleName, diff[0].dataUrl); - } - else { - parentModule = nodom.ModuleFactory.get(diff[0].module); - } - } - if (!parentModule) { - return; - } - for (let i = diff[1].length - 1; i >= 0; i--) { - const r = diff[1][i]; - if (!r.module) { - continue; - } - let module = nodom.ModuleFactory.get(r.module); - if (nodom.Util.isFunction(this.onDefaultLeave)) { - this.onDefaultLeave(module.model); - } - if (nodom.Util.isFunction(r.onLeave)) { - r.onLeave(module.model); - } - module.unactive(); - } - let showPath; - if (diff[2].length === 0) { - let route = diff[0]; - let proute = diff[3]; - if (route !== null) { - showPath = route.useParentPath && proute ? proute.fullPath : route.fullPath; - let module = nodom.ModuleFactory.get(route.module); - route.setLinkActive(); - module.setFirstRender(true); - yield module.active(); - setRouteParamToModel(route, module); - } - } - else { - for (let ii = 0, index = 0, len = diff[2].length; ii < len; ii++) { - let route = diff[2][ii]; - if (!route || !route.module) { - continue; - } - if (!route.useParentPath) { - showPath = route.fullPath; - } - let module; - if (typeof route.module === 'string') { - module = yield nodom.ModuleFactory.getInstance(route.module, route.moduleName, route.dataUrl); - if (!module) { - throw new nodom.NodomError('notexist1', nodom.TipMsg.TipWords['module'], route.module); - } - route.module = module.id; - } - else { - module = nodom.ModuleFactory.get(route.module); - } - module.setFirstRender(true); - let routerKey = Router.routerKeyMap.get(parentModule.id); - for (let i = 0; i < parentModule.children.length; i++) { - let m = nodom.ModuleFactory.get(parentModule.children[i]); - if (m && m.isContainerKey(routerKey)) { - parentModule.children.splice(i, 1); - break; - } - } - parentModule.addChild(module.id); - module.setContainerKey(routerKey); - yield module.active(); - route.setLinkActive(); - setRouteParamToModel(route); - if (nodom.Util.isFunction(this.onDefaultEnter)) { - this.onDefaultEnter(module.model); - } - if (nodom.Util.isFunction(route.onEnter)) { - route.onEnter(module.model); - } - parentModule = module; - } - } - if (this.startStyle !== 2 && showPath) { - let p = nodom.Util.mergePath([nodom.Application.getPath('route'), showPath]); - if (this.showPath && showPath.indexOf(this.showPath) === 0) { - history.replaceState(path, '', p); - } - else { - history.pushState(path, '', p); - } - this.showPath = showPath; - } - this.currentPath = path; - this.startStyle = 0; - function setRouteParamToModel(route, module) { - if (!route) { - return; - } - if (!module) { - module = nodom.ModuleFactory.get(route.module); - } - let o = { - path: route.path - }; - if (!nodom.Util.isEmpty(route.data)) { - o['data'] = route.data; - } - if (!module.model) { - module.model = new nodom.Model({}, module); - } - module.model.set('$route', o); - } - function findParentModule(pm) { - if (!pm) { - pm = nodom.ModuleFactory.getMain(); - } - if (Router.routerKeyMap.has(pm.id)) { - return pm; - } - for (let c of pm.children) { - let m = nodom.ModuleFactory.get(c); - return findParentModule(m); - } - } - }); - } - static redirect(path) { - this.go(path); - } - static addRoute(route, parent) { - if (RouterTree.add(route, parent) === false) { - throw new nodom.NodomError("exist1", nodom.TipMsg.TipWords['route'], route.path); - } - this.routes.set(route.id, route); - } - static getRoute(path, last) { - if (!path) { - return null; - } - let routes = RouterTree.get(path); - if (routes === null || routes.length === 0) { - return null; - } - if (last) { - return [routes.pop()]; - } - else { - return routes; - } - } - static compare(path1, path2) { - let arr1 = null; - let arr2 = null; - if (path1) { - arr1 = this.getRoute(path1); - } - if (path2) { - arr2 = this.getRoute(path2); - } - let len = 0; - if (arr1 !== null) { - len = arr1.length; - } - if (arr2 !== null) { - if (arr2.length < len) { - len = arr2.length; - } - } - else { - len = 0; - } - let retArr1 = []; - let retArr2 = []; - let i = 0; - for (i = 0; i < len; i++) { - if (arr1[i].id === arr2[i].id) { - if (JSON.stringify(arr1[i].data) !== JSON.stringify(arr2[i].data)) { - i++; - break; - } - } - else { - break; - } - } - if (arr1 !== null) { - for (let j = i; j < arr1.length; j++) { - retArr1.push(arr1[j]); - } - } - if (arr2 !== null) { - for (let j = i; j < arr2.length; j++) { - retArr2.push(arr2[j]); - } - } - let p1 = null; - let p2 = null; - if (arr1 !== null && i > 0) { - for (let j = i - 1; j >= 0 && (p1 === null || p2 === null); j--) { - if (arr1[j].module !== undefined) { - if (p1 === null) { - p1 = arr1[j]; - } - else if (p2 === null) { - p2 = arr1[j]; - } - } - } - } - return [p1, retArr1, retArr2, p2]; - } - static changeActive(module, path) { - if (!module || !path || path === '') { - return; - } - let domArr = Router.activeDomMap.get(module.id); - if (!domArr) { - return; - } - domArr.forEach((item) => { - let dom = module.getElement(item); - if (!dom) { - return; - } - let domPath = dom.getProp('path'); - if (dom.hasProp('activename')) { - let model = module.modelFactory.get(dom.modelId); - if (!model) { - return; - } - let field = dom.getProp('activename'); - if (path === domPath || path.indexOf(domPath + '/') === 0) { - model.set(field, true); - } - else { - model.set(field, false); - } - } - }); - } - } - Router.loading = false; - Router.routes = new Map(); - Router.currentPath = ''; - Router.showPath = ''; - Router.waitList = []; - Router.currentIndex = 0; - Router.startStyle = 0; - Router.activeDomMap = new Map(); - Router.routerKeyMap = new Map(); - return Router; - })(); - nodom.Router = Router; - class Route { - constructor(config) { - this.params = []; - this.data = {}; - this.children = []; - for (let o in config) { - this[o] = config[o]; - } - if (config.path === '') { - return; - } - this.id = nodom.Util.genId(); - if (!config.notAdd) { - Router.addRoute(this, config.parent); - } - if (nodom.Util.isArray(config.routes)) { - config.routes.forEach((item) => { - item.parent = this; - new Route(item); - }); - } - } - setLinkActive() { - if (this.parent) { - let pm; - if (!this.parent.module) { - pm = nodom.ModuleFactory.getMain(); - } - else { - pm = nodom.ModuleFactory.get(this.parent.module); - } - if (pm) { - Router.changeActive(pm, this.fullPath); - } - } - } - addChild(child) { - this.children.push(child); - child.parent = this; - } - } - nodom.Route = Route; - class RouterTree { - static add(route, parent) { - if (!this.root) { - this.root = new Route({ path: "", notAdd: true }); - } - let pathArr = route.path.split('/'); - let node = parent || this.root; - let param = []; - let paramIndex = -1; - let prePath = ''; - for (let i = 0; i < pathArr.length; i++) { - let v = pathArr[i].trim(); - if (v === '') { - pathArr.splice(i--, 1); - continue; - } - if (v.startsWith(':')) { - if (param.length === 0) { - paramIndex = i; - } - param.push(v.substr(1)); - } - else { - paramIndex = -1; - param = []; - route.path = v; - let j = 0; - for (; j < node.children.length; j++) { - let r = node.children[j]; - if (r.path === v) { - node = r; - break; - } - } - if (j === node.children.length) { - if (prePath !== '') { - let r = new Route({ path: prePath, notAdd: true }); - node.addChild(r); - node = node.children[node.children.length - 1]; - } - prePath = v; - } - } - if (paramIndex === -1) { - route.params = []; - } - else { - route.params = param; - } - } - if (node !== undefined && node !== route) { - route.path = prePath; - node.addChild(route); - } - return true; - } - static get(path) { - if (!this.root) { - throw new nodom.NodomError("notexist", nodom.TipMsg.TipWords['root']); - } - let pathArr = path.split('/'); - let node = this.root; - let paramIndex = 0; - let retArr = []; - let fullPath = ''; - let preNode = this.root; - for (let i = 0; i < pathArr.length; i++) { - let v = pathArr[i].trim(); - if (v === '') { - continue; - } - let find = false; - for (let j = 0; j < node.children.length; j++) { - if (node.children[j].path === v) { - if (preNode !== this.root) { - preNode.fullPath = fullPath; - preNode.data = node.data; - retArr.push(preNode); - } - node = node.children[j]; - node.data = {}; - preNode = node; - find = true; - paramIndex = 0; - break; - } - } - fullPath += '/' + v; - if (!find) { - if (paramIndex < node.params.length) { - node.data[node.params[paramIndex++]] = v; - } - } - } - if (node !== this.root) { - node.fullPath = fullPath; - retArr.push(node); - } - return retArr; - } - } - window.addEventListener('popstate', function (e) { - const state = history.state; - if (!state) { - return; - } - Router.startStyle = 2; - Router.go(state); - }); -})(nodom || (nodom = {})); -var nodom; -(function (nodom) { - let Scheduler = (() => { - class Scheduler { - static dispatch() { - Scheduler.tasks.forEach((item) => { - if (nodom.Util.isFunction(item.func)) { - if (item.thiser) { - item.func.call(item.thiser); - } - else { - item.func(); - } - } - }); - } - static start(scheduleTick) { - Scheduler.dispatch(); - if (window.requestAnimationFrame) { - window.requestAnimationFrame(Scheduler.start); - } - else { - window.setTimeout(Scheduler.start, scheduleTick || 50); - } - } - static addTask(foo, thiser) { - if (!nodom.Util.isFunction(foo)) { - throw new nodom.NodomError("invoke", "Scheduler.addTask", "0", "function"); - } - Scheduler.tasks.push({ func: foo, thiser: thiser }); - } - static removeTask(foo) { - if (!nodom.Util.isFunction(foo)) { - throw new nodom.NodomError("invoke", "Scheduler.removeTask", "0", "function"); - } - let ind = -1; - if ((ind = Scheduler.tasks.indexOf(foo)) !== -1) { - Scheduler.tasks.splice(ind, 1); - } - } - } - Scheduler.tasks = []; - return Scheduler; - })(); - nodom.Scheduler = Scheduler; -})(nodom || (nodom = {})); -var nodom; -(function (nodom) { - class Serializer { - static serialize(module) { - let dom = module.virtualDom; - addClsName(dom); - return JSON.stringify(dom); - function addClsName(obj) { - if (typeof obj !== 'object') { - return; - } - obj.className = obj.constructor.name; - nodom.Util.getOwnProps(obj).forEach((item) => { - if (nodom.Util.isArray(obj[item])) { - if (obj[item].length === 0) { - delete obj[item]; - } - else { - obj[item].forEach((item1) => { - addClsName(item1); - }); - } - } - else if (typeof obj[item] === 'object') { - if (nodom.Util.isEmpty(obj[item])) { - delete obj[item]; - } - else { - addClsName(obj[item]); - } - } - }); - } - } - static deserialize(jsonStr) { - let jObj = JSON.parse(jsonStr); - return handleCls(jObj); - function handleCls(jsonObj) { - if (!nodom.Util.isObject(jsonObj)) { - return jsonObj; - } - let retObj; - if (jsonObj.hasOwnProperty('className')) { - const cls = jsonObj['className']; - let param = []; - switch (cls) { - case 'Directive': - param = [jsonObj['type']]; - break; - case 'Expression': - param = [jsonObj['execString']]; - break; - case 'Element': - param = []; - break; - case 'NodomEvent': - param = [jsonObj['name']]; - break; - } - let clazz = eval(cls); - retObj = Reflect.construct(clazz, param); - } - else { - retObj = {}; - } - let objArr = []; - let arrArr = []; - nodom.Util.getOwnProps(jsonObj).forEach((item) => { - if (nodom.Util.isObject(jsonObj[item])) { - objArr.push(item); - } - else if (nodom.Util.isArray(jsonObj[item])) { - arrArr.push(item); - } - else { - if (item !== 'className') { - retObj[item] = jsonObj[item]; - } - } - }); - objArr.forEach((item) => { - retObj[item] = handleCls(jsonObj[item]); - }); - arrArr.forEach(item => { - retObj[item] = []; - jsonObj[item].forEach((item1) => { - retObj[item].push(handleCls(item1)); - }); - }); - return retObj; - } - } - } - nodom.Serializer = Serializer; -})(nodom || (nodom = {})); -var nodom; -(function (nodom) { - nodom.DirectiveManager.addType('module', 0, (directive, dom) => { - let value = directive.value; - let valueArr = value.split('|'); - directive.value = valueArr[0]; - dom.setProp('role', 'module'); - if (valueArr.length > 1) { - dom.setProp('modulename', valueArr[1]); - } - directive.extra = {}; - }, (directive, dom, module, parent) => __awaiter(this, void 0, void 0, function* () { - const ext = directive.extra; - let needNew = ext.moduleId === undefined; - let subMdl; - if (ext && ext.moduleId) { - subMdl = nodom.ModuleFactory.get(ext.moduleId); - needNew = subMdl.getContainerKey() !== dom.key; - } - if (needNew) { - let m = yield nodom.ModuleFactory.getInstance(directive.value, dom.getProp('modulename'), dom.getProp('data')); - if (m) { - m.setContainerKey(dom.key); - let dom1 = module.getElement(dom.key, true); - if (dom1) { - let dir = dom1.getDirective('module'); - dir.extra.moduleId = m.id; - } - module.addChild(m.id); - yield m.active(); - } - } - else if (subMdl && subMdl.state !== 3) { - yield subMdl.active(); - } - })); - nodom.DirectiveManager.addType('model', 1, (directive, dom) => { - let value = directive.value; - if (nodom.Util.isString(value)) { - if (value.startsWith('$$')) { - directive.extra = 1; - value = value.substr(2); - } - directive.value = value; - } - }, (directive, dom, module, parent) => { - let startIndex = 0; - let data; - let model; - if (directive.extra === 1) { - model = module.model; - startIndex = 1; - } - else if (dom.modelId) { - model = module.getModel(dom.modelId); - } - if (!model || !model.data) { - return; - } - model = model.get(directive.value); - if (model) { - dom.modelId = model.id; - } - }); - nodom.DirectiveManager.addType('repeat', 2, (directive, dom) => { - let value = directive.value; - if (!value) { - throw new nodom.NodomError("paramException", "x-repeat"); - } - let modelName; - let fa = value.split('|'); - modelName = fa[0]; - if (fa.length > 1) { - directive.filters = []; - for (let i = 1; i < fa.length; i++) { - directive.filters.push(new nodom.Filter(fa[i])); - } - } - if (modelName.startsWith('$$')) { - modelName = modelName.substr(2); - } - directive.value = modelName; - }, (directive, dom, module, parent) => { - let model = module.getModel(dom.modelId); - dom.dontRender = true; - if (!model || !model.data) { - return; - } - model = model.get(directive.value); - if (!model) { - return; - } - let rows = model.data; - if (!nodom.Util.isArray(rows) || rows.length === 0) { - return; - } - dom.dontRender = false; - if (directive.filters && directive.filters.length > 0) { - for (let f of directive.filters) { - rows = f.exec(rows, module); - } - } - let chds = []; - let key = dom.key; - dom.removeDirectives(['repeat']); - for (let i = 0; i < rows.length; i++) { - let node = dom.clone(); - node.modelId = rows[i].$modelId; - setKey(node, key, i); - rows[i].$index = i; - chds.push(node); - } - if (chds.length > 0) { - for (let i = 0, len = parent.children.length; i < len; i++) { - if (parent.children[i] === dom) { - chds = [i + 1, 0].concat(chds); - Array.prototype.splice.apply(parent.children, chds); - break; - } - } - } - dom.dontRender = true; - function setKey(node, key, id) { - node.key = key + '_' + id; - node.children.forEach((dom) => { - setKey(dom, dom.key, id); - }); - } - }); - nodom.DirectiveManager.addType('if', 10, (directive, dom) => { - if (typeof directive.value === 'string') { - let value = directive.value; - if (!value) { - throw new nodom.NodomError("paramException", "x-repeat"); - } - let expr = new nodom.Expression(value); - directive.value = expr; - } - }, (directive, dom, module, parent) => { - let model = module.getModel(dom.modelId); - let v = directive.value.val(model); - let indif = -1, indelse = -1; - for (let i = 0; i < parent.children.length; i++) { - if (parent.children[i] === dom) { - indif = i; - } - else if (indelse === -1 && parent.children[i].hasDirective('else')) { - indelse = i; - } - if (i !== indif && indif !== -1 && indelse === -1 && parent.children[i].tagName !== undefined) { - indelse = -2; - } - if (indif !== -1 && indelse !== -1) { - break; - } - } - if (v && v !== 'false') { - let ind = 0; - if (indelse > 0) { - parent.children[indelse].dontRender = true; - } - } - else { - dom.dontRender = true; - if (indelse > 0) { - parent.children[indelse].dontRender = false; - } - } - }); - nodom.DirectiveManager.addType('else', 10, (directive) => { - return; - }, (directive, dom, module, parent) => { - return; - }); - nodom.DirectiveManager.addType('show', 10, (directive, dom) => { - if (typeof directive.value === 'string') { - let value = directive.value; - if (!value) { - throw new nodom.NodomError("paramException", "x-show"); - } - let expr = new nodom.Expression(value); - directive.value = expr; - } - }, (directive, dom, module, parent) => { - let model = module.getModel(dom.modelId); - let v = directive.value.val(model); - if (v && v !== 'false') { - dom.dontRender = false; - } - else { - dom.dontRender = true; - } - }); - nodom.DirectiveManager.addType('class', 10, (directive, dom) => { - if (typeof directive.value === 'string') { - let obj = eval('(' + directive.value + ')'); - if (!nodom.Util.isObject(obj)) { - return; - } - let robj = {}; - nodom.Util.getOwnProps(obj).forEach(function (key) { - if (nodom.Util.isString(obj[key])) { - robj[key] = new nodom.Expression(obj[key]); - } - else { - robj[key] = obj[key]; - } - }); - directive.value = robj; - } - }, (directive, dom, module, parent) => { - let obj = directive.value; - let clsArr = []; - let cls = dom.getProp('class'); - let model = module.getModel(dom.modelId); - if (nodom.Util.isString(cls) && !nodom.Util.isEmpty(cls)) { - clsArr = cls.trim().split(/\s+/); - } - nodom.Util.getOwnProps(obj).forEach(function (key) { - let r = obj[key]; - if (r instanceof nodom.Expression) { - r = r.val(model); - } - let ind = clsArr.indexOf(key); - if (!r || r === 'false') { - if (ind !== -1) { - clsArr.splice(ind, 1); - } - } - else if (ind === -1) { - clsArr.push(key); - } - }); - dom.setProp('class', clsArr.join(' ')); - }); - nodom.DirectiveManager.addType('field', 10, (directive, dom) => { - dom.setProp('name', directive.value); - let type = dom.getProp('type') || 'text'; - let eventName = dom.tagName === 'input' && ['text', 'checkbox', 'radio'].includes(type) ? 'input' : 'change'; - if (!dom.hasProp('value') && ['text', 'number', 'date', 'datetime', 'datetime-local', 'month', 'week', 'time', 'email', 'password', 'search', 'tel', 'url', 'color', 'radio'].includes(type) - || dom.tagName === 'TEXTAREA') { - let field = directive.value; - dom.setProp('value', new nodom.Expression(field), true); - } - dom.addEvent(new nodom.NodomEvent(eventName, function (dom, model, module, e, el) { - if (!el) { - return; - } - let type = dom.getProp('type'); - let field = dom.getDirective('field').value; - let v = el.value; - if (type === 'checkbox') { - if (dom.getProp('yes-value') == v) { - v = dom.getProp('no-value'); - } - else { - v = dom.getProp('yes-value'); - } - } - else if (type === 'radio') { - if (!el.checked) { - v = undefined; - } - } - model.set(field, v); - if (type !== 'radio') { - dom.setProp('value', v); - el.value = v; - } - })); - }, (directive, dom, module, parent) => { - const type = dom.getProp('type'); - const tgname = dom.tagName.toLowerCase(); - const model = module.getModel(dom.modelId); - if (!model.data) { - return; - } - const dataValue = model.data[directive.value]; - let value = dom.getProp('value'); - if (type === 'radio') { - if (dataValue + '' === value) { - dom.assets.set('checked', true); - dom.setProp('checked', 'checked'); - } - else { - dom.assets.set('checked', false); - dom.delProp('checked'); - } - } - else if (type === 'checkbox') { - let yv = dom.getProp('yes-value'); - if (dataValue + '' === yv) { - dom.setProp('value', yv); - dom.assets.set('checked', true); - } - else { - dom.setProp('value', dom.getProp('no-value')); - dom.assets.set('checked', false); - } - } - else if (tgname === 'select') { - if (dataValue !== dom.getProp('value')) { - setTimeout(() => { - dom.setProp('value', dataValue); - dom.assets.set('value', dataValue); - nodom.Renderer.add(module); - }, 0); - } - } - else { - if (!dom.hasProp('value')) { - dom.assets.set('value', dataValue === undefined || dataValue === null ? '' : dataValue); - } - } - }); - nodom.DirectiveManager.addType('validity', 10, (directive, dom) => { - let ind, fn, method; - let value = directive.value; - if ((ind = value.indexOf('|')) !== -1) { - fn = value.substr(0, ind); - method = value.substr(ind + 1); - } - else { - fn = value; - } - directive.extra = { initEvent: false }; - directive.value = fn; - directive.params = { - enabled: false - }; - if (method) { - directive.params.method = method; - } - if (dom.children.length === 0) { - let vd1 = new nodom.Element(); - vd1.textContent = ''; - dom.add(vd1); - } - else { - dom.children.forEach((item) => { - if (item.children.length === 0) { - let vd1 = new nodom.Element(); - vd1.textContent = ' '; - item.add(vd1); - } - }); - } - }, (directive, dom, module, parent) => { - setTimeout(() => { - const el = module.getNode({ name: directive.value }); - if (!directive.extra.initEvent) { - directive.extra.initEvent = true; - el.addEventListener('focus', function () { - setTimeout(() => { directive.params.enabled = true; }, 0); - }); - el.addEventListener('blur', function () { - nodom.Renderer.add(module); - }); - } - }, 0); - if (!directive.params.enabled) { - dom.dontRender = true; - return; - } - const el = module.getNode({ name: directive.value }); - if (!el) { - return; - } - let chds = []; - dom.children.forEach((item) => { - if (item.tagName !== undefined && item.hasProp('rel')) { - chds.push(item); - } - }); - let resultArr = []; - if (directive.params.method) { - const foo = module.getMethod(directive.params.method); - if (nodom.Util.isFunction(foo)) { - let r = foo.call(module.model, el.value); - if (!r) { - resultArr.push('custom'); - } - } - } - let vld = el.validity; - if (!vld.valid) { - for (var o in vld) { - if (vld[o] === true) { - resultArr.push(o); - } - } - } - if (resultArr.length > 0) { - let vn = handle(resultArr); - if (chds.length === 0) { - setTip(dom, vn, el); - } - else { - for (let i = 0; i < chds.length; i++) { - let rel = chds[i].getProp('rel'); - if (rel === vn) { - setTip(chds[i], vn, el); - } - else { - chds[i].dontRender = true; - } - } - } - } - else { - dom.dontRender = true; - } - function setTip(vd, vn, el) { - let text = vd.children[0].textContent.trim(); - if (text === '') { - text = nodom.Util.compileStr(nodom.TipMsg.FormMsgs[vn], el.getAttribute(vn)); - } - vd.children[0].textContent = text; - } - function handle(arr) { - for (var i = 0; i < arr.length; i++) { - switch (arr[i]) { - case 'valueMissing': - return 'required'; - case 'typeMismatch': - return 'type'; - case 'tooLong': - return 'maxLength'; - case 'tooShort': - return 'minLength'; - case 'rangeUnderflow': - return 'min'; - case 'rangeOverflow': - return 'max'; - case 'patternMismatch': - return 'pattern'; - default: - return arr[i]; - } - } - } - }); - nodom.DirectiveManager.addType('route', 10, (directive, dom) => { - let value = directive.value; - if (nodom.Util.isEmpty(value)) { - return; - } - if (dom.tagName === 'A') { - dom.setProp('href', 'javascript:void(0)'); - } - if (typeof value === 'string' && /^\{\{.+\}\}$/.test(value)) { - value = new nodom.Expression(value.substring(2, value.length - 2)); - } - if (value instanceof nodom.Expression) { - dom.setProp('path', value, true); - directive.value = value; - } - else { - dom.setProp('path', value); - } - if (dom.hasProp('activename')) { - let an = dom.getProp('activename'); - dom.setProp('active', new nodom.Expression(an), true); - if (dom.hasProp('activeclass')) { - new nodom.Directive('class', "{" + dom.getProp('activeclass') + ":'" + an + "'}", dom); - } - } - dom.addEvent(new nodom.NodomEvent('click', (dom, model, module, e) => { - let path = dom.getProp('path'); - if (nodom.Util.isEmpty(path)) { - return; - } - nodom.Router.go(path); - })); - }, (directive, dom, module, parent) => { - let path = dom.getProp('path'); - let domArr = nodom.Router.activeDomMap.get(module.id); - if (!domArr) { - nodom.Router.activeDomMap.set(module.id, [dom.key]); - } - else { - if (!domArr.includes(dom.key)) { - domArr.push(dom.key); - } - } - if (!path || path === nodom.Router.currentPath) { - return; - } - if (dom.hasProp('active') && dom.getProp('active') && (!nodom.Router.currentPath || path.indexOf(nodom.Router.currentPath) === 0)) { - setTimeout(() => { nodom.Router.go(path); }, 0); - } - }); - nodom.DirectiveManager.addType('router', 10, (directive, dom) => { - dom.setProp('role', 'module'); - }, (directive, dom, module, parent) => { - nodom.Router.routerKeyMap.set(module.id, dom.key); - }); - nodom.DirectiveManager.addType('ignoreself', 10, (directive, dom) => { - dom.dontRenderSelf = true; - }, (directive, dom, module, parent) => { - }); -})(nodom || (nodom = {})); -var nodom; -(function (nodom) { - nodom.FilterManager.addType('date', (value, param) => { - if (nodom.Util.isEmpty(value)) { - return ''; - } - param = param.substr(1, param.length - 2); - return nodom.Util.formatDate(value, param); - }); - nodom.FilterManager.addType('currency', (value, sign) => { - if (isNaN(value)) { - return ''; - } - sign = sign || '¥'; - if (typeof value === 'string') { - value = parseFloat(value); - } - return sign + ((value * 100 + 0.5 | 0) / 100); - }); - nodom.FilterManager.addType('number', (value, param) => { - let digits = param || 0; - if (isNaN(value) || digits < 0) { - return ''; - } - if (typeof value === 'string') { - value = parseFloat(value); - } - let x = 1; - for (let i = 0; i < digits; i++) { - x *= 10; - } - return ((value * x + 0.5) | 0) / x; - }); - nodom.FilterManager.addType('tolowercase', (value) => { - if (nodom.Util.isEmpty(value)) { - return ''; - } - if (!nodom.Util.isString(value) || nodom.Util.isEmpty(value)) { - throw new nodom.NodomError('invoke1', nodom.TipMsg.TipWords['filter'] + ' tolowercase', '0', 'string'); - } - return value.toLowerCase(); - }); - nodom.FilterManager.addType('touppercase', (value) => { - if (nodom.Util.isEmpty(value)) { - return ''; - } - if (!nodom.Util.isString(value) || nodom.Util.isEmpty(value)) { - throw new nodom.NodomError('invoke1', nodom.TipMsg.TipWords['filter'] + ' touppercase', '0', 'string'); - } - return value.toUpperCase(); - }); - nodom.FilterManager.addType('orderby', function () { - let args = arguments; - let arr = args[0]; - let field = args[1]; - let odr = args[2] || 'asc'; - if (!nodom.Util.isArray(arr)) { - throw new nodom.NodomError('invoke1', nodom.TipMsg.TipWords['filter'] + ' orderby', '0', 'array'); - } - let ret = arr.concat([]); - if (field && nodom.Util.isObject(arr[0])) { - if (odr === 'asc') { - ret.sort((a, b) => a[field] >= b[field] ? 1 : -1); - } - else { - ret.sort((a, b) => a[field] <= b[field] ? 1 : -1); - } - } - else { - if (odr === 'asc') { - ret.sort((a, b) => a >= b ? 1 : -1); - } - else { - ret.sort((a, b) => a <= b ? 1 : -1); - } - } - return ret; - }); - nodom.FilterManager.addType('select', function () { - if (!nodom.Util.isArray(arguments[0])) { - throw new nodom.NodomError('invoke1', nodom.TipMsg.TipWords['filter'] + ' filter', '0', 'array'); - } - let params = new Array(); - for (let i = 0; i < arguments.length; i++) { - params.push(arguments[i]); - } - let handler = { - odd: function () { - let arr = arguments[0]; - let ret = []; - for (let i = 0; i < arr.length; i++) { - if (i % 2 === 1) { - ret.push(arr[i]); - } - } - return ret; - }, - even: function () { - let arr = arguments[0]; - let ret = []; - for (let i = 0; i < arr.length; i++) { - if (i % 2 === 0) { - ret.push(arr[i]); - } - } - return ret; - }, - range: function () { - let args = arguments; - let arr = args[0]; - let ret = []; - let first = args[1]; - let last = args[2]; - if (isNaN(first)) { - throw new nodom.NodomError('paramException', nodom.TipMsg.TipWords['filter'], 'filter range'); - } - if (!nodom.Util.isNumber(first)) { - first = parseInt(first); - } - if (isNaN(last)) { - throw new nodom.NodomError('paramException', nodom.TipMsg.TipWords['filter'], 'filter range'); - } - if (!nodom.Util.isNumber(last)) { - last = parseInt(last); - } - if (first > last) { - throw new nodom.NodomError('paramException', nodom.TipMsg.TipWords['filter'], 'filter range'); - } - return arr.slice(first, last + 1); - }, - index: function () { - let args = arguments; - let arr = args[0]; - if (!nodom.Util.isArray(args[0])) { - throw new nodom.NodomError('paramException', nodom.TipMsg.TipWords['filter'], 'filter index'); - } - let ret = []; - if (arr.length > 0) { - for (let i = 1; i < args.length; i++) { - if (isNaN(args[i])) { - continue; - } - let k = parseInt(args[i]); - if (k < arr.length) { - ret.push(arr[k]); - } - } - } - return ret; - }, - func: function (arr, param) { - if (!nodom.Util.isArray(arr) || nodom.Util.isEmpty(param)) { - throw new nodom.NodomError('paramException', nodom.TipMsg.TipWords['filter'], 'filter func'); - } - let foo = this.methodFactory.get(param); - if (nodom.Util.isFunction(foo)) { - return nodom.Util.apply(foo, this, [arr]); - } - return arr; - }, - value: function (arr, param) { - if (!nodom.Util.isArray(arr) || nodom.Util.isEmpty(param)) { - throw new nodom.NodomError('paramException', nodom.TipMsg.TipWords['filter'], 'filter value'); - } - if (nodom.Util.isObject(param)) { - let keys = nodom.Util.getOwnProps(param); - return arr.filter(function (item) { - for (let i = 0; i < keys.length; i++) { - let v = item[keys[i]]; - let v1 = param[keys[i]]; - if (v === undefined || v !== v1 || typeof v === 'string' && v.indexOf(v1) === -1) { - return false; - } - } - return true; - }); - } - else { - return arr.filter(function (item) { - let props = nodom.Util.getOwnProps(item); - for (let i = 0; i < props.length; i++) { - let v = item[props[i]]; - if (nodom.Util.isString(v) && v.indexOf(param) !== -1) { - return item; - } - } - }); - } - } - }; - let type; - if (nodom.Util.isString(params[1])) { - type = params[1].trim(); - if (handler.hasOwnProperty(type)) { - params.splice(1, 1); - } - else { - type = 'value'; - } - } - else { - type = 'value'; - } - if (type === 'range' || type === 'index' || type === 'func') { - if (params.length < 2) { - throw new nodom.NodomError('paramException', nodom.TipMsg.TipWords['filter']); - } - } - return nodom.Util.apply(handler[type], this, params); - }); -})(nodom || (nodom = {})); -var nodom; -(function (nodom) { - nodom.TipMsg = { - TipWords: {}, - ErrorMsgs: {}, - FormMsgs: {} - }; -})(nodom || (nodom = {})); -var nodom; -(function (nodom) { - nodom.TipMsg_zh = { - TipWords: { - application: "应用", - system: "系统", - module: "模块", - moduleClass: '模块类', - model: "模型", - directive: "指令", - directiveType: "指令类型", - expression: "表达式", - event: "事件", - method: "方法", - filter: "过滤器", - filterType: "过滤器类型", - data: "数据", - dataItem: '数据项', - route: '路由', - routeView: '路由容器', - plugin: '插件', - resource: '资源', - root: '根', - element: '元素' - }, - ErrorMsgs: { - unknown: "未知错误", - paramException: "{0}'{1}'方法参数错误,请参考api", - invoke: "{0}方法调用参数{1}必须为{2}", - invoke1: "{0}方法调用参数{1}必须为{2}或{3}", - invoke2: "{0}方法调用参数{1}或{2}必须为{3}", - invoke3: "{0}方法调用参数{1}不能为空", - exist: "{0}已存在", - exist1: "{0}'{1}'已存在", - notexist: "{0}不存在", - notexist1: "{0}'{1}'不存在", - notupd: "{0}不可修改", - notremove: "{0}不可删除", - notremove1: "{0}{1}不可删除", - namedinvalid: "{0}{1}命名错误,请参考用户手册对应命名规范", - initial: "{0}初始化参数错误", - jsonparse: "JSON解析错误", - timeout: "请求超时", - config: "{0}配置参数错误", - config1: "{0}配置参数'{1}'错误" - }, - FormMsgs: { - type: "请输入有效的{0}", - unknown: "输入错误", - required: "不能为空", - min: "最小输入值为{0}", - max: "最大输入值为{0}" - } - }; -})(nodom || (nodom = {})); -var nodom; -(function (nodom) { - nodom.TipMsg_en = { - TipWords: { - application: "Application", - system: "System", - module: "Module", - moduleClass: 'ModuleClass', - model: "Model", - directive: "Directive", - directiveType: "Directive-type", - expression: "Expression", - event: "Event", - method: "Method", - filter: "Filter", - filterType: "Filter-type", - data: "Data", - dataItem: 'Data-item', - route: 'Route', - routeView: 'Route-container', - plugin: 'Plugin', - resource: 'Resource', - root: 'Root', - element: 'Element' - }, - ErrorMsgs: { - unknown: "unknown error", - paramException: "{0} '{1}' parameter error,see api", - invoke: "method {0} parameter {1} must be {2}", - invoke1: "method {0} parameter {1} must be {2} or {3}", - invoke2: "method {0} parameter {1} or {2} must be {3}", - invoke3: "method {0} parameter {1} not allowed empty", - exist: "{0} is already exist", - exist1: "{0} '{1}' is already exist", - notexist: "{0} is not exist", - notexist1: "{0} '{1}' is not exist", - notupd: "{0} not allow to change", - notremove: "{0} not allow to delete", - notremove1: "{0} {1} not allow to delete", - namedinvalid: "{0} {1} name error,see name rules", - initial: "{0} init parameter error", - jsonparse: "JSON parse error", - timeout: "request overtime", - config: "{0} config parameter error", - config1: "{0} config parameter '{1}' error" - }, - FormMsgs: { - type: "please input valid {0}", - unknown: "input error", - required: "is required", - min: "min value is {0}", - max: "max value is {0}" - } - }; -})(nodom || (nodom = {})); -var nodom; -(function (nodom) { - class Plugin { - constructor(params) { - } - beforeRender(module, uidom) { - this.element = uidom; - this.moduleId = module.id; - if (!this.modelId || uidom.key !== this.key) { - this.key = uidom.key; - this.modelId = uidom.modelId; - if (uidom.hasProp('name')) { - module.addPlugin(uidom.getProp('name'), this); - } - this.needPreRender = true; - } - else { - this.needPreRender = false; - } - } - afterRender(module, uidom) { } - clone(dst) { - let plugin = Reflect.construct(this.constructor, []); - let excludeProps = ['key', 'element', 'modelId', 'moduleId']; - nodom.Util.getOwnProps(this).forEach((prop) => { - if (excludeProps.includes(prop)) { - return; - } - plugin[prop] = nodom.Util.clone(this[prop]); - }); - if (dst) { - plugin.element = dst; - } - return plugin; - } - getModel() { - let module = nodom.ModuleFactory.get(this.moduleId); - if (!module) { - return null; - } - let model = module.getModel(this.modelId); - return model ? model : null; - } - } - nodom.Plugin = Plugin; -})(nodom || (nodom = {})); -var nodom; -(function (nodom) { - let PluginManager = (() => { - class PluginManager { - static add(name, cfg) { - if (this.plugins.has(name)) { - throw new nodom.NodomError('exist1', nodom.TipMsg.TipWords['element'], name); - } - this.plugins.set(name, cfg); - } - static get(tagName) { - return this.plugins.get(tagName); - } - } - PluginManager.plugins = new Map(); - return PluginManager; - })(); - nodom.PluginManager = PluginManager; -})(nodom || (nodom = {})); \ No newline at end of file diff --git a/test/pages/js/nodomui.js b/test/pages/js/nodomui.js deleted file mode 100644 index d3ba4284f764aee76eabbc5c4dd5094d5f32dcc0..0000000000000000000000000000000000000000 --- a/test/pages/js/nodomui.js +++ /dev/null @@ -1,3559 +0,0 @@ -const NUITipWords = { - uploading: '上传中...', - total: '共', - record: '条', - NO: '第', - page: '页', - weekday: { - sunday: '日', - monday: '一', - tuesday: '二', - wednesday: '三', - thursday: '四', - friday: '五', - saturday: '六' - }, - buttons: { - ok: '确定', - cancel: '取消', - close: '关闭', - yes: '是', - no: '否', - today: '今天', - now: '此时' - } -}; -document.oncontextmenu = function (e) { - e.preventDefault(); -}; -class UITool { - static clearSpace(src) { - if (src && typeof src === 'string') { - return src.replace(/\s+/g, ''); - } - } - static adjustPosAndSize(module, key, x, y, distance, bodyHeight, changeSize) { - let el = module.container.querySelector("[key='" + key + "']"); - if (!el) { - setTimeout(() => { - UITool.adjustPosAndSize(module, key, x, y, distance, document.body.scrollHeight, changeSize); - }, 0); - } - else { - let scTop = document.documentElement.scrollTop || document.body.scrollTop; - y += scTop; - let height = bodyHeight > window.innerHeight ? bodyHeight : window.innerHeight; - if (changeSize) { - el.style.maxHeight = (window.innerHeight - 50) + 'px'; - } - if (y + el.offsetHeight > height && y > el.offsetHeight + distance) { - el.style.transform = 'translate(0,' + -(el.offsetHeight + distance) + 'px)'; - } - else { - el.style.transform = 'translate(0,0)'; - } - } - } - static handleUIParam(dom, defDom, paramArr, props, defaultValues) { - let error = false; - for (let i = 0; i < paramArr.length; i++) { - let pName = props[i]; - let p = paramArr[i]; - let type; - let pa; - if (p.includes('|')) { - pa = p.split('|'); - p = pa[0]; - type = pa[1]; - } - let v = dom.getProp(p); - if (v) { - v = this.clearSpace(v); - if (v !== '') { - switch (type) { - case 'number': - if (!nodom.Util.isNumberString(v)) { - error = true; - } - else { - defDom[pName] = parseInt(v); - } - break; - case 'array': - let va = v.split(','); - if (pa.length === 3) { - if (nodom.Util.isNumberString(pa[2])) { - if (parseInt(pa[2]) > va.length) { - error = true; - } - } - else { - if (pa[2] === 'number') { - for (let i = 0; i < va.length; i++) { - let v1 = va[i]; - if (!nodom.Util.isNumberString(v1)) { - error = true; - break; - } - va[i] = parseInt(v1); - } - } - } - } - if (!error) { - defDom[pName] = va; - } - break; - case 'bool': - if (v === 'true') { - defDom[pName] = true; - } - break; - default: - defDom[pName] = v; - } - } - } - if (!v || v === '') { - if (defaultValues && defaultValues[i] !== null) { - defDom[pName] = defaultValues[i]; - } - else { - if (type === 'bool') { - if (dom.hasProp(p)) { - defDom[pName] = true; - } - else { - defDom[pName] = false; - } - } - else { - error = true; - } - } - } - dom.delProp(p); - if (error) { - throw new nodom.NodomError('config1', defDom.tagName, p); - } - } - } -} -class UIEventRegister { - static addEvent(eventName, moduleId, domKey, handler) { - if (!this.listeners.has(eventName)) { - this.listeners.set(eventName, []); - window.addEventListener(eventName, (e) => { - let target = e.target; - let key = target.getAttribute('key'); - let evts = this.listeners.get(eventName); - for (let evt of evts) { - let module = nodom.ModuleFactory.get(evt.module); - let dom = module.renderTree.query(evt.dom); - if (!dom) { - continue; - } - let inOrOut = dom.key === key || dom.query(key) ? true : false; - if (typeof evt.handler === 'function') { - evt.handler.apply(dom, [module, dom, inOrOut, e]); - } - } - }, false); - } - let arr = this.listeners.get(eventName); - let find = arr.find(item => item.dom === domKey); - if (find) { - return; - } - arr.push({ - module: moduleId, - dom: domKey, - handler: handler - }); - } -} -UIEventRegister.listeners = new Map(); -function request(cfg) { - return nodom.request(cfg); -} -class UIAccordion extends nodom.Plugin { - constructor(params) { - super(params); - this.tagName = 'UI-ACCORDION'; - let rootDom = new nodom.Element(); - if (params) { - if (params instanceof HTMLElement) { - nodom.Compiler.handleAttributes(rootDom, params); - nodom.Compiler.handleChildren(rootDom, params); - } - else if (typeof params === 'object') { - for (let o in params) { - if (o === 'children') { - if (Array.isArray(params[o])) { - for (let c of params[o]) { - if (typeof c !== 'object') { - continue; - } - let d = new nodom.Element(c.tagName || 'div'); - for (let p in c) { - if (p === 'tagName') { - continue; - } - d.setProp(p, c[p]); - } - rootDom.add(d); - } - } - } - else { - this[o] = params[o]; - } - } - } - this.generate(rootDom); - } - rootDom.tagName = 'div'; - rootDom.plugin = this; - this.element = rootDom; - } - generate(rootDom) { - rootDom.addClass('nd-accordion'); - let firstDom = new nodom.Element(); - let secondDom = new nodom.Element(); - firstDom.tagName = 'DIV'; - secondDom.tagName = 'DIV'; - firstDom.addClass('nd-accordion-item'); - let activeName1; - let activeName2; - for (let i = 0; i < rootDom.children.length; i++) { - let item = rootDom.children[i]; - if (!item.tagName) { - continue; - } - if (item.hasProp('first')) { - firstDom.addDirective(new nodom.Directive('repeat', item.getProp('data'), firstDom), true); - item.addClass('nd-accordion-first'); - let methodId = '$nodomGenMethod' + nodom.Util.genId(); - item.addEvent(new nodom.NodomEvent('click', methodId + ':delg')); - this.method1 = methodId; - activeName1 = item.getProp('activename') || 'active'; - this.active1 = activeName1; - firstDom.add(item); - let span = new nodom.Element('span'); - span.children = item.children; - item.children = [span]; - if (item.hasProp('icon')) { - span.addClass('nd-icon-' + item.getProp('icon')); - } - this.field1 = item.getProp('data'); - let icon = new nodom.Element('b'); - icon.addClass('nd-accordion-icon nd-icon-right'); - icon.directives.push(new nodom.Directive('class', "{'nd-accordion-open':'" + activeName1 + "'}", icon)); - item.add(icon); - item.delProp(['activename', 'first']); - } - else if (item.hasProp('second')) { - activeName2 = item.getProp('activename') || 'active'; - this.active2 = activeName2; - item.addDirective(new nodom.Directive('repeat', item.getProp('data'), item)); - this.field2 = item.getProp('data'); - item.addClass('nd-accordion-second'); - if (item.hasProp('itemclick')) { - item.addEvent(new nodom.NodomEvent('click', item.getProp('itemclick') + ':delg')); - } - item.addDirective(new nodom.Directive('class', "{'nd-accordion-selected':'" + activeName2 + "'}", item)); - secondDom.addClass('nd-accordion-secondct'); - secondDom.add(item); - secondDom.addDirective(new nodom.Directive('class', "{'nd-accordion-hide':'!" + activeName1 + "'}", secondDom), true); - } - item.delProp(['data', 'second']); - } - firstDom.add(secondDom); - rootDom.children = [firstDom]; - } - beforeRender(module, uidom) { - const me = this; - super.beforeRender(module, uidom); - if (this.needPreRender) { - module.methodFactory.add(this.method1, (dom, model, module, e) => { - let pmodel = module.modelFactory.get(uidom.modelId); - let data = pmodel.data[me.field1]; - let f = me.active1; - for (let d of data) { - if (d[f] === true) { - d[f] = false; - } - } - model.set(f, true); - }); - module.methodFactory.add(this.method2, (dom, model, module, e) => { - let pmodel = module.modelFactory.get(uidom.modelId); - let data = pmodel.data[me.field1]; - let f = me.active2; - for (let d of data) { - for (let d1 of d[me.field2]) { - if (d1[f] === true) { - d1[f] = false; - } - } - } - model.set(f, true); - }); - } - } -} -nodom.PluginManager.add('UI-ACCORDION', UIAccordion); -class UIButton extends nodom.Plugin { - constructor(params) { - super(params); - this.tagName = 'UI-BUTTON'; - let rootDom = new nodom.Element(); - if (params) { - if (params instanceof HTMLElement) { - nodom.Compiler.handleAttributes(rootDom, params); - nodom.Compiler.handleChildren(rootDom, params); - UITool.handleUIParam(rootDom, this, ['size', 'icon', 'iconpos', 'theme', 'nobg|bool'], ['size', 'icon', 'iconPos', 'theme', 'nobg'], ['normal', '', 'left', '', null]); - this.text = params.innerHTML.trim(); - } - else if (typeof params === 'object') { - for (let o in params) { - this[o] = params[o]; - } - } - this.generate(rootDom); - } - rootDom.tagName = 'button'; - rootDom.plugin = this; - this.element = rootDom; - } - generate(rootDom) { - let clsArr = ['nd-btn']; - clsArr.push('nd-btn-' + this.size); - if (this.icon !== '') { - clsArr.push('nd-btn-' + this.iconPos); - } - if (this.nobg) { - clsArr.push('nd-btn-nobg'); - } - else if (this.theme !== '') { - clsArr.push('nd-btn-' + this.theme); - } - if (this.text === '') { - clsArr.push('nd-btn-notext'); - } - rootDom.addClass(clsArr.join(' ')); - let txt = new nodom.Element(); - txt.textContent = this.text; - let children = [txt]; - if (this.icon !== '') { - let img = new nodom.Element('b'); - img.addClass('nd-icon-' + this.icon); - switch (this.iconPos) { - case 'left': - children.unshift(img); - break; - case 'top': - children.unshift(img); - img.addClass('nd-btn-vert'); - break; - case 'right': - children.push(img); - break; - case 'bottom': - children.push(img); - img.addClass('nd-btn-vert'); - break; - } - } - rootDom.children = children; - } -} -nodom.PluginManager.add('UI-BUTTON', UIButton); -class UIButtonGroup extends nodom.Plugin { - constructor(params) { - super(params); - this.tagName = 'UI-BUTTONGROUP'; - let rootDom = new nodom.Element(); - if (params) { - if (params instanceof HTMLElement) { - nodom.Compiler.handleAttributes(rootDom, params); - nodom.Compiler.handleChildren(rootDom, params); - } - else if (typeof params === 'object') { - for (let o in params) { - if (o === 'children') { - if (Array.isArray(params[o])) { - for (let c of params[o]) { - if (typeof c !== 'object') { - continue; - } - rootDom.add(new UIButton(c).element); - } - } - } - else { - this[o] = params[o]; - } - } - } - } - rootDom.addClass('nd-buttongroup'); - rootDom.tagName = 'div'; - rootDom.plugin = this; - this.element = rootDom; - } -} -nodom.PluginManager.add('UI-BUTTONGROUP', UIButtonGroup); -class UICheckbox extends nodom.Plugin { - constructor(params) { - super(params); - this.tagName = 'UI-CHECKBOX'; - let rootDom = new nodom.Element(); - if (params) { - if (params instanceof HTMLElement) { - nodom.Compiler.handleAttributes(rootDom, params); - nodom.Compiler.handleChildren(rootDom, params); - UITool.handleUIParam(rootDom, this, ['yesvalue', 'novalue'], ['yesValue', 'noValue'], ['true', 'false']); - } - else if (typeof params === 'object') { - for (let o in params) { - this[o] = params[o]; - } - } - this.generate(rootDom); - } - rootDom.tagName = 'span'; - rootDom.plugin = this; - this.element = rootDom; - } - generate(rootDom) { - const me = this; - let field = rootDom.getDirective('field'); - if (field) { - this.dataName = field.value; - rootDom.removeDirectives(['field']); - } - let icon = new nodom.Element('b'); - icon.addClass('nd-checkbox-uncheck'); - icon.addDirective(new nodom.Directive('class', "{'nd-checkbox-checked':'" + this.dataName + "==\"" + this.yesValue + "\"'}", icon)); - rootDom.children.unshift(icon); - rootDom.addEvent(new nodom.NodomEvent('click', (dom, model, module) => { - let v = model.data[me.dataName]; - if (v == me.yesValue) { - model.set(me.dataName, me.noValue); - } - else { - model.set(me.dataName, me.yesValue); - } - })); - } -} -nodom.PluginManager.add('UI-CHECKBOX', UICheckbox); -class UIDatetime extends nodom.Plugin { - constructor(params) { - super(params); - this.tagName = 'UI-DATETIME'; - let rootDom = new nodom.Element(); - if (params) { - if (params instanceof HTMLElement) { - nodom.Compiler.handleAttributes(rootDom, params); - nodom.Compiler.handleChildren(rootDom, params); - UITool.handleUIParam(rootDom, this, ['type'], ['type'], ['date']); - } - else if (typeof params === 'object') { - for (let o in params) { - this[o] = params[o]; - } - } - this.generate(rootDom); - } - rootDom.tagName = 'div'; - rootDom.plugin = this; - this.element = rootDom; - } - generate(rootDom) { - let me = this; - rootDom.addClass('nd-datetime'); - let fieldDom = new nodom.Element('div'); - fieldDom.addClass('nd-datetime-field'); - let dateIco = new nodom.Element('b'); - dateIco.addClass(this.type === 'time' ? 'nd-datetime-time' : 'nd-datetime-date'); - let directive = rootDom.getDirective('field'); - if (directive) { - this.dataName = directive.value; - rootDom.removeDirectives(['field']); - } - let input = new nodom.Element('input'); - if (this.dataName) { - input.addDirective(new nodom.Directive('field', this.dataName, input)); - input.setProp('value', new nodom.Expression(this.dataName), true); - } - fieldDom.add(input); - fieldDom.add(dateIco); - fieldDom.addEvent(new nodom.NodomEvent('click', (dom, model, module, e, el) => { - me.showPicker(dom, model, module, e, el); - })); - this.extraDataName = '$ui_datetime_' + nodom.Util.genId(); - let pickerDom = new nodom.Element('div'); - pickerDom.addClass('nd-datetime-picker'); - pickerDom.addDirective(new nodom.Directive('model', this.extraDataName, pickerDom)); - pickerDom.addDirective(new nodom.Directive('show', 'show', pickerDom)); - let tblCt = new nodom.Element('div'); - tblCt.addClass('nd-datetime-tbl'); - pickerDom.add(tblCt); - if (this.type === 'date' || this.type === 'datetime') { - tblCt.add(this.genDatePicker()); - } - if (this.type === 'time' || this.type === 'datetime') { - tblCt.add(this.genTimePicker()); - } - let btnCt = new nodom.Element('div'); - btnCt.addClass('nd-datetime-btnct'); - if (this.type === 'date') { - let btnToday = new nodom.Element('button'); - btnToday.assets.set('innerHTML', NUITipWords.buttons.today); - btnToday.addEvent(new nodom.NodomEvent('click', (dom, model, module, e) => { - e.preventDefault(); - let nda = new Date(); - me.setValue(module, nda.getFullYear() + '-' + (nda.getMonth() + 1) + '-' + nda.getDate()); - })); - btnCt.add(btnToday); - } - else if (this.type === 'datetime' || this.type === 'time') { - let btn = new nodom.Element('button'); - btn.assets.set('innerHTML', NUITipWords.buttons.now); - btn.addEvent(new nodom.NodomEvent('click', (dom, model, module, e) => { - e.preventDefault(); - let nda = new Date(); - me.setValue(module, nda.getFullYear() + '-' + (nda.getMonth() + 1) + '-' + nda.getDate() + ' ' - + nda.getHours() + ':' + nda.getMinutes() + ':' + nda.getSeconds()); - })); - btnCt.add(btn); - } - let btnOk = new nodom.Element('button'); - btnOk.addClass('nd-btn-active'); - btnOk.assets.set('innerHTML', NUITipWords.buttons.ok); - btnCt.add(btnOk); - btnOk.addEvent(new nodom.NodomEvent('click', (dom, model, module, e) => { - e.preventDefault(); - model.set('show', false); - let pmodel = module.modelFactory.get(me.modelId); - pmodel.set(this.dataName, me.genValueStr()); - })); - pickerDom.add(btnCt); - rootDom.children = [fieldDom, pickerDom]; - } - beforeRender(module, uidom) { - let me = this; - super.beforeRender(module, uidom); - this.listKey = uidom.children[1].key; - let model = module.modelFactory.get(uidom.modelId); - if (this.needPreRender) { - model.set(this.extraDataName, { - show: false, - year: 2020, - month: 1, - date: 1, - hour: 0, - minute: 0, - second: 0, - time: '00:00:00', - days: [] - }); - this.pickerModelId = model.get(this.extraDataName).id; - if (this.type === 'date') { - this.genDates(module); - } - else if (this.type === 'time') { - this.genTimes(module); - } - else { - this.genDates(module); - this.genTimes(module); - } - UIEventRegister.addEvent('click', module.id, uidom.children[1].key, (module, dom, inOrOut, e) => { - if (!inOrOut) { - model.query(me.extraDataName).show = false; - } - }); - } - else { - this.pickerModelId = model.get(this.extraDataName).id; - } - } - genDatePicker() { - let me = this; - let pickerDom = new nodom.Element('div'); - pickerDom.addClass('nd-datetime-datetbl'); - let ymDom = new nodom.Element('div'); - ymDom.addClass('nd-datetime-ymct'); - pickerDom.add(ymDom); - let leftDom1 = new nodom.Element('b'); - leftDom1.addClass('nd-datetime-leftarrow1'); - let leftDom = new nodom.Element('b'); - leftDom.addClass('nd-datetime-leftarrow'); - let rightDom = new nodom.Element('b'); - rightDom.addClass('nd-datetime-rightarrow'); - let rightDom1 = new nodom.Element('b'); - rightDom1.addClass('nd-datetime-rightarrow1'); - let contentDom = new nodom.Element('span'); - contentDom.addClass('nd-datetime-ym'); - let txtDom = new nodom.Element(); - txtDom.expressions = [new nodom.Expression('year'), '/', new nodom.Expression('month')]; - contentDom.add(txtDom); - leftDom1.addEvent(new nodom.NodomEvent('click', (dom, model, module) => { - me.changeMonth(module, -12); - })); - leftDom.addEvent(new nodom.NodomEvent('click', (dom, model, module) => { - me.changeMonth(module, -1); - })); - rightDom.addEvent(new nodom.NodomEvent('click', (dom, model, module) => { - me.changeMonth(module, 1); - })); - rightDom1.addEvent(new nodom.NodomEvent('click', (dom, model, module) => { - me.changeMonth(module, 12); - })); - ymDom.children = [leftDom1, leftDom, contentDom, rightDom, rightDom1]; - let weekDom = new nodom.Element('div'); - weekDom.addClass('nd-datetime-weekdays'); - let days = Object.getOwnPropertyNames(NUITipWords.weekday); - for (let d of days) { - let span = new nodom.Element('span'); - let txt = new nodom.Element(); - txt.textContent = NUITipWords.weekday[d]; - span.add(txt); - weekDom.add(span); - } - pickerDom.add(weekDom); - let dateDom = new nodom.Element('div'); - dateDom.addClass('nd-datetime-dates'); - let daySpan = new nodom.Element('span'); - daySpan.addDirective(new nodom.Directive('repeat', 'days', daySpan)); - daySpan.addDirective(new nodom.Directive('class', "{'nd-datetime-today':'today','nd-datetime-disable':'disable','nd-datetime-selected':'selected'}", daySpan)); - let txt = new nodom.Element(); - txt.expressions = [new nodom.Expression('date')]; - daySpan.add(txt); - daySpan.addEvent(new nodom.NodomEvent('click', ':delg', (dom, model, module) => { - let data = model.data; - if (data.disable) { - return; - } - me.selectDate(module, model); - })); - dateDom.add(daySpan); - pickerDom.add(dateDom); - return pickerDom; - } - genTimePicker() { - let me = this; - let pickerDom = new nodom.Element('div'); - pickerDom.addClass('nd-datetime-timetbl'); - let showDom = new nodom.Element('input'); - showDom.addClass('nd-datetime-timeinput'); - showDom.setProp('value', new nodom.Expression('time'), true); - pickerDom.add(showDom); - let itemCt = new nodom.Element('div'); - itemCt.addClass('nd-datetime-timect'); - pickerDom.add(itemCt); - let hourDom = new nodom.Element('div'); - let item = new nodom.Element('div'); - item.addClass('nd-datetime-timeitem'); - item.addDirective(new nodom.Directive('repeat', 'hours', item)); - item.addDirective(new nodom.Directive('class', "{'nd-datetime-itemselect':'selected'}", item)); - let txt = new nodom.Element(); - txt.expressions = [new nodom.Expression('v')]; - item.setProp('role', 'hour'); - item.add(txt); - hourDom.add(item); - item.addEvent(new nodom.NodomEvent('click', ':delg', (dom, model, module, e, el) => { - me.selectTime(module, dom, model); - })); - let minuteDom = hourDom.clone(true); - let secondDom = hourDom.clone(true); - minuteDom.children[0].getDirective('repeat').value = 'minutes'; - minuteDom.children[0].setProp('role', 'minute'); - secondDom.children[0].getDirective('repeat').value = 'seconds'; - secondDom.children[0].setProp('role', 'second'); - itemCt.children = [hourDom, minuteDom, secondDom]; - return pickerDom; - } - genDates(module, year, month) { - let cda = new Date(); - let cy = cda.getFullYear(); - let cm = cda.getMonth() + 1; - let cd = cda.getDate(); - if (!year || !month) { - year = cy; - month = cm; - } - let days = this.cacMonthDays(year, month); - let dayArr = []; - let date = new Date(year + '-' + month + '-1'); - let wd = date.getDay(); - let lastMonthDays = this.cacMonthDays(year, month, -1); - for (let d = lastMonthDays, i = 0; i < wd; i++, d--) { - dayArr.unshift({ - disable: true, - selected: false, - date: d - }); - } - for (let i = 1; i <= days; i++) { - dayArr.push({ - date: i, - selected: this.year === year && this.month === month && this.date === i, - today: cy === year && cm === month && cd === i - }); - } - date = new Date(year + '-' + month + '-' + days); - wd = date.getDay(); - for (let i = wd + 1; i <= 6; i++) { - dayArr.push({ - disable: true, - selected: false, - date: i - wd - }); - } - let model = module.modelFactory.get(this.pickerModelId); - model.set('year', year); - model.set('month', month); - model.set('days', dayArr); - } - genTimes(module) { - let model = module.modelFactory.get(this.pickerModelId); - let hours = []; - let minutes = []; - let seconds = []; - for (let i = 0; i < 60; i++) { - let selected = i === 0 ? true : false; - if (i < 24) { - hours.push({ - v: i < 10 ? '0' + i : i, - selected: selected, - }); - } - minutes.push({ - v: i < 10 ? '0' + i : i, - selected: selected - }); - seconds.push({ - v: i < 10 ? '0' + i : i, - selected: selected - }); - } - model.set('hours', hours); - model.set('minutes', minutes); - model.set('seconds', seconds); - } - cacMonthDays(year, month, disMonth) { - if (disMonth) { - month += disMonth; - } - if (month <= 0) { - year--; - month += 12; - } - else if (month > 12) { - year++; - month -= 12; - } - if ([1, 3, 5, 7, 8, 10, 12].includes(month)) { - return 31; - } - else if (month !== 2) { - return 30; - } - else if (year % 400 === 0 || year % 4 === 0 && year % 100 !== 0) { - return 29; - } - else { - return 28; - } - } - changeMonth(module, distance) { - let model = module.modelFactory.get(this.pickerModelId); - let year = model.query('year'); - let month = model.query('month'); - month += distance; - if (month <= 0) { - year--; - month += 12; - } - else if (month > 12) { - year++; - month -= 12; - } - if (month <= 0) { - year--; - month += 12; - } - else if (month > 12) { - year++; - month -= 12; - } - this.genDates(module, year, month); - } - setValue(module, str) { - if (str && str !== '') { - str = str.trim(); - if (str === '') { - return; - } - let model = module.modelFactory.get(this.modelId); - let model1 = module.modelFactory.get(this.pickerModelId); - if (this.type === 'date' || this.type === 'datetime') { - let date = new Date(str); - if (date.toTimeString() !== 'Invalid Date') { - this.year = date.getFullYear(); - this.month = date.getMonth() + 1; - this.date = date.getDate(); - this.genDates(module, this.year, this.month); - if (this.type === 'datetime') { - this.hour = date.getHours(); - this.minute = date.getMinutes(); - this.second = date.getSeconds(); - model1.set('time', this.genValueStr('time')); - this.setTimeSelect(module); - } - } - else { - model.set(this.dataName, this.genValueStr()); - } - } - else if (this.type === 'time') { - if (/^\d{1,2}:\d{1,2}(:\d{1,2})?$/.test(str)) { - let sa = str.split(':'); - this.hour = parseInt(sa[0]); - this.minute = parseInt(sa[1]); - this.second = sa.length > 2 ? parseInt(sa[2]) : 0; - model1.set('time', this.genValueStr('time')); - this.setTimeSelect(module); - } - } - } - } - selectDate(module, model) { - let pmodel = module.modelFactory.get(this.pickerModelId); - if (pmodel) { - let days = pmodel.query('days'); - for (let d of days) { - if (d.selected) { - d.selected = false; - break; - } - } - this.year = pmodel.query('year'); - this.month = pmodel.query('month'); - } - if (model) { - model.set('selected', true); - this.date = model.query('date'); - } - } - selectTime(module, dom, model) { - let pmodel = module.modelFactory.get(this.pickerModelId); - let role = dom.getProp('role'); - if (pmodel) { - let datas = pmodel.query(role + 's'); - for (let d of datas) { - if (d.selected) { - d.selected = false; - break; - } - } - } - if (!model) { - model = module.modelFactory.get(dom.modelId); - } - if (model) { - model.set('selected', true); - } - this[role] = parseInt(model.query('v')); - pmodel.set('time', this.genValueStr('time')); - } - showPicker(dom, model, module, e, el) { - let data = model.query(this.extraDataName); - if (data) { - if (data.show) { - return; - } - data.show = true; - } - let pDom = dom.tagName === 'input' ? dom.getParent(module) : dom; - this.setValue(module, model.query(this.dataName)); - model.set('show', true); - let height = el.offsetHeight; - let y = e.clientY + el.offsetHeight - e.offsetY; - UITool.adjustPosAndSize(module, this.listKey, e.clientX, y, height, null, false); - } - setTimeSelect(module) { - let me = this; - let model = module.modelFactory.get(this.pickerModelId); - let data = [this.hour, this.minute, this.second]; - ['hours', 'minutes', 'seconds'].forEach((item, i) => { - let datas = model.query(item); - for (let d of datas) { - if (d.selected) { - d.selected = false; - break; - } - } - datas[data[i]].selected = true; - }); - setTimeout(scroll, 0); - function scroll() { - let uidom = me.element; - let timeCt; - if (uidom.children.length === 1) { - setTimeout(scroll, 0); - return; - } - if (me.type === 'datetime') { - timeCt = uidom.children[1].children[0].children[1].children[1]; - } - else if (me.type === 'time') { - timeCt = uidom.children[1].children[0].children[0].children[1]; - } - data.forEach((item, i) => { - let el = module.container.querySelector("[key='" + timeCt.children[i].key + "']"); - el.scrollTo(0, data[i] * 30); - }); - } - } - genValueStr(type) { - if (!this.year) { - this.year = 2020; - } - if (!this.month) { - this.month = 1; - } - if (!this.date) { - this.date = 1; - } - if (!this.hour) { - this.hour = 0; - } - if (!this.minute) { - this.minute = 0; - } - if (!this.second) { - this.second = 0; - } - switch (type || this.type) { - case 'datetime': - return [this.year, this.month < 10 ? '0' + this.month : this.month, this.date < 10 ? '0' + this.date : this.date].join('-') + - ' ' + - [this.hour < 10 ? '0' + this.hour : this.hour, this.minute < 10 ? '0' + this.minute : this.minute, this.second < 10 ? '0' + this.second : this.second].join(':'); - case 'time': - return [this.hour < 10 ? '0' + this.hour : this.hour, this.minute < 10 ? '0' + this.minute : this.minute, this.second < 10 ? '0' + this.second : this.second].join(':'); - default: - return [this.year, this.month < 10 ? '0' + this.month : this.month, this.date < 10 ? '0' + this.date : this.date].join('-'); - } - } -} -nodom.PluginManager.add('UI-DATETIME', UIDatetime); -class UIDialog extends nodom.Plugin { - constructor(params) { - super(params); - this.tagName = 'UI-DIALOG'; - let rootDom = new nodom.Element(); - if (params) { - let panel = new UIPanel(params); - this.generate(rootDom, panel); - } - rootDom.tagName = 'div'; - rootDom.plugin = this; - this.element = rootDom; - } - generate(rootDom, panel) { - const me = this; - this.dataName = '$ui_dialog_' + nodom.Util.genId(); - rootDom.addClass('nd-dialog'); - let panelDom = panel.element; - rootDom.setProp('name', panelDom.getProp('name')); - this.autoOpen = panelDom.hasProp('autoopen'); - this.onClose = panelDom.getProp('onclose'); - this.onOpen = panelDom.getProp('onopen'); - panelDom.delProp(['name', 'autoopen']); - panel.addHeadBtn('close', () => { - me.close(); - }); - rootDom.addDirective(new nodom.Directive('show', this.dataName, rootDom)); - let dialogBody = new nodom.Element('div'); - dialogBody.addClass('nd-dialog-body'); - dialogBody.add(panelDom); - let coverDom = new nodom.Element('div'); - coverDom.addClass('nd-dialog-cover'); - rootDom.add(coverDom); - rootDom.add(dialogBody); - } - beforeRender(module, dom) { - super.beforeRender(module, dom); - if (this.needPreRender) { - if (this.autoOpen) { - this.open(); - } - } - } - open() { - let module = nodom.ModuleFactory.get(this.moduleId); - if (module) { - let model = module.modelFactory.get(this.modelId); - if (model) { - model.set(this.dataName, true); - } - if (this.onOpen) { - let foo = module.methodFactory.get(this.onOpen); - if (foo) { - nodom.Util.apply(foo, model, [model, module]); - } - } - } - } - close() { - let module = nodom.ModuleFactory.get(this.moduleId); - if (module) { - let model = module.modelFactory.get(this.modelId); - if (model) { - model.set(this.dataName, false); - } - if (this.onClose) { - let foo = module.methodFactory.get(this.onClose); - if (foo) { - nodom.Util.apply(foo, model, [model, module]); - } - } - } - } -} -nodom.PluginManager.add('UI-DIALOG', UIDialog); -class UIFile extends nodom.Plugin { - constructor(params) { - super(params); - this.tagName = 'UI-FILE'; - this.state = 0; - this.maxCount = 1; - this.count = 0; - let rootDom = new nodom.Element(); - if (params) { - if (params instanceof HTMLElement) { - nodom.Compiler.handleAttributes(rootDom, params); - UITool.handleUIParam(rootDom, this, ['valuefield', 'displayfield', 'multiple|bool', 'filetype', 'maxcount|number', 'uploadurl', 'deleteurl', 'uploadname'], ['valueField', 'displayField', 'multiple', 'fileType', 'maxCount', 'uploadUrl', 'deleteUrl', 'uploadName'], [null, null, null, '', 1, null, '', 'file']); - } - else if (typeof params === 'object') { - for (let o in params) { - this[o] = params[o]; - } - } - this.generate(rootDom); - } - rootDom.tagName = 'span'; - rootDom.plugin = this; - this.element = rootDom; - } - generate(rootDom) { - rootDom.addClass('nd-file'); - this.extraDataName = '$ui_file_' + nodom.Util.genId(); - let field = rootDom.getDirective('field'); - if (field) { - this.dataName = field.value; - rootDom.removeDirectives(['field']); - rootDom.events.delete('change'); - } - if (!this.multiple) { - this.maxCount = 1; - } - rootDom.children = [this.genShowDom(), this.genUploadDom()]; - rootDom.plugin = this; - return rootDom; - } - genUploadDom() { - const me = this; - let uploadDom = new nodom.Element('div'); - uploadDom.addClass('nd-file-uploadct'); - uploadDom.addDirective(new nodom.Directive('show', this.dataName + '.length<' + this.maxCount, uploadDom)); - let fDom = new nodom.Element('input'); - fDom.setProp('type', 'file'); - fDom.addClass('nd-file-input'); - fDom.addEvent(new nodom.NodomEvent('change', (dom, model, module, e, el) => { - if (!el.files) { - return; - } - model.set(me.extraDataName + '.state', 1); - model.set(me.extraDataName + '.uploading', NUITipWords.uploading); - let form = new FormData(); - for (let f of el.files) { - form.append(me.uploadName, f); - } - nodom.request({ - url: me.uploadUrl, - method: 'POST', - params: form, - header: { - 'Content-Type': 'multipart/form-data' - }, - type: 'json' - }).then((r) => { - model.set(me.extraDataName + '.state', 0); - model.query(me.dataName).push(r); - }); - })); - let uploadingDom = new nodom.Element('div'); - uploadingDom.addClass('nd-file-uploading'); - let span1 = new nodom.Element('span'); - span1.addClass('nd-file-add'); - span1.addDirective(new nodom.Directive('show', this.extraDataName + '.state==0', span1)); - uploadingDom.add(span1); - let span2 = new nodom.Element('span'); - span2.addClass('nd-file-progress'); - span2.addDirective(new nodom.Directive('show', this.extraDataName + '.state==1', span2)); - let txt = new nodom.Element(); - txt.expressions = [new nodom.Expression((this.extraDataName + '.uploading') || NUITipWords.uploading)]; - span2.add(txt); - uploadingDom.add(span2); - uploadDom.add(uploadingDom); - uploadDom.add(fDom); - return uploadDom; - } - genShowDom() { - const me = this; - let ctDom = new nodom.Element('div'); - ctDom.addClass('nd-file-showct'); - ctDom.addDirective(new nodom.Directive('repeat', this.dataName, ctDom)); - let showDom = new nodom.Element('a'); - showDom.addClass('nd-file-content'); - showDom.setProp('target', 'blank'); - let expr = new nodom.Expression(this.displayField); - showDom.setProp('href', expr, true); - if (this.fileType === 'image') { - let img = new nodom.Element('img'); - img.setProp('src', expr, true); - showDom.add(img); - } - else { - let txt = new nodom.Element(); - txt.expressions = [expr]; - showDom.add(txt); - } - ctDom.add(showDom); - let delDom = new nodom.Element('b'); - delDom.addClass('nd-file-del'); - ctDom.add(delDom); - delDom.addEvent(new nodom.NodomEvent('click', (dom, model, module, e) => { - let params = {}; - let id = model.query(me.valueField); - params[me.valueField] = id; - if (this.deleteUrl !== '') { - nodom.request({ - url: me.deleteUrl, - params: params - }).then((r) => { - me.removeFile(module, id); - }); - } - else { - me.removeFile(module, id); - } - })); - return ctDom; - } - removeFile(module, id) { - let pm = module.modelFactory.get(this.modelId); - let rows = pm.query(this.dataName); - if (Array.isArray(rows)) { - for (let i = 0; i < rows.length; i++) { - if (rows[i][this.valueField] === id) { - rows.splice(i, 1); - break; - } - } - } - } - beforeRender(module, dom) { - super.beforeRender(module, dom); - if (this.needPreRender) { - let model = module.modelFactory.get(dom.modelId); - if (model) { - model.set(this.extraDataName, { - state: 0, - uploading: false - }); - } - } - } -} -nodom.PluginManager.add('UI-FILE', UIFile); -class UIForm extends nodom.Plugin { - constructor(params) { - super(params); - this.tagName = 'UI-FORM'; - let rootDom = new nodom.Element(); - if (params) { - if (params instanceof HTMLElement) { - nodom.Compiler.handleAttributes(rootDom, params); - nodom.Compiler.handleChildren(rootDom, params); - UITool.handleUIParam(rootDom, this, ['labelwidth|number'], ['labelWidth'], [100]); - } - else if (typeof params === 'object') { - for (let o in params) { - this[o] = params[o]; - } - } - this.generate(rootDom); - } - rootDom.tagName = 'form'; - rootDom.plugin = this; - this.element = rootDom; - } - generate(rootDom) { - rootDom.addClass('nd-form'); - for (let c of rootDom.children) { - if (!c.tagName) { - continue; - } - c.addClass('nd-form-item'); - if (c.children) { - for (let c1 of c.children) { - if (c1.tagName === 'LABEL') { - c1.assets.set('style', 'width:' + this.labelWidth + 'px'); - break; - } - } - } - } - } -} -nodom.PluginManager.add('UI-FORM', UIForm); -class UIGrid extends nodom.Plugin { - constructor(params) { - super(params); - this.tagName = 'UI-GRID'; - this.fields = []; - let rootDom = new nodom.Element(); - if (params) { - if (params instanceof HTMLElement) { - nodom.Compiler.handleAttributes(rootDom, params); - nodom.Compiler.handleChildren(rootDom, params); - UITool.handleUIParam(rootDom, this, ['dataname', 'rowalt|bool', 'sortable|bool', 'gridline', 'fixhead|bool', 'hidehead|bool', 'dataurl'], ['dataName', 'rowAlt', 'sortable', 'gridLine', 'fixHead', 'hideHead', 'dataUrl'], ['rows', null, null, '', null, null, null, null]); - } - else if (typeof params === 'object') { - for (let o in params) { - this[o] = params[o]; - } - } - rootDom.tagName = 'div'; - rootDom = this.generate(rootDom); - } - rootDom.plugin = this; - this.element = rootDom; - } - generate(rootDom) { - rootDom.addClass('nd-grid'); - this.extraDataName = '$ui_grid_' + nodom.Util.genId(); - if (this.fixHead) { - rootDom.addClass('nd-grid-fixed'); - } - let thead; - if (!this.hideHead) { - thead = new nodom.Element('div'); - thead.addClass('nd-grid-head'); - } - let tbody = new nodom.Element('div'); - tbody.addClass('nd-grid-body'); - if (this.rowAlt) { - tbody.addClass('nd-grid-body-rowalt'); - } - let rowDom; - let subDom; - let pagination; - for (let c of rootDom.children) { - if (c.tagName === 'COLS') { - rowDom = c; - } - else if (c.tagName === 'SUB') { - subDom = c; - } - else if (c.plugin && c.plugin.tagName === 'UI-PAGINATION') { - pagination = c; - } - } - if (rowDom) { - this.rowDomKey = rowDom.key; - let filter; - if (pagination) { - this.selectPageMethodId = '$$nodom_method_gen_' + nodom.Util.genId(); - filter = new nodom.Filter('select:func:' + this.selectPageMethodId); - } - let directive = new nodom.Directive('repeat', this.extraDataName + '.' + this.dataName, rowDom); - if (filter) { - directive.filters = [filter]; - } - rowDom.addDirective(directive); - rowDom.tagName = 'div'; - let dataDom = new nodom.Element('div'); - dataDom.addClass('nd-grid-row'); - if (this.gridLine === 'col' || this.gridLine === 'both') { - dataDom.addClass('nd-grid-col-line'); - } - if (this.gridLine === 'row' || this.gridLine === 'both') { - dataDom.addClass('nd-grid-row-line'); - } - for (let i = 0; i < rowDom.children.length; i++) { - let c = rowDom.children[i]; - if (!c.tagName) { - rowDom.children.splice(i--, 1); - continue; - } - if (c.hasProp('hide')) { - c.delProp('hide'); - continue; - } - let field = c.getProp('field'); - if (field) { - field = field.trim(); - } - this.fields.push({ - title: c.getProp('title'), - field: field, - expressions: c.children[0].expressions - }); - this.addToHead(c, i, thead, field); - let tdIn = c.children[0]; - switch (c.getProp('type')) { - case 'img': - tdIn.tagName = 'img'; - tdIn.setProp('src', tdIn.expressions, true); - c.children = [tdIn]; - delete tdIn.expressions; - break; - } - c.tagName = 'div'; - c.addClass('nd-grid-row-item'); - if (c.hasProp('left')) { - c.addClass('nd-grid-row-item-left'); - } - if (c.hasProp('width') && nodom.Util.isNumberString(c.getProp('width'))) { - c.setProp('style', 'flex:' + c.getProp('width')); - } - dataDom.add(c); - c.delProp(['title', 'type', 'width', 'field', 'notsort', 'left']); - } - rowDom.children = [dataDom]; - rowDom.delProp('data'); - if (subDom) { - this.handleSub(subDom, thead, dataDom, rowDom); - } - tbody.add(rowDom); - } - if (thead) { - rootDom.children = [thead, tbody]; - if (this.gridLine === 'row' || this.gridLine === 'both') { - rootDom.addClass('nd-grid-ct-row-line'); - } - } - else { - rootDom.children = [tbody]; - } - if (this.gridLine === 'row' || this.gridLine === 'both') { - rootDom.addClass('nd-grid-ct-row-line'); - } - if (this.gridLine === 'col' || this.gridLine === 'both') { - rootDom.addClass('nd-grid-ct-col-line'); - } - if (pagination) { - let parentDom = new nodom.Element('div'); - parentDom.children = [rootDom, pagination]; - pagination.addClass('nd-grid-pager'); - this.handlePagination(pagination); - return parentDom; - } - return rootDom; - } - addToHead(col, index, thead, field) { - if (!thead) { - return; - } - if (thead.children.length === 0) { - let thCt = new nodom.Element('div'); - thCt.addClass('nd-grid-row'); - if (this.gridLine === 'col' || this.gridLine === 'both') { - thCt.addClass('nd-grid-col-line'); - } - if (this.gridLine === 'row' || this.gridLine === 'both') { - thCt.addClass('nd-grid-row-line'); - } - thead.add(thCt); - } - if (thead) { - let th = new nodom.Element('div'); - th.addClass('nd-grid-row-item'); - th.setProp('style', 'flex:' + col.getProp('width') || 0); - let span = new nodom.Element('span'); - span.assets.set('innerHTML', col.getProp('title')); - th.add(span); - if (this.sortable) { - if (col.getProp('type') !== 'img' && !col.hasProp('notsort') && field) { - th.add(this.addSortBtn(index)); - } - } - thead.children[0].add(th); - } - } - addSortBtn(index) { - let updown = new nodom.Element('span'); - updown.addClass('nd-grid-sort'); - let up = new nodom.Element('B'); - up.addClass('nd-grid-sort-raise'); - up.tmpData = { index: index }; - let down = new nodom.Element('B'); - down.addClass('nd-grid-sort-down'); - down.tmpData = { index: index }; - const plugin = this; - up.addEvent(new nodom.NodomEvent('click', (dom, model, module, e) => { - plugin.sort(parseInt(dom.tmpData['index']), 'asc', module); - })); - down.addEvent(new nodom.NodomEvent('click', (dom, model, module, e) => { - plugin.sort(parseInt(dom.tmpData['index']), 'desc', module); - })); - updown.add(up); - updown.add(down); - return updown; - } - handleSub(subDom, thead, dataDom, rowDom) { - let th = new nodom.Element('div'); - th.addClass('nd-grid-iconcol'); - let b = new nodom.Element('b'); - b.addClass('nd-grid-sub-btn'); - th.add(b); - if (thead) { - thead.children[0].children.unshift(th); - } - let td = new nodom.Element('div'); - td.addClass('nd-grid-iconcol'); - b = new nodom.Element('b'); - b.addClass('nd-grid-sub-btn'); - b.addDirective(new nodom.Directive('class', "{'nd-grid-showsub':'$showSub'}", b)); - b.addEvent(new nodom.NodomEvent('click', ':delg', (dom, model, module, e) => { - model.set('$showSub', !model.data['$showSub']); - })); - td.add(b); - dataDom.children.unshift(td); - subDom.tagName = 'div'; - rowDom.add(subDom); - subDom.addDirective(new nodom.Directive('show', '$showSub', subDom)); - subDom.addClass('nd-grid-sub'); - if (subDom.hasProp('auto')) { - subDom.children = []; - let lw = subDom.getProp('labelwidth') || 100; - let cols = subDom.hasProp('cols') ? parseInt(subDom.getProp('cols')) : 1; - if (cols > 4) { - cols = 4; - } - let cnt = 0; - let rowCt; - this.fields.forEach((item) => { - if (cnt++ % cols === 0) { - rowCt = new nodom.Element('div'); - rowCt.addClass('nd-grid-sub-row'); - subDom.add(rowCt); - } - let itemCt = new nodom.Element('div'); - itemCt.addClass('nd-grid-sub-item'); - let label = new nodom.Element('label'); - label.assets.set('innerHTML', item['title'] + ':'); - label.assets.set('style', 'width:' + lw + 'px'); - itemCt.add(label); - let span = new nodom.Element('span'); - span.addClass('nd-grid-sub-content'); - let txt = new nodom.Element(); - txt.expressions = item['expressions']; - span.add(txt); - itemCt.add(span); - rowCt.add(itemCt); - subDom.delProp(['auto', 'labelwidth']); - }); - } - } - sort(index, asc, module) { - let dom = module.virtualDom.query(this.rowDomKey); - let directive = dom.getDirective('repeat'); - if (!directive) { - return; - } - let f = this.fields[index]; - if (!f || !f['field']) { - return; - } - let arr = ['orderby', f['field'], asc]; - if (!directive.filters) { - directive.filters = []; - } - if (directive.filters.length <= 1) { - directive.filters.push(new nodom.Filter(arr)); - } - else { - directive.filters[1] = new nodom.Filter(arr); - } - nodom.Renderer.add(module); - } - beforeRender(module, uidom) { - let me = this; - super.beforeRender(module, uidom); - if (this.needPreRender) { - let model = module.modelFactory.get(uidom.modelId); - model.set(this.extraDataName, {}); - if (!this.pagination) { - this.doReq(module, this.pagination); - } - if (this.selectPageMethodId) { - module.methodFactory.add(this.selectPageMethodId, (arr) => { - let start = (me.currentPage - 1) * me.pageSize; - let end = start + me.pageSize; - return arr.slice(start, end); - }); - } - } - } - handlePagination(pagination) { - let me = this; - let df = pagination.plugin; - this.pagination = df; - df.dataUrl = this.dataUrl; - if (df.currentPage) { - this.currentPage = df.currentPage; - } - if (df.pageSize) { - this.pageSize = df.pageSize; - } - if (!df.onChange) { - df.onChange = (module) => { - me.doReq(module, df); - }; - } - } - doReq(module, pagination) { - const me = this; - let params = {}; - if (pagination) { - let reqName = pagination.requestName; - if (reqName.length === 2) { - params[reqName[0]] = pagination.currentPage; - params[reqName[1]] = pagination.pageSize; - } - } - nodom.request({ - url: me.dataUrl, - params: params, - type: 'json' - }).then(r => { - if (!r) { - return; - } - let model = module.modelFactory.get(me.modelId); - model.set(this.extraDataName, r); - if (pagination) { - if (pagination.pageSize) { - this.pageSize = pagination.pageSize; - } - model.set(pagination.extraDataName + '.total', r[pagination.totalName]); - pagination.changeParams(module); - } - }); - } - getData() { - let module = nodom.ModuleFactory.get(this.moduleId); - let model = module.modelFactory.get(this.modelId); - model = model.get(this.extraDataName); - let data = model.getData(); - if (data) { - return data[this.dataName]; - } - } -} -nodom.PluginManager.add('UI-GRID', UIGrid); -class UILayout extends nodom.Plugin { - constructor(params) { - super(params); - this.tagName = 'UI-LAYOUT'; - let rootDom = new nodom.Element(); - if (params) { - if (params instanceof HTMLElement) { - nodom.Compiler.handleAttributes(rootDom, params); - nodom.Compiler.handleChildren(rootDom, params); - } - else if (typeof params === 'object') { - for (let o in params) { - this[o] = params[o]; - } - } - this.generate(rootDom); - } - rootDom.tagName = 'div'; - rootDom.plugin = this; - this.element = rootDom; - } - generate(rootDom) { - rootDom.addClass('nd-layout'); - this.extraDataName = '$ui_layout_' + nodom.Util.genId(); - let middleCt = new nodom.Element(); - middleCt.addClass('nd-layout-middle'); - middleCt.tagName = 'DIV'; - let items = {}; - let locs = ['north', 'west', 'center', 'east', 'south']; - for (let i = 0; i < rootDom.children.length; i++) { - let item = rootDom.children[i]; - if (!item.tagName) { - continue; - } - for (let l of locs) { - if (item.hasProp(l)) { - item.addClass('nd-layout-' + l); - items[l] = item; - if (l === 'west') { - this.handleEastAndWest(item, 0); - } - else if (l === 'east') { - this.handleEastAndWest(item, 1); - } - break; - } - } - } - rootDom.children = []; - if (items['north']) { - rootDom.children.push(items['north']); - } - if (items['west']) { - middleCt.children.push(items['west']); - } - if (items['center']) { - middleCt.children.push(items['center']); - } - if (items['east']) { - middleCt.children.push(items['east']); - } - rootDom.children.push(middleCt); - if (items['south']) { - rootDom.children.push(items['south']); - } - } - beforeRender(module, dom) { - super.beforeRender(module, dom); - if (this.needPreRender) { - let model = module.modelFactory.get(dom.modelId); - model.set(this.extraDataName, { - openWest: true, - openEast: true, - westWidth: 0, - eastWidth: 0 - }); - } - } - handleEastAndWest(dom, loc) { - const me = this; - if (dom.hasProp('title') || dom.hasProp('allowmin')) { - let header = new nodom.Element('div'); - header.addClass('nd-layout-header'); - dom.children.unshift(header); - let title; - if (dom.hasProp('title')) { - title = new nodom.Element('div'); - title.addClass('nd-layout-title'); - let txt = new nodom.Element(); - txt.textContent = dom.getProp('title'); - title.add(txt); - header.add(title); - } - let icon; - if (dom.hasProp('allowmin')) { - icon = new nodom.Element('b'); - if (loc === 1) { - if (title) { - title.addDirective(new nodom.Directive('show', this.extraDataName + '.openEast', title)); - } - icon.addDirective(new nodom.Directive('class', "{'nd-icon-arrow-right':'" + this.extraDataName + ".openEast','nd-icon-arrow-left':'!" + this.extraDataName + ".openEast'}", icon)); - icon.addEvent(new nodom.NodomEvent('click', (dom, model, module, e, el) => { - let data = model.query(me.extraDataName); - let eastEl = el.parentNode.parentNode; - let compStyle = window.getComputedStyle(eastEl); - let width; - if (data.openEast) { - if (data.eastWidth === 0) { - data.eastWidth = compStyle.width; - } - width = '40px'; - } - else { - width = data.eastWidth; - } - eastEl.style.width = width; - data.openEast = !data.openEast; - })); - header.children.unshift(icon); - } - else { - if (title) { - title.addDirective(new nodom.Directive('show', this.extraDataName + '.openWest', title)); - } - icon.addDirective(new nodom.Directive('class', "{'nd-icon-arrow-left':'" + this.extraDataName + ".openWest','nd-icon-arrow-right':'!" + this.extraDataName + ".openWest'}", icon)); - icon.addEvent(new nodom.NodomEvent('click', (dom, model, module, e, el) => { - let data = model.query(me.extraDataName); - let westEl = el.parentNode.parentNode; - let compStyle = window.getComputedStyle(westEl); - let width; - if (data.openWest) { - if (data.westWidth === 0) { - data.westWidth = compStyle.width; - } - width = '40px'; - } - else { - width = data.westWidth; - } - westEl.style.width = width; - data.openWest = !data.openWest; - })); - header.add(icon); - } - } - } - } -} -nodom.PluginManager.add('UI-LAYOUT', UILayout); -class UIList extends nodom.Plugin { - constructor(params) { - super(params); - this.tagName = 'UI-LIST'; - let rootDom = new nodom.Element(); - if (params) { - if (params instanceof HTMLElement) { - nodom.Compiler.handleAttributes(rootDom, params); - nodom.Compiler.handleChildren(rootDom, params); - UITool.handleUIParam(rootDom, this, ['valuefield', 'displayfield', 'disablefield', 'listfield', 'type', 'itemclick', 'itemwidth|number', 'multiselect|bool'], ['valueField', 'displayField', 'disableName', 'listField', 'type', 'clickEvent', 'itemWidth', 'multiSelect'], ['', '', '', null, 'row', '', 0, null]); - } - else if (typeof params === 'object') { - for (let o in params) { - this[o] = params[o]; - } - } - this.generate(rootDom); - } - rootDom.tagName = 'div'; - rootDom.plugin = this; - this.element = rootDom; - } - generate(rootDom) { - let me = this; - this.extraDataName = '$ui_list_' + nodom.Util.genId(); - rootDom.addDirective(new nodom.Directive('model', this.extraDataName, rootDom)); - if (this.type === 'row') { - rootDom.addClass('nd-list'); - } - else { - rootDom.addClass('nd-list-horizontal'); - } - let field = rootDom.getDirective('field'); - if (field) { - this.dataName = field.value; - } - let itemDom; - for (let c of rootDom.children) { - if (!c.tagName) { - continue; - } - itemDom = c; - break; - } - if (!itemDom) { - itemDom = new nodom.Element('div'); - if (this.displayField !== '') { - let txt = new nodom.Element(); - txt.expressions = [new nodom.Expression(this.displayField)]; - itemDom.add(txt); - } - } - itemDom.addClass('nd-list-item'); - itemDom.addDirective(new nodom.Directive('repeat', 'datas', itemDom)); - itemDom.addEvent(new nodom.NodomEvent('click', (dom, model, module) => { - if (me.disableName !== '' && model.query(me.disableName)) { - return; - } - me.setValue(module, model); - })); - if (this.type === 'row') { - let item = new nodom.Element('div'); - item.children = itemDom.children; - item.addClass('nd-list-itemcontent'); - let icon = new nodom.Element('b'); - icon.addClass('nd-list-icon'); - itemDom.children = [item, icon]; - } - if (this.disableName !== '') { - itemDom.addDirective(new nodom.Directive('class', "{'nd-list-item-active':'selected','nd-list-item-disable':'" + this.disableName + "'}", itemDom)); - } - else { - itemDom.addDirective(new nodom.Directive('class', "{'nd-list-item-active':'selected'}", itemDom)); - } - if (this.clickEvent) { - itemDom.addEvent(new nodom.NodomEvent('click', this.clickEvent)); - } - rootDom.children = [itemDom]; - } - beforeRender(module, dom) { - super.beforeRender(module, dom); - let pmodel; - let model; - if (this.needPreRender) { - pmodel = module.modelFactory.get(this.modelId); - pmodel.set(this.extraDataName, { - datas: [] - }).id; - } - if (!pmodel) { - pmodel = module.modelFactory.get(this.modelId); - } - if (!model) { - model = pmodel.get(this.extraDataName); - } - let data = model.data; - if (this.listField && data.datas.length === 0 && pmodel.data[this.listField]) { - let valueArr; - if (this.dataName) { - let value = pmodel.query(this.dataName); - if (value && value !== '') { - valueArr = value.toString().split(','); - } - } - let rows = pmodel.query(this.listField); - if (rows && Array.isArray(rows)) { - rows = nodom.Util.clone(rows); - if (this.valueField !== '') { - for (let d of rows) { - if (valueArr && valueArr.includes(d[this.valueField] + '')) { - d.selected = true; - } - else { - d.selected = false; - } - } - } - model.set('datas', rows); - this.setValue(module); - } - } - } - setValue(module, model) { - let pmodel = module.modelFactory.get(this.modelId); - let model1 = pmodel.get(this.extraDataName); - let rows = model1.data['datas']; - let valArr = []; - if (this.multiSelect) { - if (model) { - model.set('selected', !model.data.selected); - } - if (this.valueField !== '' && this.dataName) { - for (let d of rows) { - if (d.selected) { - valArr.push(d[this.valueField]); - } - } - pmodel.set(this.dataName, valArr.join(',')); - } - } - else { - if (model) { - for (let d of rows) { - if (d.selected) { - d.selected = false; - break; - } - } - model.set('selected', !model.data.selected); - } - for (let d of rows) { - if (d.selected) { - if (this.valueField !== '' && this.dataName) { - pmodel.set(this.dataName, d[this.valueField]); - } - break; - } - } - } - } -} -nodom.PluginManager.add('UI-LIST', UIList); -class UIListTransfer extends nodom.Plugin { - constructor(params) { - super(params); - this.tagName = 'UI-LISTTRANSFER'; - let rootDom = new nodom.Element(); - if (params) { - if (params instanceof HTMLElement) { - nodom.Compiler.handleAttributes(rootDom, params); - nodom.Compiler.handleChildren(rootDom, params); - UITool.handleUIParam(rootDom, this, ['valuefield', 'displayfield', 'listfield'], ['valueField', 'displayField', 'listField']); - } - else if (typeof params === 'object') { - for (let o in params) { - this[o] = params[o]; - } - } - this.generate(rootDom); - } - rootDom.tagName = 'div'; - rootDom.plugin = this; - this.element = rootDom; - } - generate(rootDom) { - let me = this; - this.extraDataName = '$ui_listtransfer_' + nodom.Util.genId(); - rootDom.addDirective(new nodom.Directive('model', this.extraDataName, rootDom)); - rootDom.addClass('nd-listtransfer'); - let field = rootDom.getDirective('field'); - if (field) { - this.dataName = field.value; - } - let listDom = new nodom.Element('div'); - listDom.addClass('nd-list'); - let itemDom; - for (let c of rootDom.children) { - if (!c.tagName) { - continue; - } - itemDom = c; - break; - } - if (!itemDom) { - itemDom = new nodom.Element('div'); - let txt = new nodom.Element(); - txt.expressions = [new nodom.Expression(this.displayField)]; - itemDom.add(txt); - } - itemDom.addClass('nd-list-item'); - itemDom.addDirective(new nodom.Directive('repeat', 'datas', itemDom, "select:value:{isValue:false}")); - itemDom.addDirective(new nodom.Directive('class', "{'nd-list-item-active':'selected'}", itemDom)); - itemDom.addEvent(new nodom.NodomEvent('click', (dom, model, module) => { - model.set('selected', !model.data.selected); - })); - let item = new nodom.Element('div'); - item.children = itemDom.children; - item.addClass('nd-list-itemcontent'); - let icon = new nodom.Element('b'); - icon.addClass('nd-list-icon'); - itemDom.children = [item, icon]; - listDom.children = [itemDom]; - let listDom1 = listDom.clone(true); - listDom1.children[0].getDirective('repeat').filters = [new nodom.Filter("select:value:{isValue:true}")]; - let btnGrp = new nodom.Element('div'); - btnGrp.addClass('nd-listtransfer-btngrp'); - let btn1 = new nodom.Element('b'); - btn1.addClass('nd-listtransfer-right2'); - let btn2 = new nodom.Element('b'); - btn2.addClass('nd-listtransfer-right1'); - let btn3 = new nodom.Element('b'); - btn3.addClass('nd-listtransfer-left1'); - let btn4 = new nodom.Element('b'); - btn4.addClass('nd-listtransfer-left2'); - btnGrp.children = [btn1, btn2, btn3, btn4]; - btn1.addEvent(new nodom.NodomEvent('click', (dom, model, module, e) => { - me.transfer(module, 1, true); - })); - btn2.addEvent(new nodom.NodomEvent('click', (dom, model, module, e) => { - me.transfer(module, 1, false); - })); - btn3.addEvent(new nodom.NodomEvent('click', (dom, model, module, e) => { - me.transfer(module, 2, false); - })); - btn4.addEvent(new nodom.NodomEvent('click', (dom, model, module, e) => { - me.transfer(module, 2, true); - })); - rootDom.children = [listDom, btnGrp, listDom1]; - rootDom.plugin = this; - return rootDom; - } - beforeRender(module, dom) { - super.beforeRender(module, dom); - let pmodel; - if (this.needPreRender) { - pmodel = module.modelFactory.get(this.modelId); - let model = pmodel.set(this.extraDataName, { - datas: [] - }); - this.extraModelId = model.id; - let value = pmodel.query(this.dataName); - let datas = pmodel.query(this.listField); - let rows = []; - if (Array.isArray(datas)) { - let va = []; - if (value) { - va = value.split(','); - } - rows = nodom.Util.clone(datas); - for (let d of rows) { - d.selected = false; - d.isValue = false; - if (va && va.includes(d[this.valueField] + '')) { - d.isValue = true; - } - } - } - model.set('datas', rows); - } - } - transfer(module, direction, all) { - let model = module.modelFactory.get(this.extraModelId); - let datas = model.data.datas; - let isValue = direction === 1 ? true : false; - for (let d of datas) { - if (all) { - d.isValue = isValue; - } - else if (d.selected) { - d.isValue = isValue; - } - d.selected = false; - } - this.updateValue(module); - } - updateValue(module) { - let pmodel = module.modelFactory.get(this.modelId); - let model = module.modelFactory.get(this.extraModelId); - let a = []; - for (let d of model.data.datas) { - if (d.isValue) { - a.push(d[this.valueField]); - } - } - pmodel.set(this.dataName, a.join(',')); - } -} -nodom.PluginManager.add('UI-LISTTRANSFER', UIListTransfer); -class UIMenu extends nodom.Plugin { - constructor(params) { - super(params); - this.tagName = 'UI-MENU'; - this.menuHeight = 30; - this.direction = 0; - let rootDom = new nodom.Element(); - if (params) { - if (params instanceof HTMLElement) { - nodom.Compiler.handleAttributes(rootDom, params); - nodom.Compiler.handleChildren(rootDom, params); - UITool.handleUIParam(rootDom, this, ['popup|bool', 'position', 'listfield', 'maxlevel|number', 'menuwidth|number'], ['popupMenu', 'position', 'listField', 'maxLevel', 'menuWidth'], [null, 'top', null, 3, 150]); - } - else if (typeof params === 'object') { - for (let o in params) { - this[o] = params[o]; - } - } - this.generate(rootDom); - } - rootDom.tagName = 'div'; - rootDom.plugin = this; - this.element = rootDom; - } - generate(rootDom) { - let me = this; - this.activeName = '$nui_menu_' + nodom.Util.genId(); - this.menuStyleName = '$nui_menu_' + nodom.Util.genId(); - rootDom.addClass('nd-menu'); - if (this.position === 'left' || this.position === 'right') { - this.popupMenu = true; - } - let menuNode; - for (let i = 0; i < rootDom.children.length; i++) { - if (rootDom.children[i].tagName) { - menuNode = rootDom.children[i]; - menuNode.addClass('nd-menu-node'); - let b = new nodom.Element('b'); - menuNode.children.unshift(b); - if (menuNode.hasProp('icon')) { - b.setProp('class', ['nd-icon-', new nodom.Expression(menuNode.getProp('icon'))], true); - menuNode.delProp('icon'); - } - break; - } - } - rootDom.children = []; - let parentCt = new nodom.Element('div'); - parentCt.addClass('nd-menu-subct'); - if (this.popupMenu) { - if (this.position === 'left' || this.position === 'right') { - rootDom.addClass('nd-menu-left'); - rootDom.addEvent(new nodom.NodomEvent('mouseleave', (dom, model, module, e) => { - dom.assets.set('style', 'width:30px'); - })); - parentCt.addEvent(new nodom.NodomEvent('mouseenter', (dom, model, module, e) => { - dom.assets.set('style', 'width:' + me.menuWidth + 'px'); - })); - } - else { - rootDom.addClass('nd-menu-popup'); - parentCt.addClass('nd-menu-first'); - parentCt.setProp('style', new nodom.Expression(this.menuStyleName), true); - parentCt.addEvent(new nodom.NodomEvent('mouseleave', (dom, model, module, e) => { - let parent = dom.getParent(module); - let pmodel = module.modelFactory.get(parent.modelId); - pmodel.set(me.activeName, false); - if (dom.hasClass('nd-menu-first')) { - this.direction = 0; - } - })); - parentCt.addDirective(new nodom.Directive('show', this.activeName, parentCt)); - } - } - else { - parentCt.addClass('nd-menu-first-nopop'); - } - rootDom.add(parentCt); - for (let i = 0; i < this.maxLevel; i++) { - parentCt.tmpData = { level: i + 1 }; - let itemCt = new nodom.Element('div'); - itemCt.directives.push(new nodom.Directive('repeat', this.listField, itemCt)); - itemCt.addClass('nd-menu-nodect'); - let item = menuNode.clone(true); - itemCt.add(item); - itemCt.tmpData = { level: (i + 1) }; - if (this.popupMenu || i > 0) { - let icon1 = new nodom.Element('b'); - icon1.addDirective(new nodom.Directive('class', "{'nd-menu-subicon':'" + this.listField + "&&" + this.listField + ".length>0'}", icon1)); - item.add(icon1); - } - let openClose = this.initOpenAndClose(); - itemCt.addEvent(openClose[0]); - itemCt.addEvent(openClose[1]); - parentCt.add(itemCt); - let subCt = new nodom.Element('div'); - subCt.addClass('nd-menu-subct'); - subCt.addEvent(new nodom.NodomEvent('mouseleave', (dom, model, module, e) => { - let parent = dom.getParent(module); - let pmodel = module.modelFactory.get(parent.modelId); - pmodel.set(me.activeName, false); - })); - subCt.setProp('style', new nodom.Expression(this.menuStyleName), true); - subCt.addDirective(new nodom.Directive('show', this.activeName, subCt)); - itemCt.add(subCt); - parentCt = subCt; - } - rootDom.delProp(['listField', 'width', , 'maxlevels']); - } - beforeRender(module, uidom) { - let me = this; - super.beforeRender(module, uidom); - if (this.needPreRender && this.popupMenu && this.position !== 'left' && this.position !== 'right') { - UIEventRegister.addEvent('mousedown', module.id, uidom.key, (module, dom, inOrOut, e) => { - if (e.button !== 2) { - return; - } - let x = e.clientX; - let w = me.menuWidth; - let model = module.modelFactory.get(uidom.modelId); - let rows = model.query(me.listField); - if (rows && rows.length > 0) { - let h = rows.length * me.menuHeight; - let loc = this.cacPos(null, e.clientX, e.clientY, this.menuWidth, h); - model.set(me.menuStyleName, 'width:' + me.menuWidth + 'px;left:' + loc[0] + 'px;top:' + loc[1] + 'px'); - model.set(me.activeName, true); - } - }); - } - } - initOpenAndClose() { - let me = this; - let openEvent = new nodom.NodomEvent('mouseenter', (dom, model, module, e, el) => { - if (model) { - let rows = model.query(this.listField); - if (!rows || rows.length === 0) { - return; - } - let firstNopop = dom.tmpData.level === 1 && !me.popupMenu; - let h = rows.length * this.menuHeight; - let w = this.menuWidth; - let x, y; - if (firstNopop) { - x = e.clientX - e.offsetX; - y = e.clientY - e.offsetY + h; - } - else { - x = e.clientX - e.offsetX + w; - y = e.clientY - e.offsetY; - } - let loc = this.cacPos(dom, x, y, w, h, el); - model.set(this.menuStyleName, 'width:' + me.menuWidth + 'px;left:' + loc[0] + 'px;top:' + loc[1] + 'px'); - model.set(this.activeName, true); - } - }); - let closeEvent = new nodom.NodomEvent('mouseleave', (dom, model, module, e, el) => { - if (model) { - let rows = model.query(this.listField); - if (rows && rows.length > 0) { - model.set(me.activeName, false); - if (this.direction === 1) { - if (me.popupMenu) { - if (dom.tmpData['level'] === 2) { - this.direction = 0; - } - } - else if (dom.tmpData['level'] === 1) { - this.direction = 0; - } - } - } - } - }); - return [openEvent, closeEvent]; - } - cacPos(dom, x, y, w, h, el) { - let firstNopop = dom && !this.popupMenu && dom.tmpData['level'] === 1; - let widthOut = x + w > window.innerWidth; - let heightOut = y + h > window.innerHeight; - let top = dom ? 0 : y; - let left = dom ? 0 : x; - if (firstNopop) { - top = this.menuHeight; - } - else if (heightOut) { - if (dom) { - top = -h + this.menuHeight; - } - else { - top = window.innerHeight - h; - } - } - if (widthOut) { - this.direction = 1; - } - if (this.direction === 1) { - if (firstNopop) { - if (widthOut) { - left = el.offsetWidth - w; - } - } - else if (dom) { - left -= w + 1; - } - else if (widthOut) { - left -= w + 3; - } - } - else { - if (dom && !firstNopop) { - left = w; - } - } - return [left, top + 1]; - } -} -nodom.PluginManager.add('UI-MENU', UIMenu); -class UIPagination extends nodom.Plugin { - constructor(params) { - super(params); - this.tagName = 'UI-PAGINATION'; - this.minPage = 1; - this.maxPage = 1; - let rootDom = new nodom.Element(); - if (params) { - if (params instanceof HTMLElement) { - nodom.Compiler.handleAttributes(rootDom, params); - nodom.Compiler.handleChildren(rootDom, params); - UITool.handleUIParam(rootDom, this, ['totalname', 'pagesize|number', 'currentpage|number', 'showtotal|bool', 'showgo|bool', 'shownum|number', 'sizechange|array|number', 'steps|number', 'onchange', 'requestname|array|2', 'dataurl'], ['totalName', 'pageSize', 'currentPage', 'showTotal', 'showGo', 'showNum', 'pageSizeData', 'steps', 'onChange', 'requestName', 'dataUrl'], ['total', 10, 1, null, null, 10, [], 5, '', [], '']); - } - else if (typeof params === 'object') { - for (let o in params) { - this[o] = params[o]; - } - } - this.generate(rootDom); - } - rootDom.tagName = 'div'; - rootDom.plugin = this; - this.element = rootDom; - } - generate(rootDom) { - let me = this; - rootDom.addClass('nd-pagination'); - rootDom.children = []; - this.extraDataName = '$ui_pagination_' + nodom.Util.genId(); - rootDom.addDirective(new nodom.Directive('model', this.extraDataName, rootDom)); - if (this.showTotal) { - let totalDom = new nodom.Element('div'); - let txt = new nodom.Element(); - txt.textContent = NUITipWords.total; - totalDom.add(txt); - let span = new nodom.Element('span'); - span.addClass('nd-pagination-total'); - txt = new nodom.Element(); - txt.expressions = [new nodom.Expression('total')]; - span.add(txt); - totalDom.add(span); - txt = new nodom.Element(); - txt.textContent = NUITipWords.record; - totalDom.add(txt); - rootDom.add(totalDom); - } - if (this.pageSizeData && this.pageSizeData.length > 0) { - let datas = []; - for (let d of this.pageSizeData) { - datas.push({ - value: d, - text: d + NUITipWords.record + '/' + NUITipWords.page - }); - } - this.pageSizeDatas = datas; - rootDom.add(new UISelect({ - dataName: 'pageSize', - listField: 'sizeData', - displayField: 'text', - valueField: 'value', - onChange: (model, module, newValue, oldValue) => { - me.changeParams(module); - me.update(module); - } - }).element); - } - let pageCt = new nodom.Element('div'); - pageCt.addClass('nd-pagination-pagect'); - let left1 = new nodom.Element('b'); - left1.addClass('nd-pagination-leftarrow1'); - left1.addDirective(new nodom.Directive('class', "{'nd-pagination-disable':'[1,3,5,7,9,11,13,15].includes(btnAllow)'}", left1)); - pageCt.add(left1); - let left = new nodom.Element('b'); - left.addClass('nd-pagination-leftarrow'); - left.addDirective(new nodom.Directive('class', "{'nd-pagination-disable':'[2,3,6,7,10,11,15].includes(btnAllow)'}", left)); - pageCt.add(left); - let page = new nodom.Element('span'); - page.addClass('nd-pagination-page'); - page.addDirective(new nodom.Directive('repeat', 'pages', page)); - page.addDirective(new nodom.Directive('class', "{'nd-pagination-active':'active'}", page), true); - let txt = new nodom.Element(); - txt.expressions = [new nodom.Expression('no')]; - page.add(txt); - pageCt.add(page); - let right = new nodom.Element('b'); - right.addClass('nd-pagination-rightarrow'); - right.addDirective(new nodom.Directive('class', "{'nd-pagination-disable':'[4,5,6,7,12,13,15].includes(btnAllow)'}", right)); - pageCt.add(right); - let right1 = new nodom.Element('b'); - right1.addClass('nd-pagination-rightarrow1'); - right1.addDirective(new nodom.Directive('class', "{'nd-pagination-disable':'[8,9,10,11,12,13,15].includes(btnAllow)'}", right1)); - pageCt.add(right1); - rootDom.add(pageCt); - page.addEvent(new nodom.NodomEvent('click', (dom, model, module) => { - me.changeParams(module, model.data['no']); - me.update(module); - })); - left.addEvent(new nodom.NodomEvent('click', (dom, model, module) => { - if (dom.hasClass('nd-pagination-disable')) { - return; - } - me.changeParams(module, -1, true); - me.update(module); - })); - right.addEvent(new nodom.NodomEvent('click', (dom, model, module) => { - if (dom.hasClass('nd-pagination-disable')) { - return; - } - me.changeParams(module, 1, true); - me.update(module); - })); - left1.addEvent(new nodom.NodomEvent('click', (dom, model, module) => { - if (dom.hasClass('nd-pagination-disable')) { - return; - } - me.changeParams(module, -me.steps, true); - me.update(module); - })); - right1.addEvent(new nodom.NodomEvent('click', (dom, model, module) => { - if (dom.hasClass('nd-pagination-disable')) { - return; - } - me.changeParams(module, me.steps, true); - me.update(module); - })); - if (this.showGo) { - let goDom = new nodom.Element('div'); - goDom.addClass('nd-pagination-go'); - let txt = new nodom.Element(); - txt.textContent = NUITipWords.NO; - goDom.add(txt); - let input = new nodom.Element('input'); - input.setProp('type', 'number'); - input.addDirective(new nodom.Directive('field', 'pageNo', input)); - input.setProp('value', new nodom.Expression('pageNo'), true); - goDom.add(input); - txt = new nodom.Element(); - txt.textContent = NUITipWords.page; - goDom.add(txt); - rootDom.add(goDom); - } - rootDom.plugin = this; - return rootDom; - } - beforeRender(module, uidom) { - super.beforeRender(module, uidom); - this.handleInit(uidom, module); - } - update(module, current, isStep) { - if (this.onChange !== '') { - let foo; - if (typeof this.onChange === 'string') { - foo = module.methodFactory.get(this.onChange); - } - else if (nodom.Util.isFunction(this.onChange)) { - foo = this.onChange; - } - if (foo) { - foo.apply(this, [module, this.currentPage, this.pageSize]); - } - } - } - changeParams(module, current, isStep) { - let model = module.modelFactory.get(this.modelId); - let data = model.query(this.extraDataName); - let total = data.total; - if (!total) { - let data1 = model.data; - if (data1 && data1[this.totalName]) { - total = data1[this.totalName]; - } - if (total) { - data.total = total; - } - } - if (isStep) { - current = this.currentPage + current; - } - if (!total) { - return; - } - model = model.get(this.extraDataName); - let pageSize = model.data['pageSize']; - if (!current) { - let d = model.query('pageNo'); - if (typeof d === 'string' && d !== '') { - d = parseInt(d); - } - current = d || 1; - } - let pageCount = Math.ceil(total / pageSize); - if (current > pageCount) { - current = pageCount; - } - else if (current < 1) { - current = 1; - } - let min = 1; - let max; - let btnAllow = 0; - if (pageCount > this.showNum) { - let center = (this.showNum + 1) / 2 | 0; - if (current - center + 1 > 0) { - min = current - center + 1; - } - if (min < 1) { - min = 1; - } - else if (min + this.showNum - 1 > pageCount) { - min = pageCount - this.showNum + 1; - } - max = min + this.showNum - 1; - if (min === 1) { - btnAllow += 1; - } - if (max === pageCount) { - btnAllow += 8; - } - } - else { - min = 1; - max = pageCount; - btnAllow = 9; - } - if (current === pageCount) { - btnAllow += 4; - } - if (current === 1) { - btnAllow += 2; - } - if (model.query('pageSize') === this.pageSize && current === this.currentPage && min === this.minPage && max === this.maxPage) { - return; - } - let pageArr = []; - for (let i = min; i <= max; i++) { - let active = i === current ? true : false; - pageArr.push({ - no: i, - active: active - }); - } - this.currentPage = current; - this.minPage = min; - this.maxPage = max; - this.pageSize = model.data['pageSize']; - model.set('pages', pageArr); - model.set('pageSize', this.pageSize); - model.set('pageNo', current); - model.set('btnAllow', btnAllow); - } - handleInit(dom, module) { - if (!this.needPreRender) { - return; - } - let model = module.modelFactory.get(dom.modelId); - let model1 = model.set(this.extraDataName, { - total: 0, - pageNum: 0, - pageNo: this.currentPage || 1, - pageSize: this.pageSize, - btnAllow: 0, - pages: [], - sizeData: this.pageSizeDatas || [10, 20, 30, 50] - }); - this.extraModelId = model1.id; - this.changeParams(module, 1); - } -} -nodom.PluginManager.add('UI-PAGINATION', UIPagination); -class UIPanel extends nodom.Plugin { - constructor(params) { - super(params); - this.tagName = 'UI-PANEL'; - let rootDom = new nodom.Element(); - if (params) { - if (params instanceof HTMLElement) { - nodom.Compiler.handleAttributes(rootDom, params); - nodom.Compiler.handleChildren(rootDom, params); - UITool.handleUIParam(rootDom, this, ['title', 'buttons|array'], ['title', 'buttons'], ['Panel', []]); - } - else if (typeof params === 'object') { - for (let o in params) { - this[o] = params[o]; - } - } - this.generate(rootDom); - } - rootDom.tagName = 'div'; - rootDom.plugin = this; - this.element = rootDom; - } - generate(rootDom) { - let me = this; - rootDom.addClass('nd-panel'); - this.handleBody(rootDom); - let headerDom = new nodom.Element('div'); - headerDom.addClass('nd-panel-header'); - if (this.title) { - let titleCt = new nodom.Element('span'); - titleCt.addClass('nd-panel-title'); - titleCt.assets.set('innerHTML', this.title); - headerDom.add(titleCt); - } - let headbarDom = new nodom.Element('div'); - headbarDom.addClass('nd-panel-header-bar'); - this.headerBtnDom = headbarDom; - headerDom.add(headbarDom); - rootDom.children.unshift(headerDom); - for (let btn of this.buttons) { - let a = btn.split('|'); - this.addHeadBtn(a[0], a[1]); - } - } - handleBody(panelDom) { - let bodyDom = new nodom.Element('div'); - bodyDom.addClass('nd-panel-body'); - let tbar; - let btnGrp; - for (let i = 0; i < panelDom.children.length; i++) { - let item = panelDom.children[i]; - if (item.plugin) { - if (item.plugin.tagName === 'UI-TOOLBAR') { - tbar = item; - } - else if (item.plugin.tagName === 'UI-BUTTONGROUP') { - btnGrp = item; - } - } - else { - bodyDom.add(item); - } - } - panelDom.children = []; - if (tbar) { - panelDom.add(tbar); - } - panelDom.add(bodyDom); - if (btnGrp) { - panelDom.add(btnGrp); - } - } - addHeadBtn(icon, handler) { - let btn = new nodom.Element('b'); - btn.addClass('nd-icon-' + icon); - btn.addClass('nd-canclick'); - this.headerBtnDom.add(btn); - if (handler) { - btn.addEvent(new nodom.NodomEvent('click', handler)); - } - } -} -nodom.PluginManager.add('UI-PANEL', UIPanel); -class UIRadio extends nodom.Plugin { - constructor(params) { - super(params); - this.tagName = 'UI-RADIO'; - let rootDom = new nodom.Element(); - if (params) { - if (params instanceof HTMLElement) { - nodom.Compiler.handleAttributes(rootDom, params); - nodom.Compiler.handleChildren(rootDom, params); - } - else if (typeof params === 'object') { - for (let o in params) { - this[o] = params[o]; - } - } - this.generate(rootDom); - } - rootDom.tagName = 'span'; - rootDom.plugin = this; - this.element = rootDom; - } - generate(rootDom) { - rootDom.addClass('nd-radio'); - let field = rootDom.getDirective('field'); - if (field) { - this.dataName = field.value; - rootDom.removeDirectives(['field']); - } - for (let c of rootDom.children) { - if (c.tagName) { - let icon = new nodom.Element('b'); - icon.addClass('nd-radio-unactive'); - icon.addDirective(new nodom.Directive('class', "{'nd-radio-active':'" + this.dataName + "==\"" + c.getProp('value') + "\"'}", icon)); - c.children.unshift(icon); - c.addEvent(new nodom.NodomEvent('click', (dom, model, module) => { - let v = model.data[this.dataName]; - model.set(this.dataName, dom.getProp('value')); - })); - } - } - } -} -nodom.PluginManager.add('UI-RADIO', UIRadio); -class UIRelationMap extends nodom.Plugin { - constructor(params) { - super(params); - this.tagName = 'UI-RELATIONMAP'; - let rootDom = new nodom.Element(); - if (params) { - if (params instanceof HTMLElement) { - nodom.Compiler.handleAttributes(rootDom, params); - UITool.handleUIParam(rootDom, this, ['valuefield|array|1', 'displayfield|array|2', 'listfield|array|2'], ['valueField', 'displayField', 'listField'], [null, null, null]); - } - else if (typeof params === 'object') { - for (let o in params) { - this[o] = params[o]; - } - } - this.generate(rootDom); - } - rootDom.tagName = 'table'; - rootDom.plugin = this; - this.element = rootDom; - } - generate(rootDom) { - let me = this; - rootDom.addClass('nd-relationmap'); - this.mapName = '$ui_relationmap_' + nodom.Util.genId(); - let field = rootDom.getDirective('field'); - if (field) { - this.dataName = field.value; - rootDom.removeDirectives(['field']); - } - let rowHead = new nodom.Element('tr'); - rowHead.addClass('nd-relationmap-head'); - rootDom.add(rowHead); - let td = new nodom.Element('td'); - rowHead.add(td); - td = new nodom.Element('td'); - td.addDirective(new nodom.Directive('repeat', this.listField[0], td)); - let txt = new nodom.Element(); - txt.expressions = [new nodom.Expression(this.displayField[0])]; - td.add(txt); - rowHead.add(td); - let tr = new nodom.Element('tr'); - tr.addDirective(new nodom.Directive('repeat', '$$' + this.mapName, tr)); - tr.addClass('nd-relationmap-row'); - td = new nodom.Element('td'); - td.addClass('nd-relationmap-head'); - txt = new nodom.Element(); - txt.expressions = [new nodom.Expression('title')]; - td.add(txt); - tr.add(td); - td = new nodom.Element('td'); - td.addDirective(new nodom.Directive('repeat', 'cols', td)); - td.addEvent(new nodom.NodomEvent('click', (dom, model, module) => { - me.switchValue(module, dom, model); - })); - let b = new nodom.Element('b'); - b.addDirective(new nodom.Directive('class', "{'nd-relationmap-active':'active'}", b)); - td.add(b); - tr.add(td); - rootDom.children = [rowHead, tr]; - } - beforeRender(module, uidom) { - super.beforeRender(module, uidom); - let model = module.modelFactory.get(uidom.modelId); - let rowData = model.query(this.listField[1]); - let colData = model.query(this.listField[0]); - let data = model.query(this.dataName); - let idRow = this.valueField[1]; - let idCol = this.valueField[0]; - if (!module.model.query(this.mapName)) { - let mapData = []; - let title; - for (let d of rowData) { - let a1 = []; - let id1 = d[idRow]; - title = d[this.displayField[1]]; - for (let d1 of colData) { - let active = false; - if (data && data.length > 0) { - for (let da of data) { - if (da[idRow] === id1 && da[idCol] === d1[idCol]) { - active = true; - break; - } - } - } - a1.push({ - id1: id1, - id2: d1[idCol], - active: active - }); - } - mapData.push({ title: title, cols: a1 }); - } - module.model.set(this.mapName, mapData); - } - } - switchValue(module, dom, model) { - let pmodel = module.modelFactory.get(this.modelId); - let data = pmodel.query(this.dataName); - let id1 = model.data['id1']; - let id2 = model.data['id2']; - let active = model.data['active']; - let o = {}; - o[this.valueField[0]] = id2; - o[this.valueField[1]] = id1; - if (!data) { - if (!active) { - pmodel.set(this.dataName, [o]); - } - } - else { - if (!active) { - data.push(o); - } - else { - for (let i = 0; i < data.length; i++) { - let d = data[i]; - if (d[this.valueField[0]] === id2 && d[this.valueField[1]] === id1) { - data.splice(i, 1); - break; - } - } - } - } - model.set('active', !active); - } -} -nodom.PluginManager.add('UI-RELATIONMAP', UIRelationMap); -class UISelect extends nodom.Plugin { - constructor(params) { - super(params); - this.tagName = 'UI-SELECT'; - let rootDom = new nodom.Element(); - if (params) { - if (params instanceof HTMLElement) { - nodom.Compiler.handleAttributes(rootDom, params); - nodom.Compiler.handleChildren(rootDom, params); - UITool.handleUIParam(rootDom, this, ['valuefield', 'displayfield', 'multiselect|bool', 'listfield', 'listwidth|number', 'allowfilter|bool', 'onchange'], ['valueField', 'displayField', 'multiSelect', 'listField', 'listWidth', 'allowFilter', 'onChange'], [null, null, null, null, 0, null, '']); - } - else if (typeof params === 'object') { - for (let o in params) { - this[o] = params[o]; - } - } - this.generate(rootDom); - } - rootDom.tagName = 'div'; - rootDom.plugin = this; - this.element = rootDom; - } - generate(rootDom) { - let me = this; - this.extraDataName = '$ui_select_' + nodom.Util.genId(); - rootDom.addClass('nd-select'); - let field = rootDom.getDirective('field'); - if (field) { - this.dataName = field.value; - rootDom.removeDirectives(['field']); - rootDom.events.delete('change'); - } - rootDom.addDirective(new nodom.Directive('model', this.extraDataName, rootDom)); - let listDom = new nodom.Element('div'); - listDom.addClass('nd-select-list'); - if (this.listWidth) { - listDom.assets.set('style', 'width:' + this.listWidth + 'px'); - } - listDom.addDirective(new nodom.Directive('show', 'show', listDom)); - let itemDom; - for (let c of rootDom.children) { - if (!c.tagName) { - continue; - } - itemDom = c; - break; - } - if (!itemDom) { - itemDom = new nodom.Element('div'); - let txt = new nodom.Element(); - txt.expressions = [new nodom.Expression(this.displayField)]; - itemDom.add(txt); - } - let item = new nodom.Element('div'); - item.children = itemDom.children; - item.addClass('nd-select-itemcontent'); - itemDom.addClass('nd-select-item'); - let directive = new nodom.Directive('repeat', 'datas', itemDom); - itemDom.addDirective(directive); - itemDom.addDirective(new nodom.Directive('class', "{'nd-select-selected':'selected'}", itemDom)); - let icon = new nodom.Element('b'); - icon.addClass('nd-select-itemicon'); - itemDom.children = [item, icon]; - itemDom.addEvent(new nodom.NodomEvent('click', (dom, model, module) => { - me.setValue(module, model); - })); - let showDom = new nodom.Element('div'); - showDom.addClass('nd-select-inputct'); - let input = new nodom.Element('input'); - input.addClass('nd-select-show'); - if (this.multiSelect) { - input.setProp('readonly', true); - } - input.setProp('value', new nodom.Expression('display'), true); - showDom.add(input); - icon = new nodom.Element('b'); - showDom.addEvent(new nodom.NodomEvent('click', (dom, model, module, e, el) => { - if (model.data.show) { - me.hideList(module, model); - } - else { - model.set('show', true); - let height = el.offsetHeight; - let y = e.clientY + el.offsetHeight - e.offsetY; - UITool.adjustPosAndSize(module, this.listKey, e.clientX, y, height, null, true); - } - })); - if (this.allowFilter) { - this.filterMethodId = '$$nodom_method_' + nodom.Util.genId(); - let filter = new nodom.Filter(['select', 'func', this.filterMethodId]); - directive.filters = [filter]; - input.assets.set('readonly', 'true'); - let queryDom = new nodom.Element('input'); - queryDom.addClass('nd-select-search'); - queryDom.addDirective(new nodom.Directive('field', 'query', queryDom)); - queryDom.addDirective(new nodom.Directive('class', "{'nd-select-search-active':'show'}", queryDom)); - showDom.add(queryDom); - } - showDom.add(icon); - listDom.children = [itemDom]; - rootDom.children = [showDom, listDom]; - } - beforeRender(module, dom) { - let me = this; - super.beforeRender(module, dom); - this.listKey = dom.children[1].key; - let pmodel; - let model; - if (this.needPreRender) { - pmodel = module.modelFactory.get(this.modelId); - let model = pmodel.set(this.extraDataName, { - show: false, - display: '', - query: '', - datas: [] - }); - this.extraModelId = model.id; - module.methodFactory.add(this.filterMethodId, function () { - let model = this.modelFactory.get(me.extraModelId); - let rows = model.query('datas'); - if (rows) { - return rows.filter((item) => { - return model.data.query === '' || item[me.displayField].indexOf(model.data.query) !== -1; - }); - } - return []; - }); - UIEventRegister.addEvent('click', module.id, dom.key, (module, dom, inOrout, e) => { - let model = module.modelFactory.get(me.extraModelId); - if (!inOrout && model.data.show) { - me.hideList(module, model); - } - }); - model = module.modelFactory.get(this.extraModelId); - } - if (!pmodel) { - pmodel = module.modelFactory.get(this.modelId); - } - if (!model) { - model = module.modelFactory.get(this.extraModelId); - } - let data = model.data; - if (this.listField && data.datas.length === 0 && pmodel.data[this.listField]) { - let valueArr; - if (this.dataName) { - let value = pmodel.query(this.dataName); - if (value && value !== '') { - valueArr = value.toString().split(','); - } - } - let txtArr = []; - let rows = pmodel.query(this.listField); - if (rows && Array.isArray(rows)) { - rows = nodom.Util.clone(rows); - for (let d of rows) { - if (valueArr && valueArr.includes(d[this.valueField] + '')) { - d.selected = true; - txtArr.push(d[this.displayField]); - } - else { - d.selected = false; - } - } - model.set('datas', rows); - this.setValue(module); - } - } - } - setValue(module, model) { - let pmodel = module.modelFactory.get(this.modelId); - let model1 = module.modelFactory.get(this.extraModelId); - let rows = model1.data['datas']; - let txtArr = []; - let valArr = []; - let value; - if (this.multiSelect) { - if (model) { - model.set('selected', !model.data.selected); - } - for (let d of rows) { - if (d.selected) { - valArr.push(d[this.valueField]); - txtArr.push(d[this.displayField]); - } - } - if (this.dataName) { - value = valArr.join(','); - } - model1.set('display', txtArr.join(',')); - } - else { - if (model) { - for (let d of rows) { - if (d.selected) { - d.selected = false; - break; - } - } - model.set('selected', !model.data.selected); - } - for (let d of rows) { - if (d.selected) { - if (this.dataName) { - value = d[this.valueField]; - } - model1.set('display', d[this.displayField]); - this.hideList(module, model1); - break; - } - } - } - if (value !== this.value) { - pmodel.set(this.dataName, value); - if (this.onChange !== '') { - let foo; - if (typeof this.onChange === 'string') { - foo = module.methodFactory.get(this.onChange); - } - else { - foo = this.onChange; - } - if (nodom.Util.isFunction(foo)) { - foo.apply(null, [model, module, value, this.value]); - } - } - this.value = value; - } - } - hideList(module, model) { - if (!model) { - model = module.modelFactory.get(this.extraModelId); - } - model.set('show', false); - model.set('query', ''); - } -} -nodom.PluginManager.add('UI-SELECT', UISelect); -class UITab extends nodom.Plugin { - constructor(params) { - super(params); - this.tagName = 'UI-TAB'; - this.tabs = []; - let rootDom = new nodom.Element(); - if (params) { - if (params instanceof HTMLElement) { - nodom.Compiler.handleAttributes(rootDom, params); - nodom.Compiler.handleChildren(rootDom, params); - UITool.handleUIParam(rootDom, this, ['position', 'allowclose|bool', 'listField', 'height|number'], ['position', 'allowClose', 'listField', 'bodyHeight'], ['top', null, '', 0]); - } - else if (typeof params === 'object') { - for (let o in params) { - this[o] = params[o]; - } - } - this.generate(rootDom); - } - rootDom.tagName = 'div'; - rootDom.plugin = this; - this.element = rootDom; - } - generate(rootDom) { - let me = this; - this.extraDataName = '$ui_tab_' + nodom.Util.genId(); - this.name = rootDom.getProp('name'); - rootDom.addClass('nd-tab'); - if (this.position === 'left' || this.position === 'right') { - rootDom.addClass('nd-tab-horizontal'); - } - let headDom = new nodom.Element('div'); - headDom.addClass('nd-tab-head'); - let bodyDom = new nodom.Element('div'); - this.bodyKey = bodyDom.key; - bodyDom.addClass('nd-tab-body'); - if (this.bodyHeight > 0) { - bodyDom.assets.set('style', 'height:' + this.bodyHeight + 'px'); - } - let index = 1; - let activeIndex = 0; - let itemDom; - for (let c of rootDom.children) { - if (!c.tagName) { - continue; - } - let tabName = 'Tab' + index++; - let title = c.getProp('title') || tabName; - let active = c.getProp('active') || false; - if (active) { - activeIndex = index; - } - this.tabs.push({ title: title, name: tabName, active: active }); - let contentDom = new nodom.Element('div'); - contentDom.children = c.children; - contentDom.addDirective(new nodom.Directive('show', this.extraDataName + '.' + tabName, contentDom)); - bodyDom.add(contentDom); - if (itemDom) { - continue; - } - c.tagName = 'div'; - c.delProp(['title', 'active', 'name']); - c.addClass('nd-tab-item'); - let txt = new nodom.Element(); - txt.expressions = [new nodom.Expression('title')]; - c.children = [txt]; - if (this.allowClose) { - let b = new nodom.Element('b'); - b.addClass('nd-tab-close'); - b.addEvent(new nodom.NodomEvent('click', ':nopopo', (dom, model, module) => { - me.delTab(model.data.name, module); - })); - c.add(b); - } - c.addDirective(new nodom.Directive('repeat', this.extraDataName + '.datas', c)); - c.addDirective(new nodom.Directive('class', "{'nd-tab-item-active':'active'}", c)); - c.addEvent(new nodom.NodomEvent('click', (dom, model, module) => { - me.setActive(model.data.name, module); - })); - itemDom = c; - } - headDom.add(itemDom); - if (activeIndex === 0 && this.tabs.length > 0) { - this.tabs[0].active = true; - } - if (this.position === 'top' || this.position === 'left') { - rootDom.children = [headDom, bodyDom]; - } - else { - rootDom.children = [bodyDom, headDom]; - } - } - beforeRender(module, dom) { - super.beforeRender(module, dom); - let pmodel; - if (this.needPreRender) { - pmodel = module.modelFactory.get(this.modelId); - let data = { - datas: this.tabs - }; - for (let d of this.tabs) { - data[d.name] = d.active; - } - this.bodyKey = dom.children[1].key; - this.extraModelId = pmodel.set(this.extraDataName, data).id; - } - } - addTab(cfg) { - let module = nodom.ModuleFactory.get(this.moduleId); - if (!module) { - return; - } - let model = module.modelFactory.get(this.extraModelId); - let index = nodom.Util.isNumber(cfg.index) ? cfg.index : model.data.datas.length; - let tabName = cfg.name || ('Tab' + nodom.Util.genId()); - model.data.datas.splice(index, 0, { - title: cfg.title, - name: tabName, - active: false - }); - model.set(tabName, false); - let bodyDom = module.virtualDom.query(this.bodyKey); - let dom; - if (cfg.content) { - dom = nodom.Compiler.compile(cfg.content); - } - else if (cfg.module) { - dom = new nodom.Element('div'); - let mdlStr = cfg.module; - if (cfg.moduleName) { - mdlStr += '|' + cfg.moduleName; - } - dom.addDirective(new nodom.Directive('module', mdlStr, dom)); - if (cfg.data) { - dom.setProp('data', cfg.data); - } - } - dom.addDirective(new nodom.Directive('show', this.extraDataName + '.' + tabName, dom)); - bodyDom.children.splice(index, 0, dom); - if (cfg.active) { - this.setActive(tabName, module); - } - } - delTab(tabName, module) { - if (!module) { - module = nodom.ModuleFactory.get(this.moduleId); - } - let pmodel = module.modelFactory.get(this.extraModelId); - let datas = pmodel.data.datas; - let activeIndex; - if (datas.length === 1) { - return; - } - for (let i = 0; i < datas.length; i++) { - if (datas[i].name === tabName) { - if (datas[i].active) { - if (i < datas.length - 1) { - activeIndex = i; - } - else { - activeIndex = 0; - } - } - datas.splice(i, 1); - pmodel.del(tabName); - let bodyDom = module.virtualDom.query(this.bodyKey); - bodyDom.children.splice(i, 1); - break; - } - } - if (activeIndex !== undefined) { - this.setActive(datas[activeIndex].name, module); - } - } - setActive(tabName, module) { - if (!module) { - module = nodom.ModuleFactory.get(this.moduleId); - } - let pmodel = module.modelFactory.get(this.extraModelId); - let datas = pmodel.data.datas; - let activeData; - for (let o of datas) { - if (o.active) { - pmodel.data[o.name] = false; - o.active = false; - } - if (o.name === tabName) { - activeData = o; - } - } - activeData.active = true; - pmodel.data[tabName] = true; - } -} -nodom.PluginManager.add('UI-TAB', UITab); -class UITip extends nodom.Plugin { - constructor(params) { - super(params); - this.tagName = 'UI-TIP'; - this.needCheck = false; - this.containers = { - top: undefined, - right: undefined, - bottom: undefined, - left: undefined - }; - let rootDom = new nodom.Element(); - if (params) { - if (params instanceof HTMLElement) { - nodom.Compiler.handleAttributes(rootDom, params); - } - else if (typeof params === 'object') { - for (let o in params) { - this[o] = params[o]; - } - } - this.generate(rootDom); - } - rootDom.tagName = 'div'; - rootDom.plugin = this; - this.element = rootDom; - } - generate(rootDom) { - rootDom.tagName = 'div'; - this.extraDataName = '$ui_tip_manager'; - rootDom.setProp('name', this.extraDataName); - rootDom.addDirective(new nodom.Directive('model', this.extraDataName, rootDom)); - for (let loc of ['top', 'right', 'bottom', 'left']) { - let ct = new nodom.Element('div'); - ct.addClass('nd-tip nd-tip-' + loc); - ct.add(this.createTipDom(loc)); - rootDom.add(ct); - } - } - beforeRender(module, dom) { - super.beforeRender(module, dom); - if (this.needPreRender) { - let model = module.model; - if (!model.get(this.extraDataName)) { - let mdl = model.set(this.extraDataName, { - top: [], - left: [], - bottom: [], - right: [] - }); - this.modelId = mdl.id; - } - } - } - createTipDom(loc) { - let me = this; - let dom = new nodom.Element('div'); - dom.addDirective(new nodom.Directive('repeat', loc, dom)); - dom.setProp('class', new nodom.Expression("'nd-tip-item nd-box-' + theme"), true); - let close = new nodom.Element('b'); - close.addClass('nd-tip-close'); - close.addDirective(new nodom.Directive('show', 'allowClose', close)); - close.addEvent(new nodom.NodomEvent('click', (dom, model, module, e) => { - model.set('close', true); - me.check(true); - })); - let contentDom = new nodom.Element('div'); - contentDom.addClass('nd-tip-content'); - let icon = new nodom.Element('b'); - icon.setProp('class', new nodom.Expression("'nd-icon-' + icon"), true); - icon.addDirective(new nodom.Directive('show', 'icon', icon)); - let txt = new nodom.Element(); - txt.expressions = [new nodom.Expression('content')]; - contentDom.children = [txt]; - dom.children = [icon, contentDom, close]; - return dom; - } - check(force) { - let me = this; - if (force) { - this.needCheck = true; - } - if (!this.needCheck || !this.modelId) { - return; - } - let needCheck = false; - let model = nodom.ModuleFactory.getMain().modelFactory.get(this.modelId); - let ct = new Date().getTime(); - for (let loc of ['top', 'right', 'bottom', 'left']) { - let data = model.data[loc]; - for (let i = 0; i < data.length; i++) { - let d = data[i]; - if (d.close || !d.allowClose && d.start + d.time <= ct) { - data.splice(i--, 1); - } - else if (!d.allowClose && d.start + d.time > ct) { - needCheck = true; - } - } - } - this.needCheck = needCheck; - if (this.needCheck) { - setTimeout(() => { me.check(); }, 100); - } - } - show(config) { - if (!nodom.Util.isObject(config)) { - return; - } - let model = nodom.ModuleFactory.getMain().model.get(this.extraDataName); - if (!model) { - return; - } - let loc = config.loc || 'top'; - let allowClose = config.allowClose || false; - let datas = model.data[loc]; - let data = { - content: config.content || 'message', - time: config.time || 3000, - start: new Date().getTime(), - allowClose: allowClose, - icon: config.icon, - theme: config.theme || 'black' - }; - if (config.exclusive) { - for (let d of datas) { - datas.pop(); - } - datas.push(data); - } - else { - datas.push(data); - } - if (!allowClose) { - this.check(true); - } - } -} -nodom.PluginManager.add('UI-TIP', UITip); -var nodom; -(function (nodom) { - function tip(config) { - let module = nodom.ModuleFactory.getMain(); - if (!module) { - return null; - } - let manager = module.getPlugin('$ui_tip_manager'); - if (manager) { - manager.show(config); - } - } - nodom.tip = tip; -})(nodom || (nodom = {})); -class UIToolbar extends nodom.Plugin { - constructor(params) { - super(params); - this.tagName = 'UI-TOOLBAR'; - let rootDom = new nodom.Element(); - if (params) { - if (params instanceof HTMLElement) { - nodom.Compiler.handleAttributes(rootDom, params); - nodom.Compiler.handleChildren(rootDom, params); - } - else if (typeof params === 'object') { - for (let o in params) { - this[o] = params[o]; - } - } - } - rootDom.tagName = 'div'; - rootDom.addClass('nd-toolbar'); - rootDom.plugin = this; - this.element = rootDom; - } -} -nodom.PluginManager.add('UI-TOOLBAR', UIToolbar); -class UITree extends nodom.Plugin { - constructor(params) { - super(params); - this.tagName = 'UI-TREE'; - let rootDom = new nodom.Element(); - if (params) { - if (params instanceof HTMLElement) { - nodom.Compiler.handleAttributes(rootDom, params); - UITool.handleUIParam(rootDom, this, ['valuefield', 'displayfield', 'listfield', 'itemclick', 'checkname', 'maxlevel|number', 'icons|array|2'], ['valueField', 'displayField', 'listField', 'itemClick', 'checkName', 'maxLevel', 'iconArr'], ['', null, null, '', '', 3, []]); - } - else if (typeof params === 'object') { - for (let o in params) { - this[o] = params[o]; - } - } - this.generate(rootDom); - } - rootDom.tagName = 'div'; - rootDom.plugin = this; - this.element = rootDom; - } - generate(rootDom) { - const me = this; - rootDom.addClass('nd-tree'); - this.activeName = '$ui_tree_' + nodom.Util.genId(); - this.checkedChdNumName = '$ui_tree_' + nodom.Util.genId(); - let methodId = '$nodomGenMethod' + nodom.Util.genId(); - this.arrowClickId = methodId; - let closeOpenEvent = new nodom.NodomEvent('click', methodId + ':delg'); - let itemClickEvent; - if (this.itemClick !== '') { - itemClickEvent = new nodom.NodomEvent('click', this.itemClick + ':delg'); - } - let parentCt = rootDom; - let item; - for (let i = 0; i < this.maxLevel; i++) { - let itemCt = new nodom.Element(); - itemCt.tagName = 'div'; - itemCt.directives.push(new nodom.Directive('repeat', this.listField, itemCt)); - itemCt.addClass('nd-tree-nodect'); - item = new nodom.Element(); - item.addClass('nd-tree-node'); - item.tagName = 'DIV'; - if (itemClickEvent) { - item.addEvent(itemClickEvent); - } - let icon1 = new nodom.Element(); - icon1.tagName = 'SPAN'; - icon1.addClass('nd-tree-icon'); - icon1.addDirective(new nodom.Directive('class', "{'nd-tree-node-open':'" + this.activeName + "'," + - "'nd-icon-right':'" + this.listField + "&&" + this.listField + ".length>0'}", icon1)); - icon1.addEvent(closeOpenEvent); - itemCt.add(icon1); - if (this.iconArr.length > 0) { - let a = []; - a.push("'nd-icon-" + this.iconArr[0] + "':'" + this.listField + "&&" + this.listField + ".length>0'"); - if (this.iconArr.length > 1) { - a.push("'nd-icon-" + this.iconArr[1] + "':'!" + this.listField + "||" + this.listField + ".length===0'"); - } - let icon = new nodom.Element(); - icon.tagName = 'SPAN'; - icon.addClass('nd-tree-icon'); - let cls = '{' + a.join(',') + '}'; - icon.directives.push(new nodom.Directive('class', cls, icon)); - itemCt.add(icon); - } - if (this.checkName !== '') { - let cb = new nodom.Element('b'); - cb.addClass('nd-tree-uncheck'); - cb.addDirective(new nodom.Directive('class', "{'nd-tree-checked':'" + this.checkName + "'}", cb)); - itemCt.add(cb); - cb.addEvent(new nodom.NodomEvent('click', (dom, model, module, e) => { - me.handleCheck(model, module); - })); - } - itemCt.add(item); - let txt = new nodom.Element(); - txt.expressions = [new nodom.Expression(this.displayField)]; - item.add(txt); - let subCt = new nodom.Element(); - subCt.addClass('nd-tree-subct'); - subCt.tagName = 'DIV'; - subCt.addDirective(new nodom.Directive('class', "{'nd-tree-show':'" + this.activeName + "'}", subCt)); - itemCt.add(subCt); - parentCt.add(itemCt); - parentCt = subCt; - } - rootDom.plugin = this; - return rootDom; - } - beforeRender(module, uidom) { - const me = this; - super.beforeRender(module, uidom); - if (this.needPreRender) { - module.methodFactory.add(me.arrowClickId, (dom, model, module, e) => { - let pmodel = module.modelFactory.get(dom.modelId); - let rows = pmodel.data[me.listField]; - if (!rows || rows.length === 0) { - return; - } - model.set(me.activeName, !model.data[me.activeName]); - }); - } - } - handleCheck(model, module) { - let checked = !model.data[this.checkName]; - model.set(this.checkName, checked); - this.handleSubCheck(model, module, checked); - this.handleParentCheck(model, module, checked); - } - handleSubCheck(model, module, checked) { - let rows = model.data[this.listField]; - if (!rows) { - return; - } - if (checked) { - model.set(this.checkedChdNumName, rows.length); - } - else { - model.set(this.checkedChdNumName, 0); - } - for (let d of rows) { - let m = module.modelFactory.get(d.$modelId); - m.set(this.checkName, checked); - this.handleSubCheck(m, module, checked); - } - } - handleParentCheck(model, module, checked) { - let pmodel = model.parent; - if (!pmodel || pmodel === module.model) { - return; - } - pmodel = pmodel.parent; - if (!pmodel || pmodel === module.model) { - return; - } - let data = pmodel.data; - if (data[this.checkedChdNumName] === undefined) { - pmodel.set(this.checkedChdNumName, 0); - } - if (checked) { - data[this.checkedChdNumName]++; - } - else { - data[this.checkedChdNumName]--; - } - let chk = data[this.checkName]; - if (data[this.checkedChdNumName] === 0) { - pmodel.set(this.checkName, false); - } - else { - pmodel.set(this.checkName, true); - } - if (chk !== data[this.checkName]) { - this.handleParentCheck(pmodel, module, checked); - } - } - getValue() { - const me = this; - if (this.valueField === '') { - return; - } - let va = []; - let module = nodom.ModuleFactory.get(this.moduleId); - let model = module.modelFactory.get(this.modelId); - getChecked(model.data[this.listField]); - return va; - function getChecked(rows) { - if (Array.isArray(rows)) { - for (let d of rows) { - if (d[me.checkName] === true) { - va.push(d[me.valueField]); - } - getChecked(d[me.listField]); - } - } - } - } -} -nodom.PluginManager.add('UI-TREE', UITree); \ No newline at end of file diff --git a/test/pages/js/tclass.js b/test/pages/js/tclass.js deleted file mode 100644 index e779049e61d4e2422ce00b09d0409647ecec02b9..0000000000000000000000000000000000000000 --- a/test/pages/js/tclass.js +++ /dev/null @@ -1,13 +0,0 @@ -// "use strict"; -// Object.defineProperty(exports, "__esModule", { value: true }); -class tclass { - constructor(param){ - this.param = param; - // console.log(param); - } - sayHello(){ - console.log(this.param); - } - -} -exports.tclass = tclass; diff --git a/test/pages/js/test.js b/test/pages/js/test.js deleted file mode 100644 index 07567e831ea35d3edd4650aa42c5f8537e003895..0000000000000000000000000000000000000000 --- a/test/pages/js/test.js +++ /dev/null @@ -1,24 +0,0 @@ - -const fs = require('fs'); -let mime = require('mime'); -// var bitmap = fs.readFileSync('../imgs/homebg.png'); -var bitmap = fs.readFileSync('./nodomui.js'); -let buf1 = Buffer.from(bitmap,'base64'); -fs.writeFileSync('./jpg1',buf1); - -const zip = require('zlib'); -let s1 = zip.deflateSync(buf1); -console.log(s1.length,buf1.length); - -// console.log(s1.toString('hex')); -// let s2 = zip -//创建压缩管道 -// await pipeline(fs.createReadStream(path),zipTool,App.fs.createWriteStream(tmpFn)); -// let buf = Buffer.from(s,'ascii'); -// let s1 = buf.toString('ascii'); -// let buf1 = Buffer.from(s1,'ascii') -// for(let i=0;i - - - - - - - - - Document - - - -

test

-
-
类型:
-
姓名:
-
- - - - \ No newline at end of file diff --git a/test/pages/test1.html b/test/pages/test1.html deleted file mode 100644 index 11309735f2d241a5fa1c2f7df9068691c07cefce..0000000000000000000000000000000000000000 --- a/test/pages/test1.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - Document - - -

测试跳转页面332

- - \ No newline at end of file diff --git a/test/pages/testModel.html b/test/pages/testModel.html deleted file mode 100644 index bebb5b7a585b76990574fc49e7ad75b03e990619..0000000000000000000000000000000000000000 --- a/test/pages/testModel.html +++ /dev/null @@ -1,47 +0,0 @@ - - - - - - - noomi-testmodel - - - - -

-

-

-

-

-

-

- - - - - - \ No newline at end of file diff --git a/test/pages/upload.html b/test/pages/upload.html deleted file mode 100644 index 268e8eae98a089169434327821ba37bdcb051f28..0000000000000000000000000000000000000000 --- a/test/pages/upload.html +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - -
-
- 用户名: -
-
- 出生日期: -
-
- 头像: -
-
- 描述: -
- -
- - - - \ No newline at end of file diff --git a/test/pages/upload1.html b/test/pages/upload1.html deleted file mode 100644 index ad5c4d38cff1bf5317001b49f8a6c54b5c76e903..0000000000000000000000000000000000000000 --- a/test/pages/upload1.html +++ /dev/null @@ -1,64 +0,0 @@ - - - - - - - - - -
-
- 用户名: -
-
- 出生日期: -
-
- 头像: -
-
- 描述: -
- -
- - - - - \ No newline at end of file diff --git a/test/pages/video.html b/test/pages/video.html deleted file mode 100644 index e24df9405a04722eb974c549e29788ad29d1b4fb..0000000000000000000000000000000000000000 --- a/test/pages/video.html +++ /dev/null @@ -1,38 +0,0 @@ - - - - - noomi-视频测试 - - - - -
    - - - - - - 下载1.zip - - - diff --git a/test/pages/videos/1.mp4 b/test/pages/videos/1.mp4 deleted file mode 100644 index 0e0833a3278f6e22f1916e464e6fb8eac820906d..0000000000000000000000000000000000000000 Binary files a/test/pages/videos/1.mp4 and /dev/null differ diff --git a/test/pages/videos/2.mp4 b/test/pages/videos/2.mp4 deleted file mode 100644 index 9b8c24dd7a5d3d76068a269f6c528b301916813d..0000000000000000000000000000000000000000 Binary files a/test/pages/videos/2.mp4 and /dev/null differ diff --git a/test/pages/videos/3.mp4 b/test/pages/videos/3.mp4 deleted file mode 100644 index 8d955a2427f804db7ccc1711da56db1dc926055c..0000000000000000000000000000000000000000 Binary files a/test/pages/videos/3.mp4 and /dev/null differ diff --git a/test/pages/videos/5.mp4 b/test/pages/videos/5.mp4 deleted file mode 100644 index d99098c5ef3f678876524efea8da6b6b95617434..0000000000000000000000000000000000000000 Binary files a/test/pages/videos/5.mp4 and /dev/null differ diff --git a/test/test1.js b/test/test1.js deleted file mode 100644 index 4e1ddb65a38279a046b088c57b804435d3b43feb..0000000000000000000000000000000000000000 --- a/test/test1.js +++ /dev/null @@ -1,63 +0,0 @@ -class PCls{ - __props=1; - - constructor(){ - this.__props = new Map(); - } - - addProp(name,value){ - // this.__props.set(name,value); - this.constructor.setProp(name,value); - } - - showProp(){ - // for(let p of this.__props){ - // console.log(p); - // } - for(let p of this.constructor.props){ - console.log(p); - } - } -} - -/*PCls.setProp = function(name,value){ - - if(!this.props){ - this.props = new Map(); - } - this.props.set(name,value); -} - -PCls.showProp = function(name){ - if(!this.props){ - return; - } - for(let p of this.props){ - console.log(p); - } -} - -class Cls1 extends PCls{ - -} - -class Cls2 extends PCls{ - -} - -let p1 = new Cls1(); -p1.addProp('a',1); -p1.showProp(); - -let p2 = new Cls2(); -p2.addProp('b',2); -p2.showProp(); */ -for(let o in PCls.prototype){ - console.log(o); -} -console.log(Object.getOwnPropertyNames(PCls.prototype)); -// p1.showProp(); -// p2.showProp(); - -// console.log(p1.constructor.props); -// console.log(p2.constructor.props); \ No newline at end of file diff --git a/tsconfig.json b/tsconfig.json index 833e6da08a496cdec0e609237ae15e118e8bf83d..c1e4e02f949e333cb3d20ed2c924a0ea249dd12b 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,19 +1,19 @@ { - "compilerOptions": { - "module":"commonjs", - "target": "es2017", - "sourceMap": true, - "experimentalDecorators": true, - "emitDecoratorMetadata": true, - "outDir":"./dist", - // "declaration": true, - // "declarationDir":"./dist/types", - // "noUnusedParameters":false - }, - "include":[ - "**/*.ts" - ], - "exclude": [ - "./index.ts" - ] -} \ No newline at end of file + "compilerOptions": { + "module":"commonjs", + "target": "es2017", + "sourceMap": true, + "experimentalDecorators": true, + "emitDecoratorMetadata": true, + "outDir":"./dist", + // "declaration": true, + // "declarationDir":"./dist/types", + // "noUnusedParameters":false + }, + "include":[ + "**/*.ts" + ], + "exclude": [ + "./index.ts" + ] + } \ No newline at end of file