import { Component, OnInit, Input, Output, EventEmitter, Injector, Optional, OnChanges } from '@angular/core'; import { ExpressionEventService } from '../utils/expression-event-service'; import { VarType } from '../expression-var-grid/vartype'; import { NotifyService } from '@farris/ui-notify'; import { GspCommonDataType, GSPCommonObject } from '@gsp-bef/gsp-cm-metadata'; import { HttpClient } from "@angular/common/http"; import { ExpressionEditorLocalePipe } from '../utils/expression-editor-locale.pipe'; import { I18nFunctions } from '../i18n/I18nFunctions'; import { NewEntitySet, NewSchema } from '../common/NewSchema'; import { CheckContext, checkFunctionParams, checkEntityStruct, checkVariable } from '../checkSyntax/CheckExpress'; import { buildVariable, buildNewSchemaEntityStruct, buildSchemaEntityStruct } from "../checkSyntax/SchemaToStruct"; import { MessagerService } from '@farris/ui-messager'; import { SyntaxCheckError, TranslateSyntaxCheckError } from '../checkSyntax/ExpressError'; import { DeprecatedFunctions, CurrLanguageVariable } from "../common/CommonResource"; import { AdvancedCheckResult, CurrentNode, CustomizedSetting, DataArea, ExpressionContextEntity, ExpressionEntity, ExtendFunction, FunctionEntity, FuncType, InjectedEntity, InjectedType, SmartHelpEntity, VarEntity } from '../common/CommonEntity'; import { EntitySet, Schema } from '../common/Schema'; import { Adapter } from '../utils/adapter'; import { CommonUtils } from "../utils/CommonUtils"; @Component({ selector: 'app-expressioneditor', templateUrl: './expressioneditor.component.html', styleUrls: ['./expressioneditor.component.css'] }) export class ExpressioneditorComponent implements OnInit, OnChanges { //定义i18n标识 private localeId: string; private localePipe: ExpressionEditorLocalePipe; //定义国际化资源名称 Advanced: string; String: string; Analytical: string; Translate: string; Math: string; DateTime: string; Extend: string; Variable: string; Entity: string; Help: string; FunctionDescription: string; VarDescription: string; CurrentProp: string; CurrentChosedProp: string; HelpButtonDesc: string; PopverTitleDesc: string; //提示服务 private notifyService: NotifyService; private messageService: MessagerService; private functions: I18nFunctions = new I18nFunctions(); constructor(private eventService: ExpressionEventService, @Optional() private injector: Injector, public http: HttpClient) { if (this.injector) { this.notifyService = this.injector.get(NotifyService); this.messageService = this.injector.get(MessagerService); this.http = this.injector.get(HttpClient); this.localeId = localStorage.getItem('languageCode'); this.localePipe = new ExpressionEditorLocalePipe(this.localeId); } //初始化i18n函数 this.allFunctions = this.functions.get(this.localeId) || this.functions.get("zh-CHS"); //变量 this.variableFuncNames = []; for (let func of this.allFunctions) { if (CommonUtils.variableFuncKeys.includes(func.key)) { this.variableFuncNames.push(func.keyFront + "." + func.key); if (this.variableFuncNames.length == 2) break; } } } //静态资源 private functionSuffixs = ["DefaultFunction", "Math", "DefaultExtendFunctionProxy"]; //定义 private notifies = { //消息提示 1: { type: 'success', msg: '表达式生成!' }, 2: { type: 'warning', msg: '请确保必填项填写完整!' }, 3: { type: 'success', msg: '语法校验通过!' }, 4: { type: 'warning', msg: '' } }; options = { //编辑器的基本参数 // theme: 'vs-light', language: 'javascript', automaticLayout: true, minimap: { enabled: false }, //关闭右侧代码预览 // lineNumbers: 'off', //关闭代码行数提示 readOnly: false, fontSize: '14px' }; private ScriptType = "text/javascript"; private EsprimaScriptSrc = "/platform/common/web/@gsp-svc/esprima/dist/esprima.js?"; @Input() readOnly: boolean = false; //编辑器是否只读 @Input() funcExtend: FunctionEntity[] = []; //扩展函数实体 @Input() expressionEntity: ExpressionContextEntity = new ExpressionContextEntity;//表达式内部上下文 @Input() contextEntities: VarEntity[] = []; @Input() sessionEntities: VarEntity[] = []; @Input() injectedEntities: InjectedEntity[] = []; @Input() smartHelp: SmartHelpEntity[] = []; //以下为面板式 @Input() text: string; @Input() isPanel: boolean = false; @Input() funcEntities: FunctionEntity[] = []; @Input() extendFuncEntities: ExtendFunction[] = []; @Input() gspCDTs: GspCommonDataType[] = []; @Input() commonObjects: GSPCommonObject[] = []; @Input() customSchemaName: string; @Input() customSchema: Schema; @Input() injectName: string; @Input() injectSchemaName: string = "CommonObject"; @Input() injectNameInSchema: string; @Input() injectedType: InjectedType = InjectedType.EntityType; @Input() customNewSchemaName: string; @Input() customNewSchema: NewSchema; @Input() windowWidth: number = 1000; @Input() setting: CustomizedSetting = new CustomizedSetting(); //表达式定制设置 @Output() result = new EventEmitter(); @Output() closeModalEmitter = new EventEmitter(); isReturnSyntax: boolean = false; //是否为return语法 selectnewfunc: boolean = false; selectedResource = false; currentFuncTabType: string = "String"; //函数类型(默认string) currentVarType: VarType = VarType.Context; //变量类型(默认Context) expressioninfo: string; //表达式临时文本 code: string; //编辑器显示文本绑定 descriptinfo: string = ""; //函数说明 standardFunctions = []; //规范函数 allFunctions = []; //所有函数,包含不规范 variableFuncNames: string[] = []; //上下文变量、会话变量函数的当前语言name schema = new Map(); //schema映射表 newSchemaMap = new Map(); //newSchema映射表 choseSchemaTableName: CurrentNode = new CurrentNode; //选择schema、entity中的表名 adapter: Adapter = new Adapter(); DataArea_DefaultSelectString: string; //数据区域默认选中tab页 ngOnInit() { //加载Esprima let esprima = this.loadEsprima(); if (esprima != null) esprima.onload = function () { console.log("Esprima加载完成...") } this.options.readOnly = this.readOnly; //重新加载时重设是否只读 //初始化frame i18n资源 this.Advanced = this.localePipe.transform("Advanced"); this.String = this.localePipe.transform("String"); this.Analytical = this.localePipe.transform("Analytical"); this.Translate = this.localePipe.transform("Translate"); this.Math = this.localePipe.transform("Math"); this.DateTime = this.localePipe.transform("DateTime"); this.Extend = this.localePipe.transform("Extend"); this.Variable = this.localePipe.transform("Variable"); this.Entity = this.localePipe.transform("Entity"); this.Help = this.localePipe.transform("Help"); this.FunctionDescription = this.localePipe.transform("FunctionDescription"); this.VarDescription = this.localePipe.transform("VarDescription"); this.CurrentProp = this.localePipe.transform("CurrentProp"); this.CurrentChosedProp = this.localePipe.transform("CurrentChosedProp"); this.PopverTitleDesc = this.localePipe.transform("PopverTitleDesc"); this.HelpButtonDesc = this.localePipe.transform("HelpButtonDesc"); //过滤不规范命名函数 for (let i = 0; i < this.allFunctions.length; i++) { if (!DeprecatedFunctions.includes(this.allFunctions[i].key)) { this.standardFunctions.push(this.allFunctions[i]); } } //数据区域默认选中tab页 this.selectDataArea(this.setting.DataArea_DefaultSelect); //区分:弹出框or面板 if (this.isPanel) { this.OninitPanel(); } else { this.OninitWindows(); } } ngOnChanges() { this.options.readOnly = this.readOnly; //重新加载时重设是否只读 this.selectDataArea(this.setting.DataArea_DefaultSelect);//数据区域默认选中tab页 if (this.isPanel) { this.OninitPanel(); } } //弹出框式 private OninitWindows() { //表达式文本实体有值则重新赋值 if (this.expressionEntity && this.expressionEntity.expr && this.expressionEntity.expr.length > 0) { this.code = this.expressionEntity.expr; } else { this.code = null; } //初始化扩展函数;扩展函数加入到standardFunctions中 this.funcExtend = []; this.expressionEntity.functionEntities.forEach(functionEntity => { if (!this.allFunctions.includes(functionEntity)) { this.funcExtend.push(functionEntity); } }); if (this.funcExtend.length > 0) { this.funcExtend.forEach(item => { if (!this.standardFunctions.includes(item) && !item.isLatestExtendFunc) { this.standardFunctions.push(item); } //扩展函数KeyFront加入this.functionSuffixs if (!this.functionSuffixs.includes(item.keyFront) && !item.isLatestExtendFunc) { this.functionSuffixs.push(item.keyFront); } }) } //初始化上下文变量、会话变量 this.expressionEntity.contextEntities.forEach(entity => { this.contextEntities.push(entity); }); this.expressionEntity.sessionEntities.forEach(entity => { this.sessionEntities.push(entity); }); //初始化Schema、NewSchema、InjectedEntity this.schema = this.expressionEntity.schemaMap; this.newSchemaMap = this.expressionEntity.newSchemaMap; this.injectedEntities = this.expressionEntity.injectedEntities; //初始化SmartHelp列表 this.smartHelp = this.expressionEntity.smartHelpEntities; } //面板式 private OninitPanel() { //初始化Schema if (this.customNewSchemaName && this.customNewSchema) { //注入NewSchema this.newSchemaMap.set(this.customNewSchemaName, this.customNewSchema); if (this.injectName && this.injectNameInSchema && this.injectSchemaName) { //去重 this.injectedEntities = this.injectedEntities.filter(item => item.schemaName !== this.injectSchemaName); //构造注入实体对象 let injectedEntity = new InjectedEntity(); //若注入的实体名为空,则默认为注入实体在newSchema中的名称 injectedEntity.name = this.injectName ? this.injectName : this.injectNameInSchema; injectedEntity.schemaName = this.injectSchemaName; injectedEntity.injectedName = this.injectNameInSchema; injectedEntity.injectedType = this.injectedType; this.injectedEntities.push(injectedEntity); } if (this.gspCDTs && this.gspCDTs.length > 0) { let innerSchema = new NewSchema(); //若newSchemaMap中存在CDT的schema if (this.newSchemaMap.get("CDT")) { innerSchema = this.newSchemaMap.get("CDT"); } //将每一个CDT转化为newSchema内部结构中的entityType this.gspCDTs.forEach(gspCDT => { let entityType = this.adapter.convertCDTOfNewSchema(gspCDT); innerSchema.entityTypes = innerSchema.entityTypes.filter(item => item.code !== entityType.code); innerSchema.entityTypes.push(entityType); }); //将合并后的newSchema放入内部上下文实体中 this.newSchemaMap.set("CDT", innerSchema); } if (this.commonObjects && this.commonObjects.length > 0) { let innerSchema = new NewSchema;; //若newSchemaMap中存在CO的newSchema if (this.newSchemaMap.get("CommonObject")) { innerSchema = this.newSchemaMap.get("CommonObject"); } this.commonObjects.forEach(co => { //将每一个CO转化为schema内部结构中的entityType let entityTypes = this.adapter.convertCOOfNewSchema(co); entityTypes.forEach(entityType => { innerSchema.entityTypes = innerSchema.entityTypes.filter(item => item.code !== entityType.code); innerSchema.entityTypes.push(entityType); let entitySet = new NewEntitySet; entitySet.code = entityType.code + "s"; entitySet.name = entityType.name; entitySet.entityType = entityType.code; innerSchema.entitySets = innerSchema.entitySets.filter(item => item.code !== entitySet.code); innerSchema.entitySets.push(entitySet); }); }) //将合并后的newSchema放入内部上下文实体中 this.newSchemaMap.set("CommonObject", innerSchema); } } else if (this.customSchemaName && this.customSchema) { //注入旧Schema对象 this.schema.set(this.customSchemaName, this.customSchema); if (this.injectName && this.injectNameInSchema && this.injectSchemaName) { this.injectedEntities = this.injectedEntities.filter(item => item.injectedName !== this.injectName); //构造注入实体对象 let injectedEntity = new InjectedEntity(); //若注入的实体名为空,则默认为注入实体在schema中的名称 injectedEntity.name = this.injectName ? this.injectName : this.injectNameInSchema; injectedEntity.schemaName = this.injectSchemaName; injectedEntity.injectedName = this.injectNameInSchema; injectedEntity.injectedType = this.injectedType; this.injectedEntities.push(injectedEntity); } if (this.gspCDTs && this.gspCDTs.length > 0) { let innerSchema = new Schema(); //若schemaMap中存在CDT的schema if (this.schema.get("CDT")) { innerSchema = this.schema.get("CDT"); } //将每一个CDT转化为schema内部结构中的entityType this.gspCDTs.forEach(gspCDT => { let entityType = this.adapter.convertCDT(gspCDT); innerSchema.entityTypes = innerSchema.entityTypes.filter(item => item.id !== entityType.id); innerSchema.entityTypes.push(entityType); }); //将合并后的schema放入内部上下文实体中 this.schema.set("CDT", innerSchema); } //处理旧Schema的CO对象 if (this.commonObjects && this.commonObjects.length > 0) { let innerSchema = new Schema;; //若schemaMap中存在CO的schema if (this.schema.get("CommonObject")) { innerSchema = this.schema.get("CommonObject"); } this.commonObjects.forEach(co => { //将每一个CO转化为schema内部结构中的entityType let entityTypes = this.adapter.convertCO(co); entityTypes.forEach(entityType => { innerSchema.entityTypes = innerSchema.entityTypes.filter(item => item.id !== entityType.id); innerSchema.entityTypes.push(entityType); let entitySet = new EntitySet; entitySet.name = entityType.name + "s"; entitySet.entityType = entityType.name; entitySet.description = entityType.description; innerSchema.entitySets = innerSchema.entitySets.filter(item => item.name !== entitySet.name); innerSchema.entitySets.push(entitySet); }); }) //将合并后的schema放入内部上下文实体中 this.schema.set("CommonObject", innerSchema); } } //扩展函数过滤 if (this.funcEntities.length > 0) { this.funcEntities.forEach(element => { this.funcExtend = this.funcExtend.filter(item => item.key !== element.key); this.funcExtend.push(element); }); } if (this.extendFuncEntities.length > 0) { this.extendFuncEntities.forEach(element => { this.funcExtend = this.funcExtend.filter(item => item.key !== element.token); element.key = element.token; element.isLatestExtendFunc = true; element.type = FuncType.Extend; this.funcExtend.push(element); }); } //扩展函数加入到standardFunctions中 if (this.funcExtend.length > 0) { this.funcExtend.forEach(item => { if (!this.standardFunctions.includes(item) && !item.isLatestExtendFunc) { this.standardFunctions.push(item); } //allFunctions函数列表才是回显时用的 if (!this.allFunctions.includes(item) && !item.isLatestExtendFunc) { this.allFunctions.push(item); } //扩展函数KeyFront加入this.functionSuffixs if (!this.functionSuffixs.includes(item.keyFront) && !item.isLatestExtendFunc) { this.functionSuffixs.push(item.keyFront); } }) } //初始化预置上下文变量(当前语言) this.contextEntities = this.contextEntities.filter(item => item.key != CurrLanguageVariable.key); this.contextEntities.splice(0, 0, CurrLanguageVariable); //预置编辑框显示值 let obj = JSON.parse(this.text ? this.text : null) as ExpressionEntity; if (obj && obj.expr) { //Antlr4分词获取tokens let tokens = CommonUtils.getTokens(obj.expr); //合并上下文变量、会话变量 let varMap = CommonUtils.getVariableMap(this.contextEntities, this.sessionEntities, "Key2Name"); //tokens解析为语义化文本 this.code = CommonUtils.toSemantic(tokens, this.allFunctions, varMap, this.functionSuffixs); } else { this.code = null } } //函数 //类型切换 funcTabChange($event) { this.currentFuncTabType = $event.nextId; this.eventService.subClearFuncSelect().subscribe(); this.selectnewfunc = false; //切换tabs时关闭函数描述 } //函数选中 selectFuncRowChange($event) { this.descriptinfo = this.FunctionDescription + "\n" + $event.description; this.eventService.clearVarSelect(); this.selectnewfunc = true; } /** * 双击插入函数 * @param $event * 1:判断是否为Advanced,如果是:直接获取对应的name插入;如果不是:获取对应的name,然后拼接参数 */ dbclickInsert($event) { //插入编辑框的语义化文本insertText let insertText = ""; if (!$event.data.isLatestExtendFunc) { //非扩展 insertText = $event.data.key; //根据$event.data.key找到函数的语义化名称 for (var index = 0; index < this.standardFunctions.length; index++) { if (insertText == this.standardFunctions[index].key) { insertText = this.standardFunctions[index].name; break; }; } //如果不是Advanced,拼接参数 if ($event.data.type != "Advanced") { insertText += "("; insertText += this.getParamText($event.data.params); insertText += ")"; } } else { //根据Invoke找到函数的语义化名称 for (var index = 0; index < this.standardFunctions.length; index++) { if ("Invoke" == this.standardFunctions[index].key) { insertText = this.standardFunctions[index].name; break; }; } //如果不是Advanced,拼接参数 insertText += "("; insertText += "\""; insertText += $event.data.key; insertText += "\","; insertText += this.getParamText($event.data.params); insertText += ")"; } this.eventService.insertExpression(insertText); } //返回函数参数的文本拼接形式 private getParamText(params: any) { let paramText = ""; for (let i = 0; i <= params.length - 1; i++) { if (params.length == 1) { //一个参数,无需添加逗号。参数类型为String则首尾追加"",其他直接添加 if (params[0].type == "string") { paramText += "\"" + params[0].name + "\""; } else if (params[0].type == "list") { paramText += "[" + params[0].name + "]"; } else { paramText += params[0].name; } } else { //多个参数,添加逗号分隔参数 if (i != params.length - 1) { //参数不是最后一位 if (params[i].type == "string") { paramText += "\"" + params[i].name + "\","; } else if (params[i].type == "list") { paramText += "[" + params[i].name + "],"; } else { paramText += params[i].name + ","; } } else { //参数是最后一位 if (params[i].type == "string") { paramText += "\"" + params[i].name + "\""; } else if (params[i].type == "list") { paramText += "[" + params[i].name + "]"; } else { paramText += params[i].name; } } } } return paramText; } //数据模型 //单击描述 selectentitychange($event) { this.choseSchemaTableName = $event; if ($event.nodeType == "Complex") { this.selectedResource = false; } else { this.selectedResource = false; } this.descriptinfo = this.CurrentProp + $event.name + "-->" + $event.description; } //双击插入 dbclickEntityInsert($event) { if ($event) { this.eventService.insertExpression($event); } } //变量 //类型切换 selectVarRowChange($event) { this.currentVarType = $event.id; } //单击描述 selectVarInfoRowChange($event) { this.descriptinfo = this.VarDescription + $event.description; this.eventService.clearFuncSelect(); } //双击插入 dbclickVarInsert($event) { if ($event) { //面板 let varMap = CommonUtils.getVariableMap(this.contextEntities, this.sessionEntities, "Key2Name"); switch (this.currentVarType) { case VarType.Context: for (let i = 0; i < this.standardFunctions.length; i++) { if (this.standardFunctions[i].key == "GetContextParameter") { this.eventService.insertExpression(this.standardFunctions[i].name + "(\"" + varMap.get($event.data.key) + "\")"); break; } } break; case VarType.Session: for (let i = 0; i < this.standardFunctions.length; i++) { if (this.standardFunctions[i].key == "GetSessionValue") { this.eventService.insertExpression(this.standardFunctions[i].name + "(\"" + varMap.get($event.data.key) + "\")"); break; } } break; default: break; } } } //智能帮助:双击(未使用) dbclickSmartHelpInsert($event) { if ($event) { this.eventService.insertExpression($event.data); } } //重置 reset() { this.expressioninfo = null; this.code = null; this.eventService.pushclearExpression(); } //##########################校验########################################## //语法校验 check(showError: boolean = true): Map { //校验上下文 let context = new CheckContext(); if ((window as any).esprima == null) { //加载esprima文件 let that = this; that.loadEsprima().onload = function () { let esprima = (window as any).esprima; try { let tokens = CommonUtils.getTokens(that.expressioninfo);//获取tokens that.checkSyntax(that, esprima, context, tokens);//语法校验 //错误提示 if (context.errors.length == 0) { if (showError) that.notifyService[that.notifies['3'].type]({ msg: that.notifies['3'].msg }); } else { return that.showErrorIfNecessary(showError, that.buildErrors(context.errors)); } } catch (err) {//捕获Esprima异常 that.handleEsprimaError(context.errors, err);//翻译Esprima异常 return that.showErrorIfNecessary(showError, that.buildErrors(context.errors)); } } } else { let esprima = (window as any).esprima; try { let tokens = CommonUtils.getTokens(this.expressioninfo);//获取tokens this.checkSyntax(this, esprima, context, tokens);//语法校验 //错误提示 if (context.errors.length == 0) { if (showError) this.notifyService[this.notifies['3'].type]({ msg: this.notifies['3'].msg }); } else { return this.showErrorIfNecessary(showError, this.buildErrors(context.errors)); } } catch (err) {//捕获Esprima异常 this.handleEsprimaError(context.errors, err);//翻译Esprima异常 return this.showErrorIfNecessary(showError, this.buildErrors(context.errors)); } } } //展示异常信息 private showErrorIfNecessary(showError: boolean = true, errorMap: Map): Map { if (showError) this.messageService.error(errorMap.get("ErrorTitle"), errorMap.get("ErrorContent")); else return errorMap; } //加载esprima private loadEsprima() { if ((window as any).esprima == null) { var body = document.getElementsByTagName("body")[0]; var esprimaScript = document.createElement("script"); esprimaScript.type = this.ScriptType; esprimaScript.src = this.EsprimaScriptSrc + Date.now(); body.appendChild(esprimaScript); return esprimaScript; } } /** * 语法校验 * @param thisObj 当前对象 * @param esprima 语法解析对象 * @param context 校验上下文 * @param tokens 分词 */ private checkSyntax(thisObj: any, esprima: any, context: CheckContext, tokens: any[]) { //return语法,特殊处理 thisObj.isReturnSyntax = thisObj.judgeReturnSyntax(tokens); if (thisObj.isReturnSyntax) { esprima.parse("function test(){%s} \n test();".replace("%s", thisObj.expressioninfo)); } else { //Esprima进行校验 esprima.parse(thisObj.expressioninfo); } //校验上下文构造变量 buildVariable(context, thisObj.contextEntities, thisObj.sessionEntities); //校验上下文构造Schema结构 if (thisObj.newSchemaMap.size != 0 && thisObj.injectedEntities.length != 0) buildNewSchemaEntityStruct(context.entityStructs, thisObj.newSchemaMap, thisObj.injectedEntities); else if (thisObj.schema.size != 0 && thisObj.injectedEntities.length != 0) buildSchemaEntityStruct(context.entityStructs, thisObj.schema, thisObj.injectedEntities); //函数参数校验 checkFunctionParams(tokens, context.errors, thisObj.standardFunctions); //数据模型属性校验 checkEntityStruct(tokens, context, context.entityStructs); //变量校验 let names = []; let varMap = CommonUtils.getVariableMap(thisObj.contextEntities, thisObj.sessionEntities, "Key2Name"); varMap.forEach((key, value) => { names.push(key); names.push(value); }) checkVariable(tokens, context.errors, thisObj.standardFunctions, names); } /** * 校验:处理Esprima校验后异常 * @param errors * @param err */ private handleEsprimaError(errors: any[], err: any) { if (err.description == SyntaxCheckError.ILLEGAL) { err.description = err.description + "】-->【" + TranslateSyntaxCheckError.ILLEGAL; } else if (err.description.startsWith(SyntaxCheckError.Token)) { err.description = err.description + "】-->【" + TranslateSyntaxCheckError.Token; } else if (err.description == SyntaxCheckError.EndOfInpur) { err.description = err.description + "】-->【" + TranslateSyntaxCheckError.EndOfInpur; } let errorText = "在第" + err.lineNumber + "行,第" + err.column + "列出现错误,原因是【" + err.description + "】。请检查红色下划线以及附近语法是否正常!"; errors.push(errorText); } /** * 校验:组装异常信息 * @param errors 异常集合 * @returns 格式化后的异常 */ private buildErrors(errors: any[]): Map { let map = new Map(); let errorTitle = "存在" + errors.length + "个异常,详细信息如下:"; let errorContent = ""; errors.forEach((er, index) => { if (index == errors.length) errorContent = errorContent + "异常" + (index + 1) + ":" + er; else errorContent = errorContent + "异常" + (index + 1) + ":" + er + "
"; }) map.set("ErrorTitle", errorTitle); map.set("ErrorContent", errorContent); return map; } /** * 校验:判断是否为return语法 * @param textTokens tokens列表 * @returns boolean */ private judgeReturnSyntax(textTokens: any[]): boolean { for (let i = 0; i < textTokens.length; i++) { if (textTokens[i] == "return") return true; } return false; } //#################################外部使用接口###################################### /** * 获取表达式返回值(弹出框用) */ public getExprs() { this.result.emit(this.getExpr()); } /** * 获取表达式返回值(面板用) * @returns 表达式返回值 */ public getExpr() { if (this.expressioninfo == null || this.expressioninfo == "") { return null; } else { //表达式文本返回实体 let exprEntity: ExpressionEntity = { expr: this.expressioninfo, sexpr: this.expressionEntity.sexpr }; //expr不为空,Antlr4解析获取tokens let tokens = CommonUtils.getTokens(exprEntity.expr); //合并上下文变量、会话变量 let varMap = CommonUtils.getVariableMap(this.contextEntities, this.sessionEntities, "Name2Key"); //语义化文本解析为表达式串 for (let index = 0; index < tokens.length; index++) { let num = 0; //遍历变量 if (num == 0) { if (tokens[index].length > 2 && tokens[index][0] == "\"" && tokens[index][tokens[index].length - 1] == "\"") { //校验第0位和第length-1位是否是" let temp = tokens[index].substring(1, tokens[index].length - 1); //此处需要DefaultFunction.GetContextParameter、DefaultFunction.GetSessionValue if (varMap.has(temp) && tokens[index - 1] == "(" && tokens[index + 1] == ")" && this.variableFuncNames.includes(tokens[index - 2])) { tokens[index] = "\"" + varMap.get(temp) + "\""; num = 1; } } } //遍历函数 if (num == 0) { for (let indexTok = 0; indexTok < this.standardFunctions.length; indexTok++) { if (tokens[index] == this.standardFunctions[indexTok].name) { tokens[index] = this.standardFunctions[indexTok].keyFront + '.' + this.standardFunctions[indexTok].key; num = 1; break; }; } } } //合并 let temp = ""; for (let index = 0; index < tokens.length; index++) { temp = temp + tokens[index]; } exprEntity.expr = temp; return JSON.stringify(exprEntity); } } /** * 带校验的表达式保存(面板用) * @returns Promise */ public getExprWithCheck(): Promise { let that = this; return new Promise( function (resolve) { let advancedResult: AdvancedCheckResult = { closeable: true, expression: null } if (that.expressioninfo == null || that.expressioninfo == "") { return resolve(advancedResult); } else { let errorMap = that.check(false); //校验失败进行提示 if (errorMap != null) { that.messageService.confirm("可能存在的语法问题如下,是否仍保存?", errorMap.get("ErrorContent"), true).subscribe(res => { advancedResult.closeable = res; advancedResult.expression = that.getExpr(); return resolve(advancedResult); }) } else { advancedResult.closeable = true; advancedResult.expression = that.getExpr(); return resolve(advancedResult); } } }); } /** * 外部校验方法 * @returns Promise 语法错误信息,无语法错误返回null */ public checkExpression(): Promise { let that = this; return new Promise( function (resolve) { let temp = that.check(false); temp != null ? resolve(temp.get("ErrorContent")) : resolve(null); } ); } //#################################按钮区域扩展###################################### hide() { this.selectnewfunc = false; } showMoreButton: boolean = false; //按钮区域展开 openButtonArea() { //展开更多按钮 if (this.showMoreButton == false) { this.showMoreButton = true; for (let i = 0; i < document.getElementsByClassName("expressupleft").length; i++) { (document.getElementsByClassName("expressupleft")[i] as HTMLElement).style.width = '71%'; } for (let i = 0; i < document.getElementsByClassName("expressupmiddle").length; i++) { (document.getElementsByClassName("expressupmiddle")[i] as HTMLElement).style.width = '18%'; } for (let i = 0; i < document.getElementsByClassName("expressextendText").length; i++) { (document.getElementsByClassName("expressextendText")[i] as HTMLElement).innerHTML = '>'; } } else { this.showMoreButton = false; for (let i = 0; i < document.getElementsByClassName("expressupleft").length; i++) { (document.getElementsByClassName("expressupleft")[i] as HTMLElement).style.width = '88%'; } for (let i = 0; i < document.getElementsByClassName("expressupmiddle").length; i++) { (document.getElementsByClassName("expressupmiddle")[i] as HTMLElement).style.width = '1%'; } for (let i = 0; i < document.getElementsByClassName("expressextendText").length; i++) { (document.getElementsByClassName("expressextendText")[i] as HTMLElement).innerHTML = '<'; } } } tabChange($event) { this.eventService.subClearVarSelect().subscribe(); } //####################################编辑器事件###################################### //编辑器初始化事件句柄 onInitHandler($event) { } //编辑器表达式改变事件句柄 onChangeHandler(event: any) { this.expressioninfo = event.data; } onTouchedHandler($event) { } //####################################按钮符号######################################## //#region 编辑符号方法 onPlus() { this.eventService.insertExpression(" + "); } onMinus() { this.eventService.insertExpression(" - "); } onMultiple() { this.eventService.insertExpression("*"); } onDivision() { this.eventService.insertExpression("/"); } onPercent() { this.eventService.insertExpression("%"); } onDoubleQuotation() { this.eventService.insertExpression("\"\""); } onEqual() { this.eventService.insertExpression(" == "); } onUnequal() { this.eventService.insertExpression(" != "); } onBrace() { this.eventService.insertExpression("[]"); } onSparen() { this.eventService.insertExpression("()"); } onOr() { this.eventService.insertExpression(" || "); } onAnd() { this.eventService.insertExpression(" && "); } onMoreequal() { this.eventService.insertExpression(" >= "); } onLessequal() { this.eventService.insertExpression(" <= "); } onLess() { this.eventService.insertExpression(" < "); } onMore() { this.eventService.insertExpression(" > "); } //####################################不重要函数####################################### //手动实时更改显示值 changeText(textii: string) { //预置编辑框显示值 let textEntity = JSON.parse(textii ? textii : null) as ExpressionEntity; if (textEntity && textEntity.expr) { this.code = textEntity.expr; } else { this.code = null } } changeInjectEntity(injectName: string, injectSchemaName: string = "CommonObject", injectNameInSchema: string, injectedType: InjectedType = InjectedType.EntityType) { if (injectName && injectNameInSchema && injectSchemaName) { //构造注入实体对象 let injectedEntity = new InjectedEntity(); //若注入的实体名为空,则默认为注入实体在schema中的名称 injectedEntity.name = injectName ? injectName : injectNameInSchema; injectedEntity.schemaName = injectSchemaName; injectedEntity.injectedName = injectNameInSchema; injectedEntity.injectedType = injectedType; this.expressionEntity.injectedEntities.push(injectedEntity); } this.injectedEntities = this.expressionEntity.injectedEntities; } changeCO(commonObjects: GSPCommonObject[]) { if (commonObjects && commonObjects.length > 0) { let schema; //若schemaMap中存在CO的schema if (this.expressionEntity.schemaMap.get("CommonObject")) { schema = this.expressionEntity.schemaMap.get("CommonObject"); } else schema = new Schema; commonObjects.forEach(co => { //将每一个CO转化为schema内部结构中的entityType let entityTypes = this.adapter.convertCO(co); entityTypes.forEach(entityType => { schema.entityTypes.push(entityType); let entitySet = new EntitySet; entitySet.name = entityType.name + "s"; entitySet.entityType = entityType.name; entitySet.description = entityType.description; schema.entitySets.push(entitySet); }); }) //将合并后的schema放入内部上下文实体中 this.schema.set("CommonObject", schema); } } changeContextVar(contextEntities: VarEntity[]) { contextEntities.forEach(item => { this.contextEntities = this.contextEntities.filter(item => item.key !== item.key); this.contextEntities.push(item); }); } //数据区域选中设置 private selectDataArea(select: DataArea) { switch (select) { case DataArea.DataModel: this.DataArea_DefaultSelectString = 'Entity'; break; case DataArea.Variable: this.DataArea_DefaultSelectString = 'Variable'; break; case DataArea.Help: this.DataArea_DefaultSelectString = 'Help'; break; default: this.DataArea_DefaultSelectString = 'Entity'; break; } } }