From cd2928c44c6a6ee9028e9a384e510f3a994ca453 Mon Sep 17 00:00:00 2001 From: chengongping Date: Tue, 21 Dec 2021 17:23:12 +0800 Subject: [PATCH] chengongping@huawei.com Signed-off-by: chengongping Change-Id: I22e687cb2dbdf09fd2914240344b49eb1e5b219f --- BUILD.gn | 74 +- LICENSE | 1 - OAT.xml | 32 + ace-loader/.npmignore | 3 +- ace-loader/main.product.js | 76 +- ace-loader/package-lock.json | 6 +- ace-loader/package.json | 2 +- ace-loader/plugin/codegen/index.js | 1000 ++++++++++------- .../plugin/templater/card_component_map.js | 2 + .../plugin/templater/component_validator.js | 38 +- ace-loader/src/cardJson-plugin.js | 4 +- ace-loader/src/compile-plugin.js | 73 +- ace-loader/src/extgen.js | 26 +- ace-loader/src/genAbc-plugin.js | 20 +- ace-loader/src/loader-gen.js | 18 +- ace-loader/src/resource-plugin.js | 86 +- ace-loader/src/resource-reference-script.js | 24 +- ace-loader/test/card/test.js | 24 +- .../testcase/pages/importLess/importLess.less | 3 +- .../test/lite/commandTest/compile.test.js | 2 +- ace-loader/test/lite/expected/attribute.js | 2 +- ace-loader/test/lite/expected/bubble.js | 2 +- ace-loader/test/lite/expected/class.js | 2 +- ace-loader/test/lite/expected/expression.js | 2 +- ace-loader/test/lite/expected/forDirective.js | 2 +- ace-loader/test/lite/expected/ifDirective.js | 2 +- ace-loader/test/lite/expected/inlineStyle.js | 2 +- ace-loader/test/rich/test.js | 24 +- .../test/rich/testcase/pages/class/class.js | 1 + .../testcase/pages/ifDirective/ifDirective.js | 15 + ace-loader/webpack.rich.config.js | 62 +- 31 files changed, 1022 insertions(+), 608 deletions(-) create mode 100644 OAT.xml diff --git a/BUILD.gn b/BUILD.gn index a416f8c..08d58a7 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -1,4 +1,15 @@ -# Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved. +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. import("//build/ohos.gni") import("//build/ohos/ace/ace.gni") @@ -73,19 +84,21 @@ action("build_ace_loader_library") { ] } +ace_loader_sources = [ + "ace-loader/.npmignore", + "ace-loader/babel.config.js", + "ace-loader/index.js", + "ace-loader/main.product.js", + "ace-loader/npm-install.js", + "ace-loader/package-lock.json", + "ace-loader/package.json", + "ace-loader/sample", + "ace-loader/webpack.lite.config.js", + "ace-loader/webpack.rich.config.js", +] + ohos_copy("ace_loader") { - sources = [ - "ace-loader/.npmignore", - "ace-loader/babel.config.js", - "ace-loader/index.js", - "ace-loader/main.product.js", - "ace-loader/npm-install.js", - "ace-loader/package-lock.json", - "ace-loader/package.json", - "ace-loader/sample", - "ace-loader/webpack.lite.config.js", - "ace-loader/webpack.rich.config.js", - ] + sources = ace_loader_sources outputs = [ target_out_dir + "/$target_name/{{source_file_part}}" ] module_source_dir = target_out_dir + "/$target_name/" module_install_name = "" @@ -101,14 +114,29 @@ ohos_copy("ace_loader_library") { license_file = "//third_party/weex-loader/NOTICE" } -# copy previewer -ohos_copy("previewer_copy") { - if (host_os == "mac") { - sources = [ "//prebuilts/previewer/darwin/previewer" ] - } else { - sources = [ "//prebuilts/previewer/windows/previewer" ] - } - outputs = [ target_out_dir + "/{{source_file_part}}" ] - module_source_dir = target_out_dir + "/previewer/" - module_install_name = "" +ace_loader_dir = + get_label_info(":ace_loader", "target_out_dir") + "/ace_loader_ark" + +ohos_copy("ace_loader_ark") { + sources = ace_loader_sources + outputs = [ target_out_dir + "/$target_name/{{source_file_part}}" ] + license_file = "//third_party/parse5/LICENSE" +} + +ohos_copy("ace_loader_ark_hap") { + deps = [ + ":ace_loader", + ":ace_loader_ark", + ":build_ace_loader_library", + ] + sources = [ ace_loader_lib_dir ] + outputs = [ ace_loader_dir + "/lib" ] + license_file = "//third_party/parse5/LICENSE" +} + +ohos_copy("ace_loader_node_modules") { + deps = [ ":ace_loader_ark_hap" ] + sources = [ "//developtools/ace-js2bundle/ace-loader/node_modules" ] + outputs = [ ace_loader_dir + "/node_modules" ] + license_file = "//third_party/parse5/LICENSE" } diff --git a/LICENSE b/LICENSE index 3fd0bc3..f433b1a 100644 --- a/LICENSE +++ b/LICENSE @@ -175,4 +175,3 @@ of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS - diff --git a/OAT.xml b/OAT.xml new file mode 100644 index 0000000..5e5aa03 --- /dev/null +++ b/OAT.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + diff --git a/ace-loader/.npmignore b/ace-loader/.npmignore index ad12608..53604b6 100644 --- a/ace-loader/.npmignore +++ b/ace-loader/.npmignore @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2020 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,7 +12,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - node_modules src test diff --git a/ace-loader/main.product.js b/ace-loader/main.product.js index 0075df8..36b123d 100644 --- a/ace-loader/main.product.js +++ b/ace-loader/main.product.js @@ -38,16 +38,71 @@ function deleteFolderRecursive(url) { function readManifest(manifestFilePath) { let manifest = {}; try { - const jsonString = fs.readFileSync(manifestFilePath).toString() - manifest = JSON.parse(jsonString) + if (fs.existsSync(manifestFilePath)) { + const jsonString = fs.readFileSync(manifestFilePath).toString(); + manifest = JSON.parse(jsonString); + } else if (process.env.aceConfigPath && fs.existsSync(process.env.aceConfigPath)) { + buildManifest(manifest, process.env.aceConfigPath); + } else { + throw Error('\u001b[31m' + 'ERROR: the manifest.json or config.json is lost.' + '\u001b[39m') + .message; + } } catch (e) { - throw Error('\u001b[31m' + 'ERROR: the manifest file is lost or format is invalid.' + '\u001b[39m').message + throw Error('\u001b[31m' + 'ERROR: the manifest.json or config.json file format is invalid.' + + '\u001b[39m').message; } return manifest; } + +function buildManifest(manifest, aceConfigPath) { + try { + const configJson = JSON.parse(fs.readFileSync(aceConfigPath).toString()); + const srcPath = process.env.srcPath; + manifest.type = process.env.abilityType; + manifest.pages = [] + if (manifest.type === 'form') { + if (configJson.module && configJson.module.abilities) { + manifest.pages = getForms(configJson, srcPath); + } else { + throw Error('\u001b[31m'+ + 'EERROR: the config.json file miss keyword module || module[abilities].' + + '\u001b[39m').message; + } + manifest.minPlatformVersion = configJson.app.apiVersion.compatible; + } + } catch (e) { + throw Error('\u001b[31m' + 'ERROR: the config.json file is lost or format is invalid.' + + '\u001b[39m').message; + } +} + +function getForms(configJson, srcPath) { + const pages = []; + for (const ability of configJson.module.abilities){ + if (ability.srcPath === srcPath) { + readForms(ability, pages); + break; + } + } + return pages; +} + +function readForms(ability, pages) { + if (ability.forms) { + for (const form of ability.forms){ + if (form.src) { + pages.push(form.src); + } + } + } else { + throw Error('\u001b[31m' +`ERROR: the ${ability} in config.json file miss forms.' + + '\u001b[39m`).message; + } +} + function loadEntryObj(projectPath, device_level, abilityType, manifestFilePath) { - let entryObj = {} + let entryObj = {}; switch (abilityType) { case 'page': const appJSPath = path.resolve(projectPath, 'app.js'); @@ -60,9 +115,13 @@ function loadEntryObj(projectPath, device_level, abilityType, manifestFilePath) entryObj['./app'] = path.resolve(projectPath, './app.js?entry'); } break; + case 'form': + entryObj = addPageEntryObj(readManifest(manifestFilePath), projectPath); + entryObj[`./${abilityType}`] = path.resolve(projectPath, `./${abilityType}.js?entry`); + break; default: - entryObj[`./${abilityType}`] = path.resolve(projectPath + `./${abilityType}.js?entry`); - break + entryObj[`./${abilityType}`] = path.resolve(projectPath, `./${abilityType}.js?entry`); + break; } return entryObj; } @@ -85,7 +144,8 @@ function addPageEntryObj(manifest, projectPath) { } else if (isHml) { entryObj['./' + element] = path.resolve(projectPath, './' + sourcePath + '.hml?entry'); } else if (isVisual) { - entryObj['./' + element] = path.resolve(aceSuperVisualPath, './' + sourcePath + '.visual?entry'); + entryObj['./' + element] = path.resolve(aceSuperVisualPath, './' + sourcePath + + '.visual?entry'); } }) return entryObj; @@ -95,4 +155,4 @@ module.exports = { deleteFolderRecursive: deleteFolderRecursive, readManifest: readManifest, loadEntryObj: loadEntryObj -}; +}; \ No newline at end of file diff --git a/ace-loader/package-lock.json b/ace-loader/package-lock.json index caec7ab..0c5f154 100644 --- a/ace-loader/package-lock.json +++ b/ace-loader/package-lock.json @@ -2563,9 +2563,9 @@ "dev": true }, "deccjsunit": { - "version": "1.0.3", - "resolved": "https://registry.nlark.com/deccjsunit/download/deccjsunit-1.0.3.tgz", - "integrity": "sha1-AcMxIKje4SsaoQiZGE14pszfiKI=" + "version": "1.0.4", + "resolved": "https://registry.nlark.com/deccjsunit/download/deccjsunit-1.0.4.tgz", + "integrity": "sha512-fkOzBz9uNKElrm6VGrisXLbAmLshcqBoqYAyo2+v9uceAkv75xh9dWAUmnZoWE/v4ujqYHylaudON1nj+LPuPA==" }, "decode-uri-component": { "version": "0.2.0", diff --git a/ace-loader/package.json b/ace-loader/package.json index 207a57b..f996f74 100644 --- a/ace-loader/package.json +++ b/ace-loader/package.json @@ -38,7 +38,7 @@ "copy-webpack-plugin": "^8.1.0", "css": "^3.0.0", "css-loader": "^3.4.2", - "deccjsunit": "1.0.3", + "deccjsunit": "1.0.4", "escodegen": "^2.0.0", "esprima": "^4.0.1", "hash-sum": "^1.0.2", diff --git a/ace-loader/plugin/codegen/index.js b/ace-loader/plugin/codegen/index.js index ba39d44..7561159 100644 --- a/ace-loader/plugin/codegen/index.js +++ b/ace-loader/plugin/codegen/index.js @@ -1,18 +1,3 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - /******/ (() => { // webpackBootstrap /******/ "use strict"; /******/ var __webpack_modules__ = ({ @@ -21,6 +6,9 @@ /***/ ((__unused_webpack_module, exports) => { +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved. + */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.errorMap = void 0; exports.errorMap = new Map([ @@ -37,6 +25,9 @@ exports.errorMap = new Map([ /***/ ((__unused_webpack_module, exports) => { +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved. + */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ASTNode = void 0; class ASTNode { @@ -53,67 +44,63 @@ exports.ASTNode = ASTNode; /***/ ((__unused_webpack_module, exports) => { +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2020-2021. All rights reserved. + */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Cache = void 0; // There is no way pass value by reference with JS and TS, but object // This Cache is used to store output code temporarily class Cache { - /** - * @description: constructor for Cache - * @param INDENT the IDENT string you want to use, such as 4 spaces - */ + * @description: constructor for Cache + * @param INDENT the IDENT string you want to use, such as 4 spaces + */ constructor(INDENT) { this.value = ""; this.indent = 0; this.flag = true; this.INDENT = INDENT; } - /** - * @description: when flag is true, there should be some indents - * @return void - */ + * @description: when flag is true, there should be some indents + * @return void + */ indentOn() { this.flag = true; } - /** - * @description: when flag is false, there should be no indents - * @return void - */ + * @description: when flag is false, there should be no indents + * @return void + */ indentOff() { this.flag = false; } - /** - * @description: increase indent - * @return void - */ + * @description: increase indent + * @return void + */ incIndent() { this.indent++; } - /** - * @description: decrease indent - * @return void - */ + * @description: decrease indent + * @return void + */ decIndent() { this.indent--; } - /** - * @description: check whether indent is LT 0 - * @return boolean value representing whether indent is LT 0 - */ + * @description: check whether indent is LT 0 + * @return boolean value representing whether indent is LT 0 + */ checkIndent() { return this.indent < 0; } - /** - * @description: get indent - * @return indents - */ + * @description: get indent + * @return indents + */ getIndents() { if (this.flag) { let indents = ""; @@ -126,22 +113,20 @@ class Cache { return ""; } } - /** - * @description: concat indents and HML/CSS code - * @param strings means HML/CSS code - * @return HML/CSS code after indents are set - */ + * @description: concat indents and HML/CSS code + * @param strings means HML/CSS code + * @return HML/CSS code after indents are set + */ concat(...strings) { this.value += this.getIndents(); this.value = this.value.concat(...strings); return String(this.value); } - /** - * @description: concat indents and HML/CSS code - * @return HML/CSS code - */ + * @description: concat indents and HML/CSS code + * @return HML/CSS code + */ toString() { return this.value; } @@ -155,17 +140,19 @@ exports.Cache = Cache; /***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/* + * @Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved. + */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Style = exports.Tag = void 0; const ASTNode_1 = __webpack_require__(117); class Tag extends ASTNode_1.ASTNode { - /** - * @description: constructor for Tag - * @param tagName is name of component - * @param attributes is attributes of component - * @param content is child elements or innerHtml of component - */ + * @description: constructor for Tag + * @param tagName is name of component + * @param attributes is attributes of component + * @param content is child elements or innerHtml of component + */ constructor(tagName, attributes, content) { super(); this.tagName = tagName; @@ -175,18 +162,19 @@ class Tag extends ASTNode_1.ASTNode { } exports.Tag = Tag; class Style extends ASTNode_1.ASTNode { - /** - * @description: constructor for Style - * @param kind distinguishes id and class - * @param name is name of id or class - * @param content is style name and value of component - */ - constructor(kind, name, content) { + * @description: constructor for Style + * @param kind distinguishes id and class + * @param name is name of id or class + * @param content is style name and value of component + */ + constructor(kind, name, content, mediaQuery) { super(); + this.mediaQuery = undefined; this.kind = kind; this.name = name; this.content = content; + this.mediaQuery = mediaQuery; } } exports.Style = Style; @@ -197,24 +185,26 @@ exports.Style = Style; /***/ 573: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +/* + * @Copyright (c) Huawei Technologies Co., Ltd. 2020-2021. All rights reserved. + */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ASTNodeGenerator = void 0; const AST_1 = __webpack_require__(243); const Token_1 = __webpack_require__(334); class ASTNodeGenerator { - /** - * @description: constructor for BridgeVisitor - * @param reference is cache for Harmony FA code - */ + * @description: constructor for BridgeVisitor + * @param reference is cache for Harmony FA code + */ constructor(reference) { this.cache = reference; } - /** - * @description: visitor mode dispatcher - * @param t Node in AST - */ + * @description: visitor mode dispatcher + * @param t Node in AST + */ visit(t) { if (t instanceof AST_1.Tag) { this.genTag(t); @@ -223,12 +213,11 @@ class ASTNodeGenerator { this.genStyle(t); } } - /** - * @description: code generator - * @param ref is cache for code - * @return ast node generator - */ + * @description: code generator + * @param ref is cache for code + * @return ast node generator + */ static getMethodGen(ref) { if (ASTNodeGenerator.instance === undefined) { ASTNodeGenerator.instance = new ASTNodeGenerator(ref); @@ -238,21 +227,19 @@ class ASTNodeGenerator { } return ASTNodeGenerator.instance; } - /** - * @description: cache for code - * @param ref is cache for code - * @return void - */ + * @description: cache for code + * @param ref is cache for code + * @return void + */ setCache(ref) { this.cache = ref; } - /** - * @description: parse Tag in AST and generate code for Tag in cache - * @param t Tag in AST - * @return void - */ + * @description: parse Tag in AST and generate code for Tag in cache + * @param t Tag in AST + * @return void + */ genTag(t) { this.cache.concat(Token_1.TokenClass.TAG_START, t.tagName); this.cache.indentOff(); @@ -261,8 +248,7 @@ class ASTNodeGenerator { for (const char of value) { valueBK += (char === "\"" ? """ : (char === "\n" ? " " : char)); } - this.cache.concat(Token_1.TokenClass.SPACE, key, Token_1.TokenClass.ASSIGN, - Token_1.TokenClass.LQUOTE, valueBK, Token_1.TokenClass.RQUOTE); + this.cache.concat(Token_1.TokenClass.SPACE, key, Token_1.TokenClass.ASSIGN, Token_1.TokenClass.LQUOTE, valueBK, Token_1.TokenClass.RQUOTE); }); if (t.content === null) { this.cache.concat(Token_1.TokenClass.EMPTY_TAG_END); @@ -292,13 +278,19 @@ class ASTNodeGenerator { this.cache.concat(Token_1.TokenClass.END_TAG_START, t.tagName, Token_1.TokenClass.TAG_END); } } - /** - * @description: parse Style in AST and generate code for Style in cache - * @param s Style in AST - * @return void - */ + * @description: parse Style in AST and generate code for Style in cache + * @param s Style in AST + * @return void + */ genStyle(s) { + if (s.mediaQuery !== undefined) { + this.cache.concat("@media"); + this.cache.indentOff(); + this.cache.concat(Token_1.TokenClass.SPACE, s.mediaQuery, Token_1.TokenClass.SPACE, Token_1.TokenClass.LBRA, Token_1.TokenClass.NEW_LINE); + this.cache.indentOn(); + this.cache.incIndent(); + } if (s.kind === "IDStyle") { this.cache.concat(Token_1.TokenClass.ID_STYLE_START); this.cache.indentOff(); @@ -307,11 +299,15 @@ class ASTNodeGenerator { this.cache.indentOn(); this.cache.incIndent(); s.content.forEach((value, key) => { - this.cache.concat(key, Token_1.TokenClass.COLON, Token_1.TokenClass.SPACE, value, - Token_1.TokenClass.SEMICOLON, Token_1.TokenClass.NEW_LINE); + this.cache.concat(key, Token_1.TokenClass.COLON, Token_1.TokenClass.SPACE, value, Token_1.TokenClass.SEMICOLON, Token_1.TokenClass.NEW_LINE); }); this.cache.decIndent(); - this.cache.concat(Token_1.TokenClass.RBRA, Token_1.TokenClass.NEW_LINE, Token_1.TokenClass.NEW_LINE); + this.cache.concat(Token_1.TokenClass.RBRA, Token_1.TokenClass.NEW_LINE); + if (s.mediaQuery !== undefined) { + this.cache.decIndent(); + this.cache.concat(Token_1.TokenClass.RBRA, Token_1.TokenClass.NEW_LINE); + } + this.cache.concat(Token_1.TokenClass.NEW_LINE); } } exports.ASTNodeGenerator = ASTNodeGenerator; @@ -324,6 +320,9 @@ ASTNodeGenerator.instance = undefined; /***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/* + * @Copyright (c) Huawei Technologies Co., Ltd. 2020-2021. All rights reserved. + */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CSSBridge = exports.HMLBridge = void 0; const AST_1 = __webpack_require__(243); @@ -332,30 +331,27 @@ class HMLBridge { constructor() { this.errors = 0; } - /** - * @description: generate error message - * @param msg is error message to show up in console - */ + * @description: generate error message + * @param msg is error message to show up in console + */ error(msg) { console.error("Code generating error: " + msg); this.errors += 1; } - /** - * @description: get error number - * @return error number - */ + * @description: get error number + * @return error number + */ getErrorCount() { return this.errors; } - /** - * @description: visitor guidance method for contents, - * sort out incoming type and guide to matching code generator - * @param visualModel is a object with Model or Container or CharUI primitive types to be generated - * @return a code tree representing input object - */ + * @description: visitor guidance method for contents, + * sort out incoming type and guide to matching code generator + * @param visualModel is a object with Model or Container or CharUI primitive types to be generated + * @return a code tree representing input object + */ visit(visualModel) { const attributes = new Map([["id", visualModel.id]]); let content = ""; @@ -370,6 +366,9 @@ class HMLBridge { content = val; } } + if (visualModel.type === "list") { + attributes.set("itemscale", "false"); + } if (visualModel.children.length > 0) { content = []; for (const visualChild of visualModel.children) { @@ -385,49 +384,57 @@ class CSSBridge { this.errors = 0; this.styles = []; } - /** - * @description: generate error message - * @param msg is error message to show up in console - */ + * @description: generate error message + * @param msg is error message to show up in console + */ error(msg) { + console.error("Code generating error: " + msg); this.errors += 1; } - /** - * @description: get error number - * @return error number - */ + * @description: get error number + * @return error number + */ getErrorCount() { return this.errors; } - /** - * @description: code generator for ID Style, which is CSS type in AST in IR - * @param visualModel is a object with CSS type to be generated - * @return a code tree representing Harmony FA CSS code - */ + * @description: code generator for ID Style, which is CSS type in AST in IR + * @param visualModel is a object with CSS type to be generated + * @return a code tree representing Harmony FA CSS code + */ genIDStyle(visualModel) { - const styles = new Map(); - for (const prop of PropertySet_1.styleSet) { - if (visualModel.property.has(prop) && PropertySet_1.isStyle(prop)) { - styles.set(prop, visualModel.property.get(prop)); + var _a; + const getStyleMap = (property) => { + const styles = new Map(); + for (const prop of PropertySet_1.styleSet) { + if (property.has(prop) && PropertySet_1.isStyle(prop)) { + styles.set(prop, property.get(prop)); + } } - } + return styles; + }; + const styles = getStyleMap(visualModel.property); if (styles.size > 0) { this.styles.push(new AST_1.Style("IDStyle", visualModel.id, styles)); } + ((_a = visualModel.mediaProperty) !== null && _a !== void 0 ? _a : new Map()).forEach((value, key) => { + const queryStyles = getStyleMap(value); + if (queryStyles.size > 0) { + this.styles.push(new AST_1.Style("IDStyle", visualModel.id, queryStyles, key)); + } + }); for (const visualChild of visualModel.children) { visualChild.accept(this); } } - /** - * @description: visitor guidance method for contents, - * sort out incoming type and guide to matching code generator - * @param obj is a object with Model or Container or CharUI primitive types to be generated - * @return a code tree representing input object - */ + * @description: visitor guidance method for contents, + * sort out incoming type and guide to matching code generator + * @param obj is a object with Model or Container or CharUI primitive types to be generated + * @return a code tree representing input object + */ visit(obj) { this.genIDStyle(obj); return this.styles; @@ -442,28 +449,29 @@ exports.CSSBridge = CSSBridge; /***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/* + * @Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved. + */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.genFACSS = exports.genFAHML = void 0; const ASTNodeVisitor_1 = __webpack_require__(573); const Cache_1 = __webpack_require__(862); - /** -* @description: generate HML -* @param t is Tag in AST -* @return HML code -*/ + * @description: generate HML + * @param t is Tag in AST + * @return HML code + */ function genFAHML(t) { const generator = ASTNodeVisitor_1.ASTNodeGenerator.getMethodGen(new Cache_1.Cache(" ")); t.accept(generator); return generator.cache.toString(); } exports.genFAHML = genFAHML; - /** -* @description: generate CSS -* @param t is Style in AST -* @return CSS code -*/ + * @description: generate CSS + * @param t is Style in AST + * @return CSS code + */ function genFACSS(t) { const generator = ASTNodeVisitor_1.ASTNodeGenerator.getMethodGen(new Cache_1.Cache(" ")); t.forEach((value) => { @@ -479,20 +487,20 @@ exports.genFACSS = genFACSS; /***/ 571: /***/ ((__unused_webpack_module, exports) => { + +/* + * @Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved. + */ Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isEvent = exports.isData = exports.isUnknown = exports.isContent = - exports.isAttribute = exports.isStyle = exports.styleSet = void 0; +exports.isEvent = exports.isData = exports.isUnknown = exports.isContent = exports.isAttribute = exports.isStyle = exports.styleSet = void 0; // Unlike the property list in ComponentList, this one is only used to tell a property is a style or an attribute const SizeStyle = ["width", "height", "min-width", "min-height", "max-width", "max-height"]; const FlexStyle = ["flex", "flex-grow", "flex-shrink", "flex-basis"]; -const BackgroundImageStyle = ["background", "background-image", "background-size", - "background-position", "background-repeat"]; +const BackgroundImageStyle = ["background", "background-image", "background-size", "background-position", "background-repeat"]; const BackgroundStyle = ["background-color", ...BackgroundImageStyle]; const PositionStyle = ["position", "display", "top", "right", "bottom", "left"]; -const PaddingStyle = ["padding", "padding-start", "padding-end", "padding-top", - "padding-right", "padding-bottom", "padding-left"]; -const MarginStyle = ["margin", "margin-start", "margin-end", "margin-top", "margin-right", - "margin-bottom", "margin-left"]; +const PaddingStyle = ["padding", "padding-start", "padding-end", "padding-top", "padding-right", "padding-bottom", "padding-left"]; +const MarginStyle = ["margin", "margin-start", "margin-end", "margin-top", "margin-right", "margin-bottom", "margin-left"]; const BorderStyle = ["border-width", "border-style", "border-color", "border-radius", "border-top-width", "border-top-style", "border-top-color", "border-top-left-radius", "border-right-width", "border-right-style", "border-right-color", "border-top-right-radius", "border-bottom-width", "border-bottom-style", @@ -516,12 +524,11 @@ const buttonStyle = ["text-color", "allow-scale", "icon-width", "icon-height", " const switchStyle = ["texton-color", "textoff-color", "text-padding", "allow-scale", ...FontStyle]; const inputStyle = ["font-size", "font-family", "font-weight", "color", "placeholder-color", "allow-scale"]; const refreshStyle = ["progress-color"]; -const chartStyle = ["stroke-width", "radius", "start-angle", "total-angle", "center-x", - "center-y", "colors", "weights"]; -const swiperStyle = ["indicator-color", "indicator-selected-color", "indicator-size", "indicator-top", - "indicator-right", "indicator-bottom", "indicator-left"]; -const pickerStyle = ["column-height", "text-color", "allow-scale", "letter-spacing", "text-decoration", - "line-height", "opacity", ...FontStyle]; +const chartStyle = ["stroke-width", "radius", "start-angle", "total-angle", "center-x", "center-y", "colors", "weights"]; +const swiperStyle = ["indicator-color", "indicator-selected-color", "indicator-size", "indicator-top", "indicator-right", + "indicator-bottom", "indicator-left"]; +const pickerStyle = ["column-height", "text-color", "allow-scale", "letter-spacing", "text-decoration", "line-height", "opacity", + ...FontStyle]; const sliderStyle = ["color", "selected-color", "block-color"]; const listStyle = ["flex-direction", "columns", "item-extent", "fade-color"]; const listItemStyle = ["column-span"]; @@ -555,17 +562,15 @@ const inputAttribute = ["type", "checked", "name", "value", "placeholder", "maxl const refreshAttribute = ["offset", "refreshing", "type", "lasttime", "friction"]; const optionAttribute = ["value"]; const chartAttribute = ["percent", "datasets", "options"]; -const swiperAttribute = ["index", "autoplay", "interval", "indicator", "digital", "indicatordisabled", - "loop", "duration", "vertical"]; -const pickerAttribute = ["range", "selected", "start", "end", "lunar", "lunarSwitch", "columns", - "hours", "containSecond"]; +const swiperAttribute = ["index", "autoplay", "interval", "indicator", "digital", "indicatordisabled", "loop", "duration", "vertical"]; +const pickerAttribute = ["range", "selected", "start", "end", "lunar", "lunarSwitch", "columns", "hours", "containSecond"]; const sliderAttribute = ["min", "max", "step", "showtips", "showsteps", "mode"]; const menuAttribute = ["target", "title"]; const clockAttribute = ["clockconfig", "showdigit", "hourswest"]; const dividerAttribute = ["vertical"]; const listAttribute = ["scrollpage", "cachedcount", "scrollbar", "scrolleffect", "shapemode", "indexer", "itemscale", "itemcenter", "updateeffect", "scrollvibrate", "initialindex", "initialoffset"]; -const listItemAttribute = ["for", "type", "primary", "section", "sticky", "stickyradius", "clickeffect"]; +const listItemAttribute = ["type", "primary", "section", "sticky", "stickyradius", "clickeffect"]; const progressAttribute = ["type", "percent", "secondarypercent", "clockwise"]; const commonEvent = ["ontouchstart", "ontouchmove", "ontouchcancel", "ontouchend", "onclick", "onlongpress", "onfocus", "onblur", "onkey", "onswipe"]; @@ -642,6 +647,9 @@ exports.isEvent = isEvent; /***/ ((__unused_webpack_module, exports) => { +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved. + */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TokenClass = void 0; var TokenClass; @@ -679,58 +687,58 @@ var TokenClass; /***/ }), -/***/ 234: +/***/ 282: /***/ ((__unused_webpack_module, exports) => { +/* + * @Copyright (c) Huawei Technologies Co., Ltd. 2020-2021. All rights reserved. + */ Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Enum = exports.Characteristic = exports.Event = exports.Service = exports.Device = void 0; -class Device { - constructor() { - this.prodId = ""; - this.udid = ""; - this.deviceModel = ""; - this.deviceName = ""; - this.deviceTypeId = ""; - this.deviceTypeName = ""; - this.manufacturerId = ""; - this.manufacturerName = ""; - this.services = []; - } -} -exports.Device = Device; -class Service { - constructor() { - this.serviceId = ""; - this.serviceType = ""; - this.characteristics = []; - } -} -exports.Service = Service; -class Event { - constructor() { - this.eventId = ""; - this.eventType = ""; - this.characteristics = []; - } -} -exports.Event = Event; -class Characteristic { - constructor() { - this.name = ""; - this.type = ""; - this.format = "int"; - this.method = []; - } -} -exports.Characteristic = Characteristic; -class Enum { - constructor() { - this.enumVal = ""; - this.description = {}; - } -} -exports.Enum = Enum; +exports.TagTypeMap = void 0; +/** + *

Semantic Model

+ * This is the Domain Specific Model for FA + * + * @author LowCode Group + * @version 1.0 + * @since 2020-08-27 + */ +const BaseSchema = { + id: "id", + tagName: "text", + attributes: "kv", + idStyle: "kv", + type: "kind", + accept: "accept", +}; +const BaseStyle = { + kind: "kind", + content: "kv", + accept: "accept", +}; +exports.TagTypeMap = new Map([ + ["button", "TextContent"], + ["span", "TextContent"], + ["divider", "TextContent"], + ["picker", "TextContent"], + ["option", "TextContent"], + ["clock", "TextContent"], + ["image", "Base"], + ["input", "Base"], + ["chart", "Base"], + ["slider", "Base"], + ["progress", "Base"], + ["text", "Text"], + ["div", "Container"], + ["list", "Container"], + ["list-item", "Container"], + ["list-item-group", "Container"], + ["refresh", "Container"], + ["dialog", "Container"], + ["stack", "Container"], + ["menu", "Container"], +]); /***/ }), @@ -741,25 +749,25 @@ exports.Enum = Enum; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.formManager = void 0; - - +/* + * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved. + */ const Instance_1 = __webpack_require__(891); const FormModel_1 = __webpack_require__(945); exports.formManager = { - /** - * remove a key-value in data node - * @param key the entry to remove - */ + * + * remove a key-value in data node + * @param key the entry to remove + */ removeData(key) { this.getFormModel().data.delete(key); }, - /** - * - * add a key-value - * @param data - */ + * + * add a key-value + * @param data + */ addData(data) { if (data instanceof Map) { data.forEach((value, key) => { @@ -772,137 +780,130 @@ exports.formManager = { }); } }, - /** - * - * update all the data - * @param data - */ + * update all the data + * @param data + */ updateAllData(data) { this.getFormModel().data.clear(); this.addData(data); }, - /** - * - * add an action in action node - * @param actionName - * @param actionType - * @param params - * @param abilityName optional param - */ - addAction(actionName, actionType, params, abilityName) { + * + * add an action in action node + * @param actionName + * @param actionType + * @param params + * @param want want params + */ + addAction(actionName, actionType, params, want) { const paramMap = new Map(); - Object.keys(params).forEach(key => { - paramMap.set(key, params[key]); - }); - this.getFormModel().actions.set(actionName, new FormModel_1.FormAction(actionType, paramMap, abilityName)); + if (params != null) { + Object.keys(params).forEach(key => { + paramMap.set(key, params[key]); + }); + } + const wantMap = new Map(); + if (want != null) { + Object.keys(want).forEach(key => { + wantMap.set(key, want[key]); + }); + } + this.getFormModel().actions.set(actionName, new FormModel_1.FormAction(actionType, paramMap, wantMap)); }, - /** - * - * update all the actions - * @param map: the new actions to be updated - */ + * update all the actions + * @param map: the new actions to be updated + */ updateAllActions(map) { this.getFormModel().actions.clear(); map.forEach((value, key) => { const params = this.objectToMap(value.params); - const action = new FormModel_1.FormAction(value.actionType, params, value.abilityName); + const action = new FormModel_1.FormAction(value.actionType, params); this.getFormModel().actions.set(key, action); }); }, - /** - * - * remove an action - * @param actionName - */ + * + * remove an action + * @param actionName + */ removeAction(actionName) { this.getFormModel().actions.delete(actionName); }, - /** - * - * add params in an action - * @param actionName - * @param params - */ + * + * add params in an action + * @param actionName + * @param params + */ addActionParams(actionName, params) { var _a, _b; - const action = (_a = this.getFormModel().actions.get(actionName)) !== null && _a !== - void 0 ? _a : new FormModel_1.FormAction(actionName); + const action = (_a = this.getFormModel().actions.get(actionName)) !== null && _a !== void 0 ? _a : new FormModel_1.FormAction(actionName); const actionParams = (_b = action.params) !== null && _b !== void 0 ? _b : new Map(); Object.keys(params).forEach(key => { actionParams.set(key, params[key]); }); action.params = actionParams; }, - /** - * - * remove params in an action - * @param actionName - * @param paramKey entry to remove - */ + * + * remove params in an action + * @param actionName + * @param paramKey entry to remove + */ removeActionParam(actionName, paramKey) { var _a; const action = this.getFormModel().actions.get(actionName); - (_a = action === null || action === void 0 ? void 0 : action.params) === null || _a - === void 0 ? void 0 : _a.delete(paramKey); + (_a = action === null || action === void 0 ? void 0 : action.params) === null || _a === void 0 ? void 0 : _a.delete(paramKey); }, - /** - * - * get the whole node - */ + * get the whole node + */ getFormModel() { return Instance_1.getInstance().formData; }, - /** - * - * codegen formModel to json - */ + * codegen formModel to json + */ codegenToJson: function () { const model = Instance_1.getInstance().formData; const data = this.mapToObject(model.data); - const actions = this.mapToObject(model.actions); const retObj = { actions: {}, data: {} }; retObj.data = data; - retObj.actions = actions; model.actions.forEach((value, key) => { - retObj.actions[key].params = this.mapToObject(value.params); + retObj.actions[key] = {}; + retObj.actions[key].action = value.action; + if (value.params instanceof Map && value.params.size > 0) { + retObj.actions[key].params = this.mapToObject(value.params); + } + if (value.want instanceof Map && value.want.size > 0) { + retObj.actions[key].want = this.mapToObject(value.want); + } }); return JSON.stringify(retObj, null, 4); }, - /** - * - * clear all datas and actions in model - */ + * clear all datas and actions in model + */ clear() { Instance_1.getInstance().formData.data.clear(); Instance_1.getInstance().formData.actions.clear(); }, - /** - * - * convert a map to an object - * @param sourceMap - */ + * + * convert a map to an object + * @param sourceMap + */ mapToObject(sourceMap) { if (sourceMap === undefined) { return {}; } - return Array.from(sourceMap.entries()).reduce((main, [key, value]) => - (Object.assign(Object.assign({}, main), { [key]: value })), {}); + return Array.from(sourceMap.entries()).reduce((main, [key, value]) => (Object.assign(Object.assign({}, main), { [key]: value })), {}); }, - /** - * - * convert an object to map - */ + * convert an object to map + */ objectToMap(sourceObj) { const map = new Map(); Object.keys(sourceObj).forEach((value, index) => { @@ -919,6 +920,9 @@ exports.formManager = { /***/ ((__unused_webpack_module, exports) => { +/* + * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved. + */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FormAction = exports.FormModel = void 0; class FormModel { @@ -929,10 +933,10 @@ class FormModel { } exports.FormModel = FormModel; class FormAction { - constructor(action, params, abilityName) { + constructor(action, params, want) { this.action = action; - this.abilityName = abilityName; this.params = params; + this.want = want; } } exports.FormAction = FormAction; @@ -940,23 +944,193 @@ exports.FormAction = FormAction; /***/ }), -/***/ 964: -/***/ ((__unused_webpack_module, exports) => { +/***/ 509: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isBindingEvent = exports.CombinedSelfType = void 0; -var CombinedSelfType; -(function (CombinedSelfType) { - CombinedSelfType[CombinedSelfType["None"] = 0] = "None"; - CombinedSelfType[CombinedSelfType["Root"] = 1] = "Root"; - CombinedSelfType[CombinedSelfType["Container"] = 2] = "Container"; - CombinedSelfType[CombinedSelfType["Active"] = 4] = "Active"; -})(CombinedSelfType = exports.CombinedSelfType || (exports.CombinedSelfType = {})); -function isBindingEvent(obj) { - return obj !== undefined && typeof obj.type === "string" && typeof obj.physicalModelName === "string"; +exports.deserializeForVersion1 = exports.rootToVisualContent = exports.visualToRootContent = exports.serializeForVersion1 = void 0; +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved. + */ +const Instance_1 = __webpack_require__(891); +const VisualModel_1 = __webpack_require__(933); +const PropertySet_1 = __webpack_require__(571); +const AST_1 = __webpack_require__(282); +const FormModel_1 = __webpack_require__(945); +const Serialization_1 = __webpack_require__(977); +// map for extra data. key: name of extra data; value: extra data +const extraData = new Map(); +/** + * save old voisual model(version 1) + * @return {string} + */ +function serializeForVersion1(model) { + extraData.set("textMap", new Map()); + const content = convertToVersion1AST(model !== null && model !== void 0 ? model : Instance_1.getInstance().visualModel); + return JSON.stringify({ + VisualVersion: "1", + content: JSON.stringify(content), + extraData: JSON.stringify(convert(extraData)), + }); +} +exports.serializeForVersion1 = serializeForVersion1; +/** + * convert visual files to root files + * + * @param visualInput source input content + */ +function visualToRootContent(visualInput) { + try { + const instance = JSON.parse(visualInput, Serialization_1.reviver); + return serializeForVersion1(instance.visualModel); + } + catch (e) { + console.error("convert visual model to root model failed"); + } + return visualInput; +} +exports.visualToRootContent = visualToRootContent; +/** + * convert root files to visual files + * @param rootInput input source content + */ +function rootToVisualContent(rootInput) { + const visualFile = JSON.parse(rootInput); + const rootModel = JSON.parse(visualFile.content); + let extraData = "[\"$$map\",[\"textMap\",[\"$$map\"]]]"; + if (typeof visualFile.extraData === "string") { + extraData = JSON.parse(visualFile.extraData); + } + const visualModel = convertFromVersion1AST(rootModel, recover(extraData)); + if (!visualModel.property.has("flex-direction")) { + visualModel.property.set("flex-direction", "column"); + } + return JSON.stringify({ + document: { VisualVersion: "12", type: "FA" }, + visualModel: visualModel, + formData: new FormModel_1.FormModel(), + }, Serialization_1.replacer); +} +exports.rootToVisualContent = rootToVisualContent; +/** + * convert visualModel version12 to version1 + * @param visualModel + * @return {HmlNode} + */ +function convertToVersion1AST(visualModel) { + const attributes = Array.from(visualModel.property).filter(value => PropertySet_1.isAttribute(value[0])); + attributes.push(["id", visualModel.id]); + const idStyle = Array.from(visualModel.property).filter(value => PropertySet_1.isStyle(value[0])); + let type = AST_1.TagTypeMap.get(visualModel.type); + if (type === undefined) { + type = "Base"; + } + let content = visualModel.property.has("content") + ? visualModel.property.get("content") : []; + if (visualModel.children.length > 0) { + if (typeof content === "string") { + const textMap = extraData.get("textMap"); + if (textMap instanceof Map) { + textMap.set(visualModel.id, content); + } + } + content = visualModel.children.map(value => convertToVersion1AST(value)); + } + return { + id: visualModel.id, + tagName: visualModel.type, + attributes: attributes, + idStyle: idStyle, + type: type, + content: content, + }; +} +/** + * read old voisual model(version 1) + * @param input + */ +function deserializeForVersion1(input) { + try { + const visualFile = JSON.parse(input); + const rootModel = JSON.parse(visualFile.content); + let extraData = "[\"$$map\",[\"textMap\",[\"$$map\"]]]"; + if (typeof visualFile.extraData === "string") { + extraData = JSON.parse(visualFile.extraData); + } + Instance_1.getInstance().visualModel = convertFromVersion1AST(rootModel, recover(extraData)); + if (!Instance_1.getInstance().visualModel.property.has("flex-direction")) { + Instance_1.getInstance().visualModel.property.set("flex-direction", "column"); + } + } + catch (e) { + console.error("convert error"); + } +} +exports.deserializeForVersion1 = deserializeForVersion1; +/** + * convert visualModel version1 to version12 + * @param node + * @return {VisualModel} + */ +function convertFromVersion1AST(node, extraData) { + let textContent; + if (extraData instanceof Map) { + const textMap = extraData.get("textMap"); + if (textMap instanceof Map) { + textContent = textMap.get(node.id); + } + } + const res = new VisualModel_1.VisualModel({ + id: node.id, + type: node.tagName, + property: new Map([...node.attributes, ...node.idStyle]), + }); + if (typeof textContent === "string") { + res.property.set("content", textContent); + } + res.property.delete("id"); + if (typeof node.content === "string") { + res.property.set("content", node.content); + } + if (Array.isArray(node.content)) { + res.children = node.content.map(child => convertFromVersion1AST(child, extraData)); + } + return res; +} +/** + * @description: recover extraData array + * @param {string} input extraData array + * @return {DataType} extraData + */ +function recover(input) { + if (input instanceof Array && input.length > 0) { + if (input[0] === "$$map") { + input.shift(); + const res = new Map(); + for (const [key, value] of input) { + res.set(key, recover(value)); + } + return res; + } + } + return input; +} +/** + * @description: convert input extraData to array + * @param {string} input extraData + * @return {any} extraData array + */ +function convert(input) { + if (input instanceof Map) { + const res = ["$$map"]; + for (const [key, value] of input) { + res.push([key, convert(value)]); + } + return res; + } + return input; } -exports.isBindingEvent = isBindingEvent; /***/ }), @@ -966,33 +1140,28 @@ exports.isBindingEvent = isBindingEvent; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.addPhysicalModel = exports.getPhysicalModel = exports.setInstance = exports.getInstance = void 0; - - -const PhysicalModel_1 = __webpack_require__(234); +exports.setInstance = exports.getInstance = void 0; +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved. + */ const VisualModel_1 = __webpack_require__(933); const FormModel_1 = __webpack_require__(945); const instance = { document: { VisualVersion: "12", type: "FA" }, visualModel: new VisualModel_1.VisualModel({ type: "div", id: "wrapper" }), - harmonyConnectDevice: new PhysicalModel_1.Device(), formData: new FormModel_1.FormModel(), }; - /** -* -* instance is unique during the entire web page lifecycle -*/ + * instance is unique during the entire web page lifecycle + */ function getInstance() { return instance; } exports.getInstance = getInstance; - /** -* -* replace instance -* @param ins -*/ + * replace instance + * @param ins + */ function setInstance(ins) { for (const key in instance) { if (Object.prototype.hasOwnProperty.call(ins, key)) { @@ -1002,41 +1171,6 @@ function setInstance(ins) { } exports.setInstance = setInstance; -/** -* -* get a physical model by its serviceId and characteristicName -* @param path -*/ -function getPhysicalModel(path) { - const service = getInstance().harmonyConnectDevice.services.find(e => e.serviceId === path.serviceId); - if (service === undefined) { - return undefined; - } - return service.characteristics.find(e => e.name === path.characteristicName); -} -exports.getPhysicalModel = getPhysicalModel; - -/** -* -* add a service, would overide if serviceId and characteristicName is same -* @param service -*/ -function addPhysicalModel(service) { - const device = getInstance().harmonyConnectDevice; - const existed = device.services.find(e => e.serviceId === service.serviceId); - if (existed === undefined) { - device.services.push(service); - } - else { - for (const ch of service.characteristics) { - if (existed.characteristics.every(e => e.name !== ch.name)) { - existed.characteristics.push(ch); - } - } - } -} -exports.addPhysicalModel = addPhysicalModel; - /***/ }), @@ -1045,38 +1179,41 @@ exports.addPhysicalModel = addPhysicalModel; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.deserialize = exports.serialize = void 0; - - -const VisualModel_1 =__webpack_require__(933); -const Instance_1 = __webpack_require__(891); - +exports.reviver = exports.replacer = exports.deserialize = exports.serialize = void 0; /** -* -* @description: convert JsonModel to Json -* @return model in json format -*/ -function serialize() { - return JSON.stringify(Instance_1.getInstance(), replacer); + * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved. + */ +const VisualModel_1 = __webpack_require__(933); +const Instance_1 = __webpack_require__(891); +const Compatibility_1 = __webpack_require__(509); +/** + * @description: convert JsonModel to Json + * @return model in json format + */ +function serialize(version, input) { + if (version === 1) { + return Compatibility_1.serializeForVersion1(input); + } + return JSON.stringify(input !== null && input !== void 0 ? input : Instance_1.getInstance(), replacer); } exports.serialize = serialize; - /** -* @description: convert Json to JsonModel -* @return model in json format -*/ + * @description: convert Json to JsonModel + * @return model in json format + */ function deserialize(json) { + if (JSON.parse(json).VisualVersion === "1") { + return Compatibility_1.deserializeForVersion1(json); + } const ins = JSON.parse(json, reviver); Instance_1.setInstance(ins); } exports.deserialize = deserialize; - /** -* -* json replacer, turn any class into string -* @param key -* @param value -*/ + * json replacer, turn any class into string + * @param key + * @param value + */ function replacer(key, value) { if (value instanceof Map) { return { @@ -1091,12 +1228,12 @@ function replacer(key, value) { }; } else if (value instanceof VisualModel_1.VisualModel) { - const visualObj = new VisualModel_1.VisualModel({ type: "none"}); + const visualObj = new VisualModel_1.VisualModel({ type: "none" }); const res = {}; for (const visualKey in visualObj) { - if (Object.prototype.hasOwnProperty.call(value, visualKey)) { - res[visualKey] = value[visualKey]; - } + if (Object.prototype.hasOwnProperty.call(value, visualKey)) { + res[visualKey] = value[visualKey]; + } } return { dataType: "VisualModel", @@ -1107,13 +1244,12 @@ function replacer(key, value) { return value; } } - +exports.replacer = replacer; /** -* -* json reviver, true magic, replace plain json to classes -* @param key -* @param value -*/ + * json reviver, true magic, replace plain json to classes + * @param key + * @param value + */ function reviver(key, value) { if (typeof value === "object" && value !== null && value !== undefined) { if (value.dataType === "Map") { @@ -1130,25 +1266,28 @@ function reviver(key, value) { } return value; } +exports.reviver = reviver; /***/ }), /***/ 933: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/***/ ((__unused_webpack_module, exports) => { +/* + * @Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved. + */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.VisualModel = void 0; -const CombinedModel_1 = __webpack_require__(964); // sometimes the type of VisualModel would be add a suffix to distinguish origin component of GrapesJs // e.g. button-visual const typeSuffix = "-visual"; class VisualModel { constructor(obj) { + this.mediaProperty = undefined; this.property = (obj.property !== undefined) ? obj.property : new Map(); this.children = (obj.children !== undefined) ? obj.children : []; - this.physicalModel = obj.physicalModel; if (obj.type === "wrapper") { this.id = "wrapper"; this.type = "div"; @@ -1159,16 +1298,6 @@ class VisualModel { } this.id = (obj.id !== undefined) ? obj.id : ""; this.type = obj.type; - if (obj.combinedSelfType !== undefined || obj.data !== undefined || obj.event !== undefined) { - this.combinedInfo = { - id: "", - type: "", - selfType: obj.combinedSelfType === - undefined ? CombinedModel_1.CombinedSelfType.None : obj.combinedSelfType, - data: obj.data, - event: obj.event, - }; - } } accept(v) { return v.visit(this); @@ -1179,31 +1308,31 @@ exports.VisualModel = VisualModel; /***/ }) -/******/ }); +/******/ }); /************************************************************************/ -/******/ // The module cache -/******/ var __webpack_module_cache__ = {}; +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; /******/ -/******/ // The require function -/******/ function __webpack_require__(moduleId) { -/******/ // Check if module is in cache -/******/ var cachedModule = __webpack_module_cache__[moduleId]; -/******/ if (cachedModule !== undefined) { -/******/ return cachedModule.exports; -/******/ } -/******/ // Create a new module (and put it into the cache) -/******/ var module = __webpack_module_cache__[moduleId] = { -/******/ // no module.id needed -/******/ // no module.loaded needed -/******/ exports: {} -/******/ }; +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ // Check if module is in cache +/******/ var cachedModule = __webpack_module_cache__[moduleId]; +/******/ if (cachedModule !== undefined) { +/******/ return cachedModule.exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ // no module.id needed +/******/ // no module.loaded needed +/******/ exports: {} +/******/ }; /******/ -/******/ // Execute the module function -/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); +/******/ // Execute the module function +/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); /******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } /******/ /************************************************************************/ var __webpack_exports__ = {}; @@ -1211,6 +1340,9 @@ var __webpack_exports__ = {}; (() => { var exports = __webpack_exports__; +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved. + */ Object.defineProperty(exports, "__esModule", ({ value: true })); const errorMap_1 = __webpack_require__(784); const Instance_1 = __webpack_require__(891); @@ -1219,13 +1351,11 @@ const BridgeVisitor_1 = __webpack_require__(844); const HmlCssCodeGenerator_1 = __webpack_require__(55); const FormManager_1 = __webpack_require__(207); const visualVersion = 12; - /** -* -* @description: codegen hml and css according to code in visual file -* @param source is code in visual file -* @return object of hmlCSS, errorType and errorMessage -*/ + * @description: codegen hml and css according to code in visual file + * @param source is code in visual file + * @return object of hmlCSS, errorType and errorMessage + */ function genHmlAndCss(source) { const retObj = { hmlCss: { @@ -1275,11 +1405,9 @@ function genHmlAndCss(source) { } return retObj; } - /** -* -* @description: output hml and css source code of the model -*/ + * @description: output hml and css source code of the model + */ function emitFA(rootModel) { const hmlCss = { hml: "", @@ -1316,4 +1444,4 @@ var __webpack_export_target__ = exports; for(var i in __webpack_exports__) __webpack_export_target__[i] = __webpack_exports__[i]; if(__webpack_exports__.__esModule) Object.defineProperty(__webpack_export_target__, "__esModule", { value: true }); /******/ })() -; +; \ No newline at end of file diff --git a/ace-loader/plugin/templater/card_component_map.js b/ace-loader/plugin/templater/card_component_map.js index d636217..8ffc4fc 100644 --- a/ace-loader/plugin/templater/card_component_map.js +++ b/ace-loader/plugin/templater/card_component_map.js @@ -324,6 +324,8 @@ var cardCommonTag = { accessibilityimportance: { enum: ['auto', 'yes', 'no', 'no-hide-descendants'], }, + for: {}, + tid: {} }, 'children': ['block', 'slot'], 'parents': ['block'] diff --git a/ace-loader/plugin/templater/component_validator.js b/ace-loader/plugin/templater/component_validator.js index db2f3e7..26e6c07 100644 --- a/ace-loader/plugin/templater/component_validator.js +++ b/ace-loader/plugin/templater/component_validator.js @@ -177,7 +177,7 @@ function validateTagName(domNode, out, relativePath) { const depends = out.deps const jsonTemplate = out.jsonTemplate const log = out.log - const oneChildNode = ['dialog', 'popup', 'badge'] + const oneChildNode = ['dialog', 'popup', 'badge', 'list-item'] const logType = process.env.DEVICE_LEVEL === DEVICE_LEVEL.LITE ? 'ERROR' : 'WARNING' let pos = domNode.__location || {} const elementNamesInFile = elementNames[relativePath] || [] @@ -765,6 +765,14 @@ function validateStyle(css, out, nodeLoc, relativePath) { if (styleContent.length === 2) { const key = styleContent[0].trim().replace(/-([a-z])/g, function(s, m) { return m.toUpperCase() }) let value = bind(styleContent[1].trim(), undefined, true, out, nodeLoc) + const contentValue = styleContent[1].trim().toString(); + if (contentValue.match(/^linear-gradient/) && contentValue.match(/\(.*\{\{.*\}\}.*\)/)) { + log.push({ + line: nodeLoc.line || 1, + column: nodeLoc.col || 1, + reason: `ERROR: can not bind data for linear-gradient in inline style at ${css}` + }) + } if (key === 'flex' && typeof value === 'string') { expandFlex(key, value, cssStyle, nodeLoc, log) } else { @@ -1073,8 +1081,8 @@ function validateEvent(eventName, val, out, pos, relativePath) { let paramList = content[2] if (paramList) { paramList = transContent.parseExpression(paramList, true) - val = eval('(function (evt) {' + bind('{{' + functionName + '(' + paramList + ',evt)}}', - false, true, out, pos) + '})') + val = eval('(function (evt) {' + bind('{{' + functionName + '(' + paramList + ',evt)}}', + false, true, out, pos) + '})') } } } @@ -1102,17 +1110,17 @@ function distributeEvent(out, eventName, name, val) { out.jsonTemplate.onBubbleEvents[name] = val } } else if (process.env.DEVICE_LEVEL === DEVICE_LEVEL.RICH && CLICK_EVENT_REGEXP.test(name) && - !eventName.match(END_CAPTURE_REGEXP) && process.env.PLATFORM_VERSION === PLATFORM.VERSION6) { - if (eventName.match(START_CATCH_REGEXP)) { - out.jsonTemplate.catchBubbleEvents = out.jsonTemplate.catchBubbleEvents || {} - out.jsonTemplate.catchBubbleEvents[name] = val - } else { - out.jsonTemplate.onBubbleEvents = out.jsonTemplate.onBubbleEvents || {} - out.jsonTemplate.onBubbleEvents[name] = val - } + !eventName.match(END_CAPTURE_REGEXP) && process.env.PLATFORM_VERSION === PLATFORM.VERSION6) { + if (eventName.match(START_CATCH_REGEXP)) { + out.jsonTemplate.catchBubbleEvents = out.jsonTemplate.catchBubbleEvents || {} + out.jsonTemplate.catchBubbleEvents[name] = val } else { - out.jsonTemplate.events = out.jsonTemplate.events || {} - out.jsonTemplate.events[name] = val + out.jsonTemplate.onBubbleEvents = out.jsonTemplate.onBubbleEvents || {} + out.jsonTemplate.onBubbleEvents[name] = val + } +} else { + out.jsonTemplate.events = out.jsonTemplate.events || {} + out.jsonTemplate.events[name] = val } } @@ -1244,8 +1252,8 @@ function validateAttrElse(preNode, out, nodeLoc, relativePath) { function parseDataAttr(name, value, out) { const childName = name.replace('data-', '') out.jsonTemplate.attr = out.jsonTemplate.attr || {} - out.jsonTemplate.attr.data = out.jsonTemplate.attr.data || {} - out.jsonTemplate.attr.data[childName] = bind(value, undefined, true, out) + out.jsonTemplate.attr.$data = out.jsonTemplate.attr.$data || {} + out.jsonTemplate.attr.$data[childName] = bind(value, undefined, true, out) } function isSupportedSelfClosing(tagName) { diff --git a/ace-loader/src/cardJson-plugin.js b/ace-loader/src/cardJson-plugin.js index 5a27c28..ff0d893 100644 --- a/ace-loader/src/cardJson-plugin.js +++ b/ace-loader/src/cardJson-plugin.js @@ -30,7 +30,9 @@ class AfterEmitPlugin { (assets, back) => { const keys = Object.keys(assets) keys.forEach(key => { - sourceChange(key, assets, compilation); + if ('./' + process.env.abilityType + '.js' !== key) { + sourceChange(key, assets, compilation); + } }); back && back(); } diff --git a/ace-loader/src/compile-plugin.js b/ace-loader/src/compile-plugin.js index fa80c12..f933d3c 100644 --- a/ace-loader/src/compile-plugin.js +++ b/ace-loader/src/compile-plugin.js @@ -13,12 +13,15 @@ * limitations under the License. */ -const Stats = require('webpack/lib/Stats'); const fs = require('fs'); const path = require('path'); -const { DEVICE_LEVEL } = require('./lite/lite-enum'); +import Compilation from 'webpack/lib/Compilation'; +import JavascriptModulesPlugin from 'webpack/lib/javascript/JavascriptModulesPlugin'; +import CachedSource from 'webpack-sources/lib/CachedSource'; +import ConcatSource from 'webpack-sources/lib/ConcatSource'; + +import { circularFile } from './util'; -const REG = /\([^\)]+\)/; let mStats; let mErrorCount = 0; let mWarningCount = 0; @@ -29,6 +32,14 @@ let warningCount = 0; let noteCount = 0; let errorCount = 0; +const GLOBAL_COMMON_MODULE_CACHE = ` +globalThis["__common_module_cache__"] = globalThis["__common_module_cache__"] || {}; +globalThis["webpackChunkace_loader"].forEach((item)=> { + Object.keys(item[1]).forEach((element) => { + globalThis["__common_module_cache__"][element] = null; + }) +});`; + class ResultStates { constructor(options) { this.options = options; @@ -36,6 +47,30 @@ class ResultStates { apply(compiler) { const buildPath = this.options.build; + const modulePaths = new Set(); + + compiler.hooks.compilation.tap('toFindModule', (compilation) => { + compilation.hooks.buildModule.tap("findModule", (module) => { + if (/node_modules/.test(module.context)) { + const beforNodeModules = module.context.substr(0, module.context.indexOf('node_modules')); + const afterNodeModules = + module.context.replace(beforNodeModules, '').replace('node_modules' + path.sep, ''); + const src = afterNodeModules.substr(0, afterNodeModules.indexOf(path.sep)); + const modulePath = + path.resolve(beforNodeModules, 'node_modules', src, 'src', 'js', 'share'); + if (fs.existsSync(modulePath)) { + modulePaths.add(modulePath) + } + } + }); + }); + + compiler.hooks.afterCompile.tap('copyFindModule', () => { + for (let modulePath of modulePaths) { + circularFile(modulePath, path.resolve(buildPath, '../share')); + } + }); + compiler.hooks.done.tap('Result States', (stats) => { mStats = stats; warningCount = 0; @@ -58,6 +93,38 @@ class ResultStates { } printResult(buildPath); }); + + compiler.hooks.compilation.tap('CommonAsset', compilation => { + compilation.hooks.processAssets.tap( + { + name: 'GLOBAL_COMMON_MODULE_CACHE', + stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONS, + }, + (assets) => { + if (assets['commons.js']) { + assets['commons.js'] = new CachedSource( + new ConcatSource(assets['commons.js'], GLOBAL_COMMON_MODULE_CACHE)); + } else if (assets['vendors.js']) { + assets['vendors.js'] = new CachedSource( + new ConcatSource(assets['vendors.js'], GLOBAL_COMMON_MODULE_CACHE)); + } + } + ); + }); + + compiler.hooks.compilation.tap('Require', compilation => { + JavascriptModulesPlugin.getCompilationHooks(compilation).renderRequire.tap('renderRequire', + (source) => { + return `var commonCachedModule = globalThis["__common_module_cache__"] ? ` + + `globalThis["__common_module_cache__"][moduleId]: null;\n` + + `if (commonCachedModule) { return commonCachedModule.exports; }\n` + + source.replace('// Execute the module function', + `if (globalThis["__common_module_cache__"] && moduleId.indexOf("?name=") < 0 && ` + + `Object.keys(globalThis["__common_module_cache__"]).indexOf(moduleId) >= 0) {\n` + + ` globalThis["__common_module_cache__"][moduleId] = module;\n}`); + } + ); + }); } } diff --git a/ace-loader/src/extgen.js b/ace-loader/src/extgen.js index 385a892..441f425 100644 --- a/ace-loader/src/extgen.js +++ b/ace-loader/src/extgen.js @@ -1,20 +1,16 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ import loaderUtils from 'loader-utils'; @@ -24,7 +20,7 @@ const codegen = require("./codegen/index.js"); module.exports = function (source, map) { this.cacheable && this.cacheable(); const callback = this.async(); - + const parsed = codegen.genHmlAndCss(source); const loaderQuery = loaderUtils.getOptions(this) || {}; if (parsed.errorType && parsed.errorType !== '') { diff --git a/ace-loader/src/genAbc-plugin.js b/ace-loader/src/genAbc-plugin.js index 2f7b2ef..e33a8c5 100644 --- a/ace-loader/src/genAbc-plugin.js +++ b/ace-loader/src/genAbc-plugin.js @@ -17,7 +17,6 @@ const fs = require('fs') const path = require('path') const process = require('child_process') -const arkDir = path.join(__dirname, '..', 'bin', 'ark'); const forward = '(global.___mainEntry___ = function (globalObjects) {' + '\n' + ' var define = globalObjects.define;' + '\n' + ' var require = globalObjects.require;' + '\n' + @@ -35,25 +34,25 @@ const forward = '(global.___mainEntry___ = function (globalObjects) {' + '\n' + const last = '\n' + '})(this.__appProto__);' + '\n' + '})' const firstFileEXT = '_.js' let output -let webpackPath let isWin = false let isMac = false let isDebug = false +let arkDir class GenAbcPlugin { - constructor(output_, webpackPath_, isDebug_) { + constructor(output_, arkDir_, isDebug_) { output = output_ - webpackPath = webpackPath_ + arkDir = arkDir_ isDebug = isDebug_ } apply(compiler) { - if (fs.existsSync(path.resolve(webpackPath, 'ark/build-win'))) { + if (fs.existsSync(path.resolve(arkDir, 'build-win'))) { isWin = true } else { - if (fs.existsSync(path.resolve(webpackPath, 'ark/build-mac'))) { + if (fs.existsSync(path.resolve(arkDir, 'build-mac'))) { isMac = true } else { - if (!fs.existsSync(path.resolve(webpackPath, 'ark/build'))) { + if (!fs.existsSync(path.resolve(arkDir, 'build'))) { console.error('\u001b[31m', `find build fail`, '\u001b[39m') return } @@ -65,11 +64,14 @@ class GenAbcPlugin { const keys = Object.keys(assets) keys.forEach(key => { // choice *.js - if (output && webpackPath && path.extname(key) === '.js') { + if (output && path.extname(key) === '.js') { let newContent = assets[key].source() - if (key.search('./workers/') !== 0) { + if (key.search('./workers/') !== 0 && key !== 'commons.js' && key !== 'vendors.js') { newContent = forward + newContent + last } + if (key === 'commons.js' || key === 'vendors.js') { + newContent = `\n\n\n\n\n\n\n\n\n\n\n\n\n\n` + newContent + } const keyPath = key.replace(/\.js$/, firstFileEXT) writeFileSync(newContent, path.resolve(output, keyPath), key) } diff --git a/ace-loader/src/loader-gen.js b/ace-loader/src/loader-gen.js index 888a82d..132c8bf 100644 --- a/ace-loader/src/loader-gen.js +++ b/ace-loader/src/loader-gen.js @@ -192,11 +192,11 @@ function codegenHmlAndCss() { if (process.env.DEVICE_LEVEL === 'card') { output = '//card_start\n' - output += `var card_template =` + getRequireString(this, + output += `var card_template =` + getRequireString(this, jsonLoaders('template', undefined, true, 'template'), this.resourcePath) - output += `var card_style =` + getRequireString(this, + output += `var card_style =` + getRequireString(this, jsonLoaders('style', undefined, true, 'style'), this.resourcePath) - output += `var card_json =` + getRequireString(this, + output += `var card_json =` + getRequireString(this, jsonLoaders('json', undefined, true, 'json'), this.resourcePath) output += '\n//card_end' } else { @@ -207,7 +207,7 @@ function codegenHmlAndCss() { elementName: undefined, source: jsFileName }), jsFileName) - + output += 'var $app_template$ = ' + getRequireString(this, getLoaderString('template', { customLang, lang: undefined, @@ -215,7 +215,7 @@ function codegenHmlAndCss() { elementName: undefined, source: this.resourcePath }), this.resourcePath) - + output += 'var $app_style$ = ' + getRequireString(this, getLoaderString('style', { customLang, lang: undefined, @@ -223,9 +223,9 @@ function codegenHmlAndCss() { elementName: undefined, source: this.resourcePath }), this.resourcePath) - + output += ` - $app_define$('@app-component/${getNameByPath(this.resourcePath)}', [], + $app_define$('@app-component/${getNameByPath(this.resourcePath)}', [], function($app_require$, $app_exports$, $app_module$) { ` + ` $app_script$($app_module$, $app_exports$, $app_require$) @@ -240,8 +240,8 @@ function codegenHmlAndCss() { }) ` if (isEntry) { - output += `$app_bootstrap$('@app-component/ - ${getNameByPath(this.resourcePath)}'` + ',undefined' + ',undefined' + `)` + output += `$app_bootstrap$('@app-component/${getNameByPath(this.resourcePath)}'` + + ',undefined' + ',undefined' + `)` } } return output diff --git a/ace-loader/src/resource-plugin.js b/ace-loader/src/resource-plugin.js index 1619b04..58fccb0 100644 --- a/ace-loader/src/resource-plugin.js +++ b/ace-loader/src/resource-plugin.js @@ -19,6 +19,7 @@ const SingleEntryPlugin = require('webpack/lib/SingleEntryPlugin'); const CUSTOM_THEME_PROP_GROUPS = require('./theme/customThemeStyles'); const OHOS_THEME_PROP_GROUPS = require('./theme/ohosStyles'); +import { mkDir } from './util'; const FILE_EXT_NAME = ['.js', '.css', '.jsx', '.less', '.sass', '.scss', '.md', '.DS_Store', '.hml']; const red = '\u001b[31m'; @@ -63,14 +64,6 @@ function copyFile(input, output) { } } -function mkDir(path_) { - const parent = path.join(path_, '..'); - if (!(fs.existsSync(parent) && !fs.statSync(parent).isFile())) { - mkDir(parent); - } - fs.mkdirSync(path_); -} - function circularFile(inputPath, outputPath, ext) { const realPath = path.join(inputPath, ext); const localI18n = path.join(input, 'i18n'); @@ -146,12 +139,8 @@ let entryObj = {}; function addPageEntryObj() { entryObj = {}; if (process.env.abilityType === 'page') { - if (!fs.existsSync(manifestFilePath)) { - throw Error('ERROR: missing manifest').message; - } - const jsonString = fs.readFileSync(manifestFilePath).toString(); - const obj = JSON.parse(jsonString); - const pages = obj.pages; + const jsonString = readManifest(manifestFilePath); + const pages = jsonString.pages; if (pages === undefined) { throw Error('ERROR: missing pages').message; } @@ -164,13 +153,12 @@ function addPageEntryObj() { const isVisual = fs.existsSync(visualPath); const projectPath = process.env.projectPath; if (isHml && isVisual) { - logWarn(this, [{ - reason: 'ERROR: ' + sourcePath + ' cannot both have hml && visual', - }]); + console.error('ERROR: ' + sourcePath + ' cannot both have hml && visual'); } else if (isHml) { entryObj['./' + element] = path.resolve(projectPath, './' + sourcePath + '.hml?entry'); } else if (isVisual) { - entryObj['./' + element] = path.resolve(aceSuperVisualPath, './' + sourcePath + '.visual?entry'); + entryObj['./' + element] = path.resolve(aceSuperVisualPath, './' + sourcePath + + '.visual?entry'); } }); } @@ -180,6 +168,66 @@ function addPageEntryObj() { return entryObj; } +function readManifest(manifestFilePath) { + let manifest = {}; + try { + if (fs.existsSync(manifestFilePath)) { + const jsonString = fs.readFileSync(manifestFilePath).toString(); + manifest = JSON.parse(jsonString); + } else if (process.env.aceConfigPath && fs.existsSync(process.env.aceConfigPath)) { + buildManifest(manifest, process.env.aceConfigPath); + } else { + throw Error('\u001b[31m' + 'ERROR: the manifest.json or config.json is lost.' + + '\u001b[39m').message; + } + } catch (e) { + throw Error('\u001b[31m' + 'ERROR: the manifest.json or config.json file format is invalid.' + + '\u001b[39m').message; + } + return manifest; +} + +function buildManifest(manifest, aceConfigPath) { + try { + const configJson = JSON.parse(fs.readFileSync(aceConfigPath).toString()); + const srcPath = process.env.srcPath; + manifest.type = process.env.abilityType; + if (configJson.module && configJson.module.abilities) { + manifest.pages = getPages(configJson, srcPath); + } else { + throw Error('\u001b[31m'+ + 'EERROR: the config.json file miss keyword module || module[abilities].' + + '\u001b[39m').message; + } + manifest.minPlatformVersion = configJson.app.apiVersion.compatible; + } catch (e) { + throw Error("\x1B[31m" + 'ERROR: the config.json file is lost or format is invalid.' + + "\x1B[39m").message; + } +} + +function getPages(configJson, srcPath) { + let pages = [] + for (const ability of configJson.module.abilities){ + if (ability.srcPath === srcPath) { + readPages(ability, pages, configJson) + break; + } + } + return pages; +} + +function readPages(ability, pages, configJson) { + for (const js of configJson.module.js){ + if (ability.name === js.name) { + js.pages.forEach(page => { + pages.push(page) + }) + break; + } + } +} + function loadWorker(entryObj) { const workerPath = path.resolve(input, 'workers'); if (fs.existsSync(workerPath)) { @@ -236,4 +284,4 @@ function themeFileBuild(customThemePath, customThemeBuild) { return false; } -module.exports = ResourcePlugin; +module.exports = ResourcePlugin; \ No newline at end of file diff --git a/ace-loader/src/resource-reference-script.js b/ace-loader/src/resource-reference-script.js index ff78f2f..2884d0e 100644 --- a/ace-loader/src/resource-reference-script.js +++ b/ace-loader/src/resource-reference-script.js @@ -1,20 +1,16 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ const OHOS_THEME_PROP_GROUPS = require('./theme/ohosStyles') diff --git a/ace-loader/test/card/test.js b/ace-loader/test/card/test.js index 6935260..5662070 100644 --- a/ace-loader/test/card/test.js +++ b/ace-loader/test/card/test.js @@ -1,20 +1,16 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ 'use strict'; diff --git a/ace-loader/test/card/testcase/pages/importLess/importLess.less b/ace-loader/test/card/testcase/pages/importLess/importLess.less index fffa9e9..7bd3617 100644 --- a/ace-loader/test/card/testcase/pages/importLess/importLess.less +++ b/ace-loader/test/card/testcase/pages/importLess/importLess.less @@ -12,7 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + + @colorBackground: #000000; .container { background-color: @colorBackground; diff --git a/ace-loader/test/lite/commandTest/compile.test.js b/ace-loader/test/lite/commandTest/compile.test.js index 15a7708..b8f71eb 100644 --- a/ace-loader/test/lite/commandTest/compile.test.js +++ b/ace-loader/test/lite/commandTest/compile.test.js @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2020 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/ace-loader/test/lite/expected/attribute.js b/ace-loader/test/lite/expected/attribute.js index 503c5e4..f670fa0 100644 --- a/ace-loader/test/lite/expected/attribute.js +++ b/ace-loader/test/lite/expected/attribute.js @@ -13,4 +13,4 @@ * limitations under the License. */ -{"render": "function (vm) { var _vm = vm || this; return _c('div', [_c('slider', {'attrs' : {'max' : 100}} ),_c('image'),_c('div', {'attrs' : {'key' : \"day\",'value' : \"hello\"}} ),_c('text', {'attrs' : {'value' : \"hello\"}} ),_c('text', {'attrs' : {'value' : function () {return _vm.num}}} )] ) }"} +{"render": "function (vm) { var _vm = vm || this; return _c('div', [_c('slider', {'attrs' : {'max' : 100}} ),_c('image'),_c('div', {'attrs' : {'key' : \"day\",'value' : \"hello\"}} ),_c('text', {'attrs' : {'value' : \"hello\"}} ),_c('text', {'attrs' : {'value' : function () {return _vm.num}}} )] ) }"} \ No newline at end of file diff --git a/ace-loader/test/lite/expected/bubble.js b/ace-loader/test/lite/expected/bubble.js index a109bcd..554eb78 100644 --- a/ace-loader/test/lite/expected/bubble.js +++ b/ace-loader/test/lite/expected/bubble.js @@ -13,4 +13,4 @@ * limitations under the License. */ -{"render": "function (vm) { var _vm = vm || this; return _c('div', {'staticClass' : [\"container\"]} , [_c('div', {'onBubbleEvents' : {'click' : _vm.test1}} ),_c('div', {'onBubbleEvents' : {'click' : _vm.test2}} ),_c('div', {'onBubbleEvents' : {'click' : _vm.test3}} ),_c('div', {'catchBubbleEvents' : {'click' : _vm.test4}} ),_c('div', {'onBubbleEvents' : {'click' : _vm.test5}} ),_c('div', {'onBubbleEvents' : {'click' : _vm.test6}} ),_c('div', {'onBubbleEvents' : {'click' : _vm.test7}} ),_c('div', {'catchBubbleEvents' : {'click' : _vm.test8}} ),_c('div', {'onCaptureEvents' : {'click' : _vm.test9}} ),_c('div', {'onCaptureEvents' : {'click' : _vm.test10}} ),_c('div', {'onCaptureEvents' : {'click' : _vm.test11}} ),_c('div', {'catchCaptureEvents' : {'click' : _vm.test12}} ),_c('div', {'onBubbleEvents' : {'swipe' : _vm.swipe1},'catchCaptureEvents' : {'longpress' : _vm.longpress1}} ),_c('div', {'onBubbleEvents' : {'swipe' : _vm.swipe2},'onCaptureEvents' : {'longpress' : _vm.longpress2}} ),_c('div', {'onBubbleEvents' : {'swipe' : _vm.swipe3},'onCaptureEvents' : {'longpress' : _vm.longpress3}} ),_c('div', {'catchBubbleEvents' : {'swipe' : _vm.swipe4},'onCaptureEvents' : {'longpress' : _vm.longpress4}} ),_c('div', {'onBubbleEvents' : {'swipe' : _vm.swipe5},'catchBubbleEvents' : {'longpress' : _vm.longpress5}} ),_c('div', {'onBubbleEvents' : {'swipe' : _vm.swipe6,'longpress' : _vm.longpress6}} ),_c('div', {'onBubbleEvents' : {'swipe' : _vm.swipe7,'longpress' : _vm.longpress7}} ),_c('div', {'catchBubbleEvents' : {'swipe' : _vm.swipe8},'onBubbleEvents' : {'longpress' : _vm.longpress8}} ),_c('div', {'onCaptureEvents' : {'swipe' : _vm.swipe9},'catchBubbleEvents' : {'longpress' : _vm.longpress9}} ),_c('div', {'onCaptureEvents' : {'swipe' : _vm.swipe10},'onBubbleEvents' : {'longpress' : _vm.longpress10}} ),_c('div', {'onCaptureEvents' : {'swipe' : _vm.swipe11},'onBubbleEvents' : {'longpress' : _vm.longpress11}} ),_c('div', {'catchCaptureEvents' : {'swipe' : _vm.swipe12},'onBubbleEvents' : {'longpress' : _vm.longpress12}} )] ) }"} +{"render": "function (vm) { var _vm = vm || this; return _c('div', {'staticClass' : [\"container\"]} , [_c('div', {'onBubbleEvents' : {'click' : _vm.test1}} ),_c('div', {'onBubbleEvents' : {'click' : _vm.test2}} ),_c('div', {'onBubbleEvents' : {'click' : _vm.test3}} ),_c('div', {'catchBubbleEvents' : {'click' : _vm.test4}} ),_c('div', {'onBubbleEvents' : {'click' : _vm.test5}} ),_c('div', {'onBubbleEvents' : {'click' : _vm.test6}} ),_c('div', {'onBubbleEvents' : {'click' : _vm.test7}} ),_c('div', {'catchBubbleEvents' : {'click' : _vm.test8}} ),_c('div', {'onCaptureEvents' : {'click' : _vm.test9}} ),_c('div', {'onCaptureEvents' : {'click' : _vm.test10}} ),_c('div', {'onCaptureEvents' : {'click' : _vm.test11}} ),_c('div', {'catchCaptureEvents' : {'click' : _vm.test12}} ),_c('div', {'onBubbleEvents' : {'swipe' : _vm.swipe1},'catchCaptureEvents' : {'longpress' : _vm.longpress1}} ),_c('div', {'onBubbleEvents' : {'swipe' : _vm.swipe2},'onCaptureEvents' : {'longpress' : _vm.longpress2}} ),_c('div', {'onBubbleEvents' : {'swipe' : _vm.swipe3},'onCaptureEvents' : {'longpress' : _vm.longpress3}} ),_c('div', {'catchBubbleEvents' : {'swipe' : _vm.swipe4},'onCaptureEvents' : {'longpress' : _vm.longpress4}} ),_c('div', {'onBubbleEvents' : {'swipe' : _vm.swipe5},'catchBubbleEvents' : {'longpress' : _vm.longpress5}} ),_c('div', {'onBubbleEvents' : {'swipe' : _vm.swipe6,'longpress' : _vm.longpress6}} ),_c('div', {'onBubbleEvents' : {'swipe' : _vm.swipe7,'longpress' : _vm.longpress7}} ),_c('div', {'catchBubbleEvents' : {'swipe' : _vm.swipe8},'onBubbleEvents' : {'longpress' : _vm.longpress8}} ),_c('div', {'onCaptureEvents' : {'swipe' : _vm.swipe9},'catchBubbleEvents' : {'longpress' : _vm.longpress9}} ),_c('div', {'onCaptureEvents' : {'swipe' : _vm.swipe10},'onBubbleEvents' : {'longpress' : _vm.longpress10}} ),_c('div', {'onCaptureEvents' : {'swipe' : _vm.swipe11},'onBubbleEvents' : {'longpress' : _vm.longpress11}} ),_c('div', {'catchCaptureEvents' : {'swipe' : _vm.swipe12},'onBubbleEvents' : {'longpress' : _vm.longpress12}} )] ) }"} \ No newline at end of file diff --git a/ace-loader/test/lite/expected/class.js b/ace-loader/test/lite/expected/class.js index 85e6e7d..2721e6c 100644 --- a/ace-loader/test/lite/expected/class.js +++ b/ace-loader/test/lite/expected/class.js @@ -13,4 +13,4 @@ * limitations under the License. */ -{"render": "function (vm) { var _vm = vm || this; return _c('div', [_c('div', {'staticClass' : [\"container\"]} ),_c('div', {'staticClass' : [\"container\",\"table\"]} )] ) }"} +{"render": "function (vm) { var _vm = vm || this; return _c('div', [_c('div', {'staticClass' : [\"container\"]} ),_c('div', {'staticClass' : [\"container\",\"table\"]} )] ) }"} \ No newline at end of file diff --git a/ace-loader/test/lite/expected/expression.js b/ace-loader/test/lite/expected/expression.js index 26185b6..9347aa1 100644 --- a/ace-loader/test/lite/expected/expression.js +++ b/ace-loader/test/lite/expected/expression.js @@ -13,4 +13,4 @@ * limitations under the License. */ -{"render": "function (vm) { var _vm = vm || this; return _c('div', [_c('text', {'attrs' : {'value' : function () {return _vm.ti||_vm.subTitle}}} ),_c('text', {'attrs' : {'value' : function () {return _vm.ti&&_vm.subTitle}}} ),_c('div', {'attrs' : {'value' : function () {return _vm.isArrived==='arrived'&&_vm.isTravel===false}}} ),_c('div', {'attrs' : {'value' : function () {return _vm.isArrived==='arrived'||_vm.isTravel===false}}} ),_c('div', {'attrs' : {'value' : function () {return !_vm.flag}}} ),_c('div', {'attrs' : {'value' : function () {return !!_vm.flag}}} )] ) }"} +{"render": "function (vm) { var _vm = vm || this; return _c('div', [_c('text', {'attrs' : {'value' : function () {return _vm.ti||_vm.subTitle}}} ),_c('text', {'attrs' : {'value' : function () {return _vm.ti&&_vm.subTitle}}} ),_c('div', {'attrs' : {'value' : function () {return _vm.isArrived==='arrived'&&_vm.isTravel===false}}} ),_c('div', {'attrs' : {'value' : function () {return _vm.isArrived==='arrived'||_vm.isTravel===false}}} ),_c('div', {'attrs' : {'value' : function () {return !_vm.flag}}} ),_c('div', {'attrs' : {'value' : function () {return !!_vm.flag}}} )] ) }"} \ No newline at end of file diff --git a/ace-loader/test/lite/expected/forDirective.js b/ace-loader/test/lite/expected/forDirective.js index e901262..50fc560 100644 --- a/ace-loader/test/lite/expected/forDirective.js +++ b/ace-loader/test/lite/expected/forDirective.js @@ -13,4 +13,4 @@ * limitations under the License. */ -{"render": "function (vm) { var _vm = vm || this; return _c('div', [_l((function () {return _vm.list}),function($item,$idx){return _c('div', {'onBubbleEvents' : {'click' : function (evt) {_vm.test($item,evt)}}} , [_c('text', {'attrs' : {'value' : function () {return ($idx) + decodeURI('.') + ($item.name)}}} )] )}),_c('div', [_l((function () {return _vm.list}),function(personItem,$idx){return _c('div', {'onBubbleEvents' : {'click' : function (evt) {_vm.test($idx,evt)}}} , [_c('text', {'attrs' : {'value' : function () {return ($idx) + decodeURI('-') + (personItem.name) + decodeURI('--') + (personItem.age)}}} )] )}),_c('image', {'attrs' : {'src' : function () {return _vm.personItem}}} )] ),_c('div', [_l((function () {return _vm.list}),function(personItem,personIndex){return _c('div', {'onBubbleEvents' : {'click' : function (evt) {_vm.test(personItem,evt)}}} , [_c('text', {'attrs' : {'value' : function () {return (personIndex) + decodeURI('.') + (personItem.name)}}} )] )}),_c('swiper', {'attrs' : {'index' : function () {return _vm.personIndex},'loop' : function () {return _vm.personItem}}} )] ),_l((function () {return _vm.list}),function(personItem,personIndex){return _c('div', {'onBubbleEvents' : {'click' : function (evt) {_vm.test(personItem,evt)}}} , [_l((function () {return _vm.menu}),function(item,index){return _c('div', [_c('text', {'attrs' : {'value' : function () {return (personItem.id) + decodeURI('--') + (item.name)}}} )] )})] )}),_l((function () {return _vm.list}),function(personItem,personIndex){return _c('div', {'onBubbleEvents' : {'click' : function (evt) {_vm.test(personItem,evt)}}} , [_l((function () {return personItem}),function(item,index){return _c('div', [_c('text', {'attrs' : {'value' : function () {return (index) + decodeURI('--') + (item.name)}}} )] )})] )}),_l((function () {return _vm.list}),function(personItem,personIndex){return _c('div', {'onBubbleEvents' : {'click' : function (evt) {_vm.test(personItem,evt)}}} , [_c('div', {'attrs' : {'value' : function () {return (personIndex) + decodeURI('.') + (personItem.name)}},'onBubbleEvents' : {'click' : personItem.click}} )] )}),_l((function () {return value.list}),function(index,value){return _c('div', {'onBubbleEvents' : {'click' : function (evt) {_vm.test(value,evt)}}} , [_c('div', {'attrs' : {'value' : function () {return value.info}},'onBubbleEvents' : {'click' : value.click}} )] )})] ) }"} +{"render": "function (vm) { var _vm = vm || this; return _c('div', [_l((function () {return _vm.list}),function($item,$idx){return _c('div', {'onBubbleEvents' : {'click' : function (evt) {_vm.test($item,evt)}}} , [_c('text', {'attrs' : {'value' : function () {return ($idx) + decodeURI('.') + ($item.name)}}} )] )}),_c('div', [_l((function () {return _vm.list}),function(personItem,$idx){return _c('div', {'onBubbleEvents' : {'click' : function (evt) {_vm.test($idx,evt)}}} , [_c('text', {'attrs' : {'value' : function () {return ($idx) + decodeURI('-') + (personItem.name) + decodeURI('--') + (personItem.age)}}} )] )}),_c('image', {'attrs' : {'src' : function () {return _vm.personItem}}} )] ),_c('div', [_l((function () {return _vm.list}),function(personItem,personIndex){return _c('div', {'onBubbleEvents' : {'click' : function (evt) {_vm.test(personItem,evt)}}} , [_c('text', {'attrs' : {'value' : function () {return (personIndex) + decodeURI('.') + (personItem.name)}}} )] )}),_c('swiper', {'attrs' : {'index' : function () {return _vm.personIndex},'loop' : function () {return _vm.personItem}}} )] ),_l((function () {return _vm.list}),function(personItem,personIndex){return _c('div', {'onBubbleEvents' : {'click' : function (evt) {_vm.test(personItem,evt)}}} , [_l((function () {return _vm.menu}),function(item,index){return _c('div', [_c('text', {'attrs' : {'value' : function () {return (personItem.id) + decodeURI('--') + (item.name)}}} )] )})] )}),_l((function () {return _vm.list}),function(personItem,personIndex){return _c('div', {'onBubbleEvents' : {'click' : function (evt) {_vm.test(personItem,evt)}}} , [_l((function () {return personItem}),function(item,index){return _c('div', [_c('text', {'attrs' : {'value' : function () {return (index) + decodeURI('--') + (item.name)}}} )] )})] )}),_l((function () {return _vm.list}),function(personItem,personIndex){return _c('div', {'onBubbleEvents' : {'click' : function (evt) {_vm.test(personItem,evt)}}} , [_c('div', {'attrs' : {'value' : function () {return (personIndex) + decodeURI('.') + (personItem.name)}},'onBubbleEvents' : {'click' : personItem.click}} )] )}),_l((function () {return value.list}),function(index,value){return _c('div', {'onBubbleEvents' : {'click' : function (evt) {_vm.test(value,evt)}}} , [_c('div', {'attrs' : {'value' : function () {return value.info}},'onBubbleEvents' : {'click' : value.click}} )] )})] ) }"} \ No newline at end of file diff --git a/ace-loader/test/lite/expected/ifDirective.js b/ace-loader/test/lite/expected/ifDirective.js index a11efd3..2d41dda 100644 --- a/ace-loader/test/lite/expected/ifDirective.js +++ b/ace-loader/test/lite/expected/ifDirective.js @@ -13,4 +13,4 @@ * limitations under the License. */ -{"render": "function (vm) { var _vm = vm || this; return _c('div', [_i((function () {return _vm.conditionVar===1}),function(){return _c('text', {'attrs' : {'value' : function () {return _vm.componentData.if}}} )}),_c('div', {'staticClass' : [\"item-content\"]} , [_i((function () {return _vm.conditionVar===1}),function(){return _c('text', {'attrs' : {'value' : function () {return _vm.componentData.if}}} )}),_i((function () {return _vm.conditionVar===2&&!(_vm.conditionVar===1)}),function(){return _c('text', {'attrs' : {'value' : function () {return _vm.componentData.elif}}} )}),_i((function () {return !(_vm.conditionVar===2)&&!(_vm.conditionVar===1)}),function(){return _c('text', {'attrs' : {'value' : function () {return _vm.componentData.else}}} )})] ),_i((function () {return _vm.showTest}),function(){return _c('div', [_l((function () {return _vm.list}),function($item,$idx){return _c('div', [_c('text', {'attrs' : {'value' : function () {return ($idx) + decodeURI('.') + ($item.name)}}} )] )})] )}),_l((function () {return _vm.list}),function($item,$idx){return _c('div', [_i((function () {return _vm.showTest}),function(){return _c('div', [_c('text', {'attrs' : {'value' : function () {return ($idx) + decodeURI('.') + ($item.name)}}} )] )})] )}),_l((function () {return _vm.list}),function(personItem,personIndex){return _c('div', [_i((function () {return personIndex==1}),function(){return _c('div', [_c('text', {'attrs' : {'value' : function () {return personItem.name}}} )] )})] )})] ) }"} +{"render": "function (vm) { var _vm = vm || this; return _c('div', [_i((function () {return _vm.conditionVar===1}),function(){return _c('text', {'attrs' : {'value' : function () {return _vm.componentData.if}}} )}),_c('div', {'staticClass' : [\"item-content\"]} , [_i((function () {return _vm.conditionVar===1}),function(){return _c('text', {'attrs' : {'value' : function () {return _vm.componentData.if}}} )}),_i((function () {return _vm.conditionVar===2&&!(_vm.conditionVar===1)}),function(){return _c('text', {'attrs' : {'value' : function () {return _vm.componentData.elif}}} )}),_i((function () {return !(_vm.conditionVar===2)&&!(_vm.conditionVar===1)}),function(){return _c('text', {'attrs' : {'value' : function () {return _vm.componentData.else}}} )})] ),_i((function () {return _vm.showTest}),function(){return _c('div', [_l((function () {return _vm.list}),function($item,$idx){return _c('div', [_c('text', {'attrs' : {'value' : function () {return ($idx) + decodeURI('.') + ($item.name)}}} )] )})] )}),_l((function () {return _vm.list}),function($item,$idx){return _c('div', [_i((function () {return _vm.showTest}),function(){return _c('div', [_c('text', {'attrs' : {'value' : function () {return ($idx) + decodeURI('.') + ($item.name)}}} )] )})] )}),_l((function () {return _vm.list}),function(personItem,personIndex){return _c('div', [_i((function () {return personIndex==1}),function(){return _c('div', [_c('text', {'attrs' : {'value' : function () {return personItem.name}}} )] )})] )})] ) }"} \ No newline at end of file diff --git a/ace-loader/test/lite/expected/inlineStyle.js b/ace-loader/test/lite/expected/inlineStyle.js index 9d8ac2b..ce11834 100644 --- a/ace-loader/test/lite/expected/inlineStyle.js +++ b/ace-loader/test/lite/expected/inlineStyle.js @@ -13,4 +13,4 @@ * limitations under the License. */ -{"render": "function (vm) { var _vm = vm || this; return _c('div', [_c('div', {'staticStyle' : {'width' : 10}, } ),_c('div', {'dynamicStyle' :{'height' : function () {return _vm.num}}} ),_c('text', {'staticStyle' : {'color' : 13047173}, } ),_c('div', {'staticStyle' : {'color' : 14745599}, } ),_c('div', {'staticStyle' : {'animationDelay' : \"900ms\"}, } ),_c('div', {'staticStyle' : {'animationDuration' : \"200ms\"}, } ),_c('div', {'staticStyle' : {'animationIterationCount' : \"infinite\"}, } ),_c('div', {'staticStyle' : {'animationIterationCount' : 1000}, } ),_c('div', {'staticStyle' : {'backgroundImage' : \"url(/common/img/xmad.jpg)\"}, } ),_c('div', {'staticStyle' : {'backgroundImage' : \"url(/common/img/map.jpg)\"}, } )] ) }"} +{"render": "function (vm) { var _vm = vm || this; return _c('div', [_c('div', {'staticStyle' : {'width' : 10}, } ),_c('div', {'dynamicStyle' :{'height' : function () {return _vm.num}}} ),_c('text', {'staticStyle' : {'color' : 13047173}, } ),_c('div', {'staticStyle' : {'color' : 14745599}, } ),_c('div', {'staticStyle' : {'animationDelay' : \"900ms\"}, } ),_c('div', {'staticStyle' : {'animationDuration' : \"200ms\"}, } ),_c('div', {'staticStyle' : {'animationIterationCount' : \"infinite\"}, } ),_c('div', {'staticStyle' : {'animationIterationCount' : 1000}, } ),_c('div', {'staticStyle' : {'backgroundImage' : \"url(/common/img/xmad.jpg)\"}, } ),_c('div', {'staticStyle' : {'backgroundImage' : \"url(/common/img/map.jpg)\"}, } )] ) }"} \ No newline at end of file diff --git a/ace-loader/test/rich/test.js b/ace-loader/test/rich/test.js index 3c79264..7d86d42 100644 --- a/ace-loader/test/rich/test.js +++ b/ace-loader/test/rich/test.js @@ -1,20 +1,16 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ 'use strict'; diff --git a/ace-loader/test/rich/testcase/pages/class/class.js b/ace-loader/test/rich/testcase/pages/class/class.js index 2e73d04..d8fdade 100644 --- a/ace-loader/test/rich/testcase/pages/class/class.js +++ b/ace-loader/test/rich/testcase/pages/class/class.js @@ -12,3 +12,4 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + diff --git a/ace-loader/test/rich/testcase/pages/ifDirective/ifDirective.js b/ace-loader/test/rich/testcase/pages/ifDirective/ifDirective.js index e69de29..d8fdade 100644 --- a/ace-loader/test/rich/testcase/pages/ifDirective/ifDirective.js +++ b/ace-loader/test/rich/testcase/pages/ifDirective/ifDirective.js @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + diff --git a/ace-loader/webpack.rich.config.js b/ace-loader/webpack.rich.config.js index 0064f87..1d78e6d 100644 --- a/ace-loader/webpack.rich.config.js +++ b/ace-loader/webpack.rich.config.js @@ -40,7 +40,7 @@ const richModule = { }] }, { - test: /(\.hml|app\.js|data\.js|service\.js)(\?[^?]+)?$/, + test: /(\.hml)(\?[^?]+)?$/, use: [{ loader: path.resolve(__dirname, './index.js') }] @@ -137,9 +137,32 @@ let config = { poll: false, ignored: /node_modules/ }, + optimization: { + splitChunks: { + chunks: "all", + minSize: 0, + cacheGroups: { + vendors: { + test: /[\\/]node_modules[\\/]/, + priority: -10, + name: "vendors", + chunks: 'initial' + }, + commons: { + test: /\.js|css|hml$/, + name: 'commons', + priority: -20, + minChunks: 2, + chunks: 'initial', + reuseExistingChunk: true + } + } + }, + }, output: { filename: '[name].js', - devtoolModuleFilenameTemplate: 'webpack:///[absolute-resource-path]' + devtoolModuleFilenameTemplate: 'webpack:///[absolute-resource-path]', + globalObject: 'globalThis' }, devtool: 'nosources-source-map', mode: 'development', @@ -164,7 +187,7 @@ function setConfigs(env) { process.env.aceManifestPath = process.env.aceManifestPath || path.resolve(process.env.projectPath, 'manifest.json'); process.env.abilityType = process.env.abilityType || 'page' process.env.DEVICE_LEVEL = process.env.DEVICE_LEVEL || 'rich' - if (process.env.abilityType === 'page') { + if (process.env.abilityType === 'page' || process.env.abilityType === 'form') { const manifest = readManifest(process.env.aceManifestPath) process.env.DEVICE_LEVEL = manifest.type === 'form' ? 'card' : 'rich' process.env.PLATFORM_VERSION = PLATFORM.VERSION6; @@ -183,13 +206,6 @@ module.exports = (env) => { setConfigs(env) deleteFolderRecursive(process.env.buildPath); config.cache.cacheDirectory = path.resolve(process.env.cachePath, '.rich_cache'); - config.module.rules.push({ - test: new RegExp("(" + (process.env.abilityType === 'page' ? - 'app' : process.env.abilityType) + "\.js)(\\?[^?]+)?$"), - use: [{ - loader: path.resolve(__dirname, './index.js') - }] - }) config.entry = loadEntryObj(process.env.projectPath, process.env.DEVICE_LEVEL, process.env.abilityType, process.env.aceManifestPath) config.output.path = path.resolve(__dirname, process.env.buildPath) @@ -218,6 +234,17 @@ module.exports = (env) => { ] })) } + if (process.env.aceConfigPath && fs.existsSync(process.env.aceConfigPath)) { + config.plugins.push(new CopyPlugin({ + patterns: [ + { + from: path.resolve(process.env.aceConfigPath), + to: path.resolve(process.env.buildPath, 'config.json'), + noErrorOnMissing: true + } + ] + })) + } if (process.env.DEVICE_LEVEL === 'card') { config.module = cardModule config.plugins.push(new AfterEmitPlugin()) @@ -225,7 +252,11 @@ module.exports = (env) => { if (env.isPreview !== "true") { config.plugins.push(new ModuleCollectionPlugin()) if (env.compilerType && env.compilerType === 'ark') { - config.plugins.push(new GenAbcPlugin(process.env.buildPath, path.join(__dirname, 'bin'), + let arkDir = path.join(__dirname, 'bin', 'ark'); + if (env.arkFrontendDir) { + arkDir = env.arkFrontendDir; + } + config.plugins.push(new GenAbcPlugin(process.env.buildPath, arkDir, env.buildMode === 'debug')) } else { if (env.deviceType) { @@ -267,5 +298,12 @@ module.exports = (env) => { config.output.sourceMapFilename = '_releaseMap/[name].js.map' } } + config.module.rules.push({ + test: new RegExp("(" + (process.env.abilityType === 'page' ? + 'app' : process.env.abilityType) + "\.js)(\\?[^?]+)?$"), + use: [{ + loader: path.resolve(__dirname, './index.js') + }] + }) return config -} +} \ No newline at end of file