diff --git a/.gitignore b/.gitignore index 91cc1be145fe9ad2ef03870ad25d1a4d7e46692c..eaa3c668f4d660204088d3b7a035951fd293817d 100644 --- a/.gitignore +++ b/.gitignore @@ -4,4 +4,5 @@ compiler/lib/ compiler/declarations/ compiler/sample/build/ compiler/component_config.json +compiler/form_config.json compiler/syntax_parser/dist/ \ No newline at end of file diff --git a/BUILD.gn b/BUILD.gn index 9296e50a9afa7e12aa8368313dd9dbf8fbc8b450..3d3db65ae6c2047cbef5e64e152540d569394a9b 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -23,28 +23,30 @@ if (sdk_build_public) { ets_loader_lib_dir = get_label_info(":build_ets_loader_library", "target_out_dir") + "/lib" -ets_loader_syntax_dir = get_label_info(":build_ets_loader_library", - "target_out_dir") + "/syntax_parser/dist" ets_loader_declarations_dir = get_label_info(":build_ets_loader_library", "target_out_dir") + "/declarations" ets_loader_component_config_file = get_label_info(":build_ets_loader_library", "target_out_dir") + "/component_config.json" +ets_loader_form_config_file = + get_label_info(":build_ets_loader_library", "target_out_dir") + + "/form_config.json" ets_sysResource = get_label_info(":build_ets_sysResource", "target_out_dir") + "/sysResource.js" action("build_ets_loader_library") { deps = [ ":components", + ":form_components", ":server", ] script = "build_ets_loader_library.py" depfile = "$target_gen_dir/$target_name.d" outputs = [ ets_loader_lib_dir, - ets_loader_syntax_dir, ets_loader_declarations_dir, ets_loader_component_config_file, + ets_loader_form_config_file, ] _ets_loader_dir = "compiler" @@ -62,14 +64,12 @@ action("build_ets_loader_library") { _babel_js = _ace_config_dir + "/node_modules/@babel/cli/bin/babel.js" _babel_config_js = _ace_config_dir + "/babel.config.js" _uglify_source_js = _ace_config_dir + "/uglify-source.js" - _build_parser_js = _ace_config_dir + "/build_parser.js" _build_declarations_file_js = _ace_config_dir + "/build_declarations_file.js" inputs = [ _babel_config_js, _babel_js, _uglify_source_js, - _build_parser_js, _build_declarations_file_js, ] @@ -101,18 +101,12 @@ action("build_ets_loader_library") { rebase_path(_babel_js, root_build_dir), "--ets-loader-src-dir", rebase_path(_ets_loader_dir + "/src", root_build_dir), - "--ets-loader-syntax-src-dir", - rebase_path(_ets_loader_dir + "/syntax_parser/src", root_build_dir), "--babel-config-js", rebase_path(_babel_config_js, root_build_dir), "--uglify-source-js", rebase_path(_uglify_source_js, root_build_dir), - "--build-parser-js", - rebase_path(_build_parser_js, root_build_dir), "--output-dir", rebase_path(ets_loader_lib_dir, root_build_dir), - "--output-syntax-dir", - rebase_path(ets_loader_syntax_dir, root_build_dir), "--declarations-file-dir", rebase_path(_declarations_file_dir, root_build_dir), "--build-declarations-file-js", @@ -121,6 +115,8 @@ action("build_ets_loader_library") { rebase_path(ets_loader_declarations_dir, root_build_dir), "--output-component-config-file", rebase_path(ets_loader_component_config_file, root_build_dir), + "--output-form-config-file", + rebase_path(ets_loader_form_config_file, root_build_dir), ] } @@ -132,7 +128,7 @@ action("build_ets_sysResource") { } outputs = [ ets_sysResource ] - _id_defined_json = "//utils/system_resources/systemres/main/resources/base/element/id_defined.json" + _id_defined_json = "//base/global/system_resources/systemres/main/resources/base/element/id_defined.json" inputs = [ _id_defined_json ] args = [ @@ -144,10 +140,12 @@ action("build_ets_sysResource") { } ets_loader_sources = [ + "compiler/compile_plugin.js", "compiler/main.js", "compiler/npm-install.js", "compiler/package-lock.json", "compiler/package.json", + "compiler/rollup.config.js", "compiler/tsconfig.esm.json", "compiler/tsconfig.json", "compiler/webpack.config.js", @@ -185,17 +183,18 @@ ohos_copy("ets_loader_component_config") { module_install_name = "" } -ohos_copy("ets_loader_library") { +ohos_copy("ets_loader_form_config") { deps = [ ":build_ets_loader_library" ] - sources = [ ets_loader_lib_dir ] - outputs = [ target_out_dir + "/$target_name" ] + sources = [ ets_loader_form_config_file ] + + outputs = [ target_out_dir + "/$target_name/{{source_file_part}}" ] module_source_dir = target_out_dir + "/$target_name" module_install_name = "" } -ohos_copy("ets_loader_syntax") { +ohos_copy("ets_loader_library") { deps = [ ":build_ets_loader_library" ] - sources = [ ets_loader_syntax_dir ] + sources = [ ets_loader_lib_dir ] outputs = [ target_out_dir + "/$target_name" ] module_source_dir = target_out_dir + "/$target_name" module_install_name = "" @@ -208,6 +207,13 @@ ohos_copy("components") { module_install_name = "" } +ohos_copy("form_components") { + sources = [ "compiler/form_components" ] + outputs = [ target_out_dir + "/$target_name" ] + module_source_dir = target_out_dir + "/$target_name" + module_install_name = "" +} + ohos_copy("server") { sources = [ "compiler/server" ] outputs = [ target_out_dir + "/$target_name" ] @@ -256,22 +262,22 @@ ohos_copy("ets_loader_ark_declaration") { outputs = [ target_out_dir + "/ets_loader_ark/declarations" ] } -ohos_copy("ets_loader_ark_syntax") { +ohos_copy("ets_loader_ark_components") { deps = [ ":build_ets_loader_library", ":ets_loader_ark", ] - sources = [ ets_loader_syntax_dir ] - outputs = [ target_out_dir + "/ets_loader_ark/syntax_parser/dist" ] + sources = [ "compiler/components" ] + outputs = [ target_out_dir + "/ets_loader_ark/components" ] } -ohos_copy("ets_loader_ark_components") { +ohos_copy("ets_loader_ark_form_components") { deps = [ ":build_ets_loader_library", ":ets_loader_ark", ] - sources = [ "compiler/components" ] - outputs = [ target_out_dir + "/ets_loader_ark/components" ] + sources = [ "compiler/form_components" ] + outputs = [ target_out_dir + "/ets_loader_ark/form_components" ] } ohos_copy("ets_loader_ark_server") { @@ -319,9 +325,9 @@ ohos_copy("ets_loader_node_modules") { ":ets_loader_ark_codegen", ":ets_loader_ark_components", ":ets_loader_ark_declaration", + ":ets_loader_ark_form_components", ":ets_loader_ark_lib", ":ets_loader_ark_server", - ":ets_loader_ark_syntax", ] sources = [ "//developtools/ace_ets2bundle/compiler/node_modules" ] outputs = [ target_out_dir + "/ets_loader_ark/node_modules" ] diff --git a/build_ets_loader_library.py b/build_ets_loader_library.py index 592f315525ed01e13654fc531b3626d6b1ce6c8e..01dfcfae03e53d7021df30c8bbca8795b3f8ccf0 100755 --- a/build_ets_loader_library.py +++ b/build_ets_loader_library.py @@ -39,14 +39,9 @@ def parse_args(): parser.add_argument('--node', help='path to nodejs exetuable') parser.add_argument('--babel-js', help='path to babel.js') parser.add_argument('--ets-loader-src-dir', help='path to compiler/src') - parser.add_argument('--ets-loader-syntax-src-dir', - help='path to compiler/syntax_parser/src') parser.add_argument('--babel-config-js', help='path babel.config.js') parser.add_argument('--uglify-source-js', help='path uglify-source.js') - parser.add_argument('--build-parser-js', help='path build_parser.js') parser.add_argument('--output-dir', help='path to output') - parser.add_argument('--output-syntax-dir', - help='path syntax file to output') parser.add_argument('--declarations-file-dir', help='path declarations file') parser.add_argument('--build-declarations-file-js', @@ -55,14 +50,15 @@ def parse_args(): help='path declarations file to output') parser.add_argument('--output-component-config-file', help='path component config file to output') + parser.add_argument('--output-form-config-file', + help='path form config file to output') options = parser.parse_args() return options -def do_build(build_cmd, uglify_cmd, syntax_cmd, build_declarations_file_cmd): - for cmd in [build_cmd, uglify_cmd, syntax_cmd, - build_declarations_file_cmd]: +def do_build(build_cmd, uglify_cmd, build_declarations_file_cmd): + for cmd in [build_cmd, uglify_cmd, build_declarations_file_cmd]: build_utils.check_output(cmd) @@ -76,16 +72,10 @@ def main(): build_cmd.extend(['--config-file', options.babel_config_js]) depfile_deps = [options.node, options.babel_js, options.babel_config_js] depfile_deps.extend(build_utils.get_all_files(options.ets_loader_src_dir)) - depfile_deps.extend( - build_utils.get_all_files(options.ets_loader_syntax_src_dir)) uglify_cmd = [options.node, options.uglify_source_js, options.output_dir] depfile_deps.append(options.uglify_source_js) - syntax_cmd = [options.node, options.build_parser_js, - options.output_syntax_dir, options.ets_loader_src_dir] - depfile_deps.append(options.build_parser_js) - build_declarations_file_cmd = [options.node, options.build_declarations_file_js, options.declarations_file_dir, @@ -94,16 +84,15 @@ def main(): depfile_deps.append(options.build_declarations_file_js) build_utils.call_and_write_depfile_if_stale( - lambda: do_build(build_cmd, uglify_cmd, - syntax_cmd, build_declarations_file_cmd), + lambda: do_build(build_cmd, uglify_cmd, build_declarations_file_cmd), options, depfile_deps=depfile_deps, input_paths=depfile_deps, output_paths=([ options.output_dir, - options.output_syntax_dir, options.output_declarations_dir, - options.output_component_config_file])) + options.output_component_config_file, + options.output_form_config_file])) if __name__ == '__main__': sys.exit(main()) diff --git a/compiler/build_declarations_file.js b/compiler/build_declarations_file.js index 8fd255905d96299d240677ad54f8ef52bf753f6b..806a388c41bed13f2f1dcb5c115b979360c03207 100644 --- a/compiler/build_declarations_file.js +++ b/compiler/build_declarations_file.js @@ -28,7 +28,7 @@ const addTSAttributeSet = ['AlphabetIndexer', 'Animator', 'Badge', 'Blank', 'But 'QRCode', 'Radio', 'Rating', 'Rect', 'Refresh', 'Row', 'RowSplit', 'Scroll', 'ScrollBar', 'Search', 'Select', 'Shape', 'Sheet', 'Slider', 'Span', 'Stack', 'Stepper', 'StepperItem', 'Swiper', 'TabContent', 'Tabs', 'Text', 'TextArea', 'TextClock', 'TextInput', 'TextPicker', 'TextTimer', - 'Toggle', 'Video', 'Web', 'XComponent', 'RichText', 'RemoteWindow']; + 'Toggle', 'Video', 'Web', 'XComponent', 'RichText', 'RemoteWindow', 'WaterFlow', 'FlowItem']; generateTargetFile(process.argv[2], process.argv[3]); function generateTargetFile(filePath, output) { @@ -215,9 +215,10 @@ generateComponentConfig(process.argv[4]); function generateComponentConfig(dir) { const configFile = path.resolve(dir, 'component_map.js'); if (fs.existsSync(configFile)) { - const { COMPONENT_MAP } = require(configFile); + const { COMPONENT_MAP, FORM_MAP } = require(configFile); try { fs.writeFileSync(path.resolve(dir, '../component_config.json'), JSON.stringify(COMPONENT_MAP)); + fs.writeFileSync(path.resolve(dir, '../form_config.json'), JSON.stringify(FORM_MAP)); } catch (error) { console.error(error); } diff --git a/compiler/codegen/codegen_ets.js b/compiler/codegen/codegen_ets.js index 2a21775040c81e10cec0745e1be5a1a7903338a7..8dcc55a8c6955976d4459296344fde3aee1d09b4 100644 --- a/compiler/codegen/codegen_ets.js +++ b/compiler/codegen/codegen_ets.js @@ -12,5 +12,4 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -(()=>{var e={486:function(e,t,r){var n;e=r.nmd(e),function(){var o,i="Expected a function",a="__lodash_hash_undefined__",s="__lodash_placeholder__",c=32,u=128,l=1/0,p=9007199254740991,f=NaN,d=4294967295,y=[["ary",u],["bind",1],["bindKey",2],["curry",8],["curryRight",16],["flip",512],["partial",c],["partialRight",64],["rearg",256]],h="[object Arguments]",m="[object Array]",g="[object Boolean]",E="[object Date]",v="[object Error]",T="[object Function]",S="[object GeneratorFunction]",_="[object Map]",N="[object Number]",A="[object Object]",C="[object Promise]",w="[object RegExp]",b="[object Set]",R="[object String]",O="[object Symbol]",I="[object WeakMap]",M="[object ArrayBuffer]",P="[object DataView]",x="[object Float32Array]",L="[object Float64Array]",k="[object Int8Array]",F="[object Int16Array]",D="[object Int32Array]",U="[object Uint8Array]",B="[object Uint8ClampedArray]",G="[object Uint16Array]",z="[object Uint32Array]",j=/\b__p \+= '';/g,V=/\b(__p \+=) '' \+/g,W=/(__e\(.*?\)|\b__t\)) \+\n'';/g,$=/&(?:amp|lt|gt|quot|#39);/g,q=/[&<>"']/g,H=RegExp($.source),Y=RegExp(q.source),Q=/<%-([\s\S]+?)%>/g,X=/<%([\s\S]+?)%>/g,J=/<%=([\s\S]+?)%>/g,K=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Z=/^\w*$/,ee=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,te=/[\\^$.*+?()[\]{}|]/g,re=RegExp(te.source),ne=/^\s+/,oe=/\s/,ie=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,ae=/\{\n\/\* \[wrapped with (.+)\] \*/,se=/,? & /,ce=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,ue=/[()=,{}\[\]\/\s]/,le=/\\(\\)?/g,pe=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,fe=/\w*$/,de=/^[-+]0x[0-9a-f]+$/i,ye=/^0b[01]+$/i,he=/^\[object .+?Constructor\]$/,me=/^0o[0-7]+$/i,ge=/^(?:0|[1-9]\d*)$/,Ee=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,ve=/($^)/,Te=/['\n\r\u2028\u2029\\]/g,Se="\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff",_e="a-z\\xdf-\\xf6\\xf8-\\xff",Ne="A-Z\\xc0-\\xd6\\xd8-\\xde",Ae="\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",Ce="["+Ae+"]",we="["+Se+"]",be="\\d+",Re="["+_e+"]",Oe="[^\\ud800-\\udfff"+Ae+be+"\\u2700-\\u27bf"+_e+Ne+"]",Ie="\\ud83c[\\udffb-\\udfff]",Me="[^\\ud800-\\udfff]",Pe="(?:\\ud83c[\\udde6-\\uddff]){2}",xe="[\\ud800-\\udbff][\\udc00-\\udfff]",Le="["+Ne+"]",ke="(?:"+Re+"|"+Oe+")",Fe="(?:"+Le+"|"+Oe+")",De="(?:['’](?:d|ll|m|re|s|t|ve))?",Ue="(?:['’](?:D|LL|M|RE|S|T|VE))?",Be="(?:"+we+"|"+Ie+")?",Ge="[\\ufe0e\\ufe0f]?",ze=Ge+Be+"(?:\\u200d(?:"+[Me,Pe,xe].join("|")+")"+Ge+Be+")*",je="(?:"+["[\\u2700-\\u27bf]",Pe,xe].join("|")+")"+ze,Ve="(?:"+[Me+we+"?",we,Pe,xe,"[\\ud800-\\udfff]"].join("|")+")",We=RegExp("['’]","g"),$e=RegExp(we,"g"),qe=RegExp(Ie+"(?="+Ie+")|"+Ve+ze,"g"),He=RegExp([Le+"?"+Re+"+"+De+"(?="+[Ce,Le,"$"].join("|")+")",Fe+"+"+Ue+"(?="+[Ce,Le+ke,"$"].join("|")+")",Le+"?"+ke+"+"+De,Le+"+"+Ue,"\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])","\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",be,je].join("|"),"g"),Ye=RegExp("[\\u200d\\ud800-\\udfff"+Se+"\\ufe0e\\ufe0f]"),Qe=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,Xe=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],Je=-1,Ke={};Ke[x]=Ke[L]=Ke[k]=Ke[F]=Ke[D]=Ke[U]=Ke[B]=Ke[G]=Ke[z]=!0,Ke[h]=Ke[m]=Ke[M]=Ke[g]=Ke[P]=Ke[E]=Ke[v]=Ke[T]=Ke[_]=Ke[N]=Ke[A]=Ke[w]=Ke[b]=Ke[R]=Ke[I]=!1;var Ze={};Ze[h]=Ze[m]=Ze[M]=Ze[P]=Ze[g]=Ze[E]=Ze[x]=Ze[L]=Ze[k]=Ze[F]=Ze[D]=Ze[_]=Ze[N]=Ze[A]=Ze[w]=Ze[b]=Ze[R]=Ze[O]=Ze[U]=Ze[B]=Ze[G]=Ze[z]=!0,Ze[v]=Ze[T]=Ze[I]=!1;var et={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},tt=parseFloat,rt=parseInt,nt="object"==typeof r.g&&r.g&&r.g.Object===Object&&r.g,ot="object"==typeof self&&self&&self.Object===Object&&self,it=nt||ot||Function("return this")(),at=t&&!t.nodeType&&t,st=at&&e&&!e.nodeType&&e,ct=st&&st.exports===at,ut=ct&&nt.process,lt=function(){try{return st&&st.require&&st.require("util").types||ut&&ut.binding&&ut.binding("util")}catch(e){}}(),pt=lt&<.isArrayBuffer,ft=lt&<.isDate,dt=lt&<.isMap,yt=lt&<.isRegExp,ht=lt&<.isSet,mt=lt&<.isTypedArray;function gt(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)}function Et(e,t,r,n){for(var o=-1,i=null==e?0:e.length;++o-1}function At(e,t,r){for(var n=-1,o=null==e?0:e.length;++n-1;);return r}function Ht(e,t){for(var r=e.length;r--&&xt(t,e[r],0)>-1;);return r}function Yt(e,t){for(var r=e.length,n=0;r--;)e[r]===t&&++n;return n}var Qt=Ut({À:"A",Á:"A",Â:"A",Ã:"A",Ä:"A",Å:"A",à:"a",á:"a",â:"a",ã:"a",ä:"a",å:"a",Ç:"C",ç:"c",Ð:"D",ð:"d",È:"E",É:"E",Ê:"E",Ë:"E",è:"e",é:"e",ê:"e",ë:"e",Ì:"I",Í:"I",Î:"I",Ï:"I",ì:"i",í:"i",î:"i",ï:"i",Ñ:"N",ñ:"n",Ò:"O",Ó:"O",Ô:"O",Õ:"O",Ö:"O",Ø:"O",ò:"o",ó:"o",ô:"o",õ:"o",ö:"o",ø:"o",Ù:"U",Ú:"U",Û:"U",Ü:"U",ù:"u",ú:"u",û:"u",ü:"u",Ý:"Y",ý:"y",ÿ:"y",Æ:"Ae",æ:"ae",Þ:"Th",þ:"th",ß:"ss",Ā:"A",Ă:"A",Ą:"A",ā:"a",ă:"a",ą:"a",Ć:"C",Ĉ:"C",Ċ:"C",Č:"C",ć:"c",ĉ:"c",ċ:"c",č:"c",Ď:"D",Đ:"D",ď:"d",đ:"d",Ē:"E",Ĕ:"E",Ė:"E",Ę:"E",Ě:"E",ē:"e",ĕ:"e",ė:"e",ę:"e",ě:"e",Ĝ:"G",Ğ:"G",Ġ:"G",Ģ:"G",ĝ:"g",ğ:"g",ġ:"g",ģ:"g",Ĥ:"H",Ħ:"H",ĥ:"h",ħ:"h",Ĩ:"I",Ī:"I",Ĭ:"I",Į:"I",İ:"I",ĩ:"i",ī:"i",ĭ:"i",į:"i",ı:"i",Ĵ:"J",ĵ:"j",Ķ:"K",ķ:"k",ĸ:"k",Ĺ:"L",Ļ:"L",Ľ:"L",Ŀ:"L",Ł:"L",ĺ:"l",ļ:"l",ľ:"l",ŀ:"l",ł:"l",Ń:"N",Ņ:"N",Ň:"N",Ŋ:"N",ń:"n",ņ:"n",ň:"n",ŋ:"n",Ō:"O",Ŏ:"O",Ő:"O",ō:"o",ŏ:"o",ő:"o",Ŕ:"R",Ŗ:"R",Ř:"R",ŕ:"r",ŗ:"r",ř:"r",Ś:"S",Ŝ:"S",Ş:"S",Š:"S",ś:"s",ŝ:"s",ş:"s",š:"s",Ţ:"T",Ť:"T",Ŧ:"T",ţ:"t",ť:"t",ŧ:"t",Ũ:"U",Ū:"U",Ŭ:"U",Ů:"U",Ű:"U",Ų:"U",ũ:"u",ū:"u",ŭ:"u",ů:"u",ű:"u",ų:"u",Ŵ:"W",ŵ:"w",Ŷ:"Y",ŷ:"y",Ÿ:"Y",Ź:"Z",Ż:"Z",Ž:"Z",ź:"z",ż:"z",ž:"z",IJ:"IJ",ij:"ij",Œ:"Oe",œ:"oe",ʼn:"'n",ſ:"s"}),Xt=Ut({"&":"&","<":"<",">":">",'"':""","'":"'"});function Jt(e){return"\\"+et[e]}function Kt(e){return Ye.test(e)}function Zt(e){var t=-1,r=Array(e.size);return e.forEach((function(e,n){r[++t]=[n,e]})),r}function er(e,t){return function(r){return e(t(r))}}function tr(e,t){for(var r=-1,n=e.length,o=0,i=[];++r",""":'"',"'":"'"}),cr=function e(t){var r,n=(t=null==t?it:cr.defaults(it.Object(),t,cr.pick(it,Xe))).Array,oe=t.Date,Se=t.Error,_e=t.Function,Ne=t.Math,Ae=t.Object,Ce=t.RegExp,we=t.String,be=t.TypeError,Re=n.prototype,Oe=_e.prototype,Ie=Ae.prototype,Me=t["__core-js_shared__"],Pe=Oe.toString,xe=Ie.hasOwnProperty,Le=0,ke=(r=/[^.]+$/.exec(Me&&Me.keys&&Me.keys.IE_PROTO||""))?"Symbol(src)_1."+r:"",Fe=Ie.toString,De=Pe.call(Ae),Ue=it._,Be=Ce("^"+Pe.call(xe).replace(te,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Ge=ct?t.Buffer:o,ze=t.Symbol,je=t.Uint8Array,Ve=Ge?Ge.allocUnsafe:o,qe=er(Ae.getPrototypeOf,Ae),Ye=Ae.create,et=Ie.propertyIsEnumerable,nt=Re.splice,ot=ze?ze.isConcatSpreadable:o,at=ze?ze.iterator:o,st=ze?ze.toStringTag:o,ut=function(){try{var e=li(Ae,"defineProperty");return e({},"",{}),e}catch(e){}}(),lt=t.clearTimeout!==it.clearTimeout&&t.clearTimeout,It=oe&&oe.now!==it.Date.now&&oe.now,Ut=t.setTimeout!==it.setTimeout&&t.setTimeout,ur=Ne.ceil,lr=Ne.floor,pr=Ae.getOwnPropertySymbols,fr=Ge?Ge.isBuffer:o,dr=t.isFinite,yr=Re.join,hr=er(Ae.keys,Ae),mr=Ne.max,gr=Ne.min,Er=oe.now,vr=t.parseInt,Tr=Ne.random,Sr=Re.reverse,_r=li(t,"DataView"),Nr=li(t,"Map"),Ar=li(t,"Promise"),Cr=li(t,"Set"),wr=li(t,"WeakMap"),br=li(Ae,"create"),Rr=wr&&new wr,Or={},Ir=Bi(_r),Mr=Bi(Nr),Pr=Bi(Ar),xr=Bi(Cr),Lr=Bi(wr),kr=ze?ze.prototype:o,Fr=kr?kr.valueOf:o,Dr=kr?kr.toString:o;function Ur(e){if(rs(e)&&!$a(e)&&!(e instanceof jr)){if(e instanceof zr)return e;if(xe.call(e,"__wrapped__"))return Gi(e)}return new zr(e)}var Br=function(){function e(){}return function(t){if(!ts(t))return{};if(Ye)return Ye(t);e.prototype=t;var r=new e;return e.prototype=o,r}}();function Gr(){}function zr(e,t){this.__wrapped__=e,this.__actions__=[],this.__chain__=!!t,this.__index__=0,this.__values__=o}function jr(e){this.__wrapped__=e,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=d,this.__views__=[]}function Vr(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t=t?e:t)),e}function sn(e,t,r,n,i,a){var s,c=1&t,u=2&t,l=4&t;if(r&&(s=i?r(e,n,i,a):r(e)),s!==o)return s;if(!ts(e))return e;var p=$a(e);if(p){if(s=function(e){var t=e.length,r=new e.constructor(t);return t&&"string"==typeof e[0]&&xe.call(e,"index")&&(r.index=e.index,r.input=e.input),r}(e),!c)return Ro(e,s)}else{var f=di(e),d=f==T||f==S;if(Qa(e))return _o(e,c);if(f==A||f==h||d&&!i){if(s=u||d?{}:hi(e),!c)return u?function(e,t){return Oo(e,fi(e),t)}(e,function(e,t){return e&&Oo(t,xs(t),e)}(s,e)):function(e,t){return Oo(e,pi(e),t)}(e,rn(s,e))}else{if(!Ze[f])return i?e:{};s=function(e,t,r){var n,o=e.constructor;switch(t){case M:return No(e);case g:case E:return new o(+e);case P:return function(e,t){var r=t?No(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.byteLength)}(e,r);case x:case L:case k:case F:case D:case U:case B:case G:case z:return Ao(e,r);case _:return new o;case N:case R:return new o(e);case w:return function(e){var t=new e.constructor(e.source,fe.exec(e));return t.lastIndex=e.lastIndex,t}(e);case b:return new o;case O:return n=e,Fr?Ae(Fr.call(n)):{}}}(e,f,c)}}a||(a=new Hr);var y=a.get(e);if(y)return y;a.set(e,s),ss(e)?e.forEach((function(n){s.add(sn(n,t,r,n,e,a))})):ns(e)&&e.forEach((function(n,o){s.set(o,sn(n,t,r,o,e,a))}));var m=p?o:(l?u?ni:ri:u?xs:Ps)(e);return vt(m||e,(function(n,o){m&&(n=e[o=n]),Zr(s,o,sn(n,t,r,o,e,a))})),s}function cn(e,t,r){var n=r.length;if(null==e)return!n;for(e=Ae(e);n--;){var i=r[n],a=t[i],s=e[i];if(s===o&&!(i in e)||!a(s))return!1}return!0}function un(e,t,r){if("function"!=typeof e)throw new be(i);return Ii((function(){e.apply(o,r)}),t)}function ln(e,t,r,n){var o=-1,i=Nt,a=!0,s=e.length,c=[],u=t.length;if(!s)return c;r&&(t=Ct(t,Vt(r))),n?(i=At,a=!1):t.length>=200&&(i=$t,a=!1,t=new qr(t));e:for(;++o-1},Wr.prototype.set=function(e,t){var r=this.__data__,n=en(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this},$r.prototype.clear=function(){this.size=0,this.__data__={hash:new Vr,map:new(Nr||Wr),string:new Vr}},$r.prototype.delete=function(e){var t=ci(this,e).delete(e);return this.size-=t?1:0,t},$r.prototype.get=function(e){return ci(this,e).get(e)},$r.prototype.has=function(e){return ci(this,e).has(e)},$r.prototype.set=function(e,t){var r=ci(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this},qr.prototype.add=qr.prototype.push=function(e){return this.__data__.set(e,a),this},qr.prototype.has=function(e){return this.__data__.has(e)},Hr.prototype.clear=function(){this.__data__=new Wr,this.size=0},Hr.prototype.delete=function(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r},Hr.prototype.get=function(e){return this.__data__.get(e)},Hr.prototype.has=function(e){return this.__data__.has(e)},Hr.prototype.set=function(e,t){var r=this.__data__;if(r instanceof Wr){var n=r.__data__;if(!Nr||n.length<199)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new $r(n)}return r.set(e,t),this.size=r.size,this};var pn=Po(vn),fn=Po(Tn,!0);function dn(e,t){var r=!0;return pn(e,(function(e,n,o){return r=!!t(e,n,o)})),r}function yn(e,t,r){for(var n=-1,i=e.length;++n0&&r(s)?t>1?mn(s,t-1,r,n,o):wt(o,s):n||(o[o.length]=s)}return o}var gn=xo(),En=xo(!0);function vn(e,t){return e&&gn(e,t,Ps)}function Tn(e,t){return e&&En(e,t,Ps)}function Sn(e,t){return _t(t,(function(t){return Ka(e[t])}))}function _n(e,t){for(var r=0,n=(t=Eo(t,e)).length;null!=e&&rt}function wn(e,t){return null!=e&&xe.call(e,t)}function bn(e,t){return null!=e&&t in Ae(e)}function Rn(e,t,r){for(var i=r?At:Nt,a=e[0].length,s=e.length,c=s,u=n(s),l=1/0,p=[];c--;){var f=e[c];c&&t&&(f=Ct(f,Vt(t))),l=gr(f.length,l),u[c]=!r&&(t||a>=120&&f.length>=120)?new qr(c&&f):o}f=e[0];var d=-1,y=u[0];e:for(;++d=s?c:c*("desc"==r[n]?-1:1)}return e.index-t.index}(e,t,r)}));n--;)e[n]=e[n].value;return e}(Dn(e,(function(e,r,o){return{criteria:Ct(t,(function(t){return t(e)})),index:++n,value:e}})))}function Vn(e,t,r){for(var n=-1,o=t.length,i={};++n-1;)s!==e&&nt.call(s,c,1),nt.call(e,c,1);return e}function $n(e,t){for(var r=e?t.length:0,n=r-1;r--;){var o=t[r];if(r==n||o!==i){var i=o;gi(o)?nt.call(e,o,1):uo(e,o)}}return e}function qn(e,t){return e+lr(Tr()*(t-e+1))}function Hn(e,t){var r="";if(!e||t<1||t>p)return r;do{t%2&&(r+=e),(t=lr(t/2))&&(e+=e)}while(t);return r}function Yn(e,t){return Mi(Ci(e,t,oc),e+"")}function Qn(e){return Qr(zs(e))}function Xn(e,t){var r=zs(e);return Li(r,an(t,0,r.length))}function Jn(e,t,r,n){if(!ts(e))return e;for(var i=-1,a=(t=Eo(t,e)).length,s=a-1,c=e;null!=c&&++ii?0:i+t),(r=r>i?i:r)<0&&(r+=i),i=t>r?0:r-t>>>0,t>>>=0;for(var a=n(i);++o>>1,a=e[i];null!==a&&!us(a)&&(r?a<=t:a=200){var u=t?null:Yo(e);if(u)return rr(u);a=!1,o=$t,c=new qr}else c=t?[]:s;e:for(;++n=n?e:to(e,t,r)}var So=lt||function(e){return it.clearTimeout(e)};function _o(e,t){if(t)return e.slice();var r=e.length,n=Ve?Ve(r):new e.constructor(r);return e.copy(n),n}function No(e){var t=new e.constructor(e.byteLength);return new je(t).set(new je(e)),t}function Ao(e,t){var r=t?No(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}function Co(e,t){if(e!==t){var r=e!==o,n=null===e,i=e==e,a=us(e),s=t!==o,c=null===t,u=t==t,l=us(t);if(!c&&!l&&!a&&e>t||a&&s&&u&&!c&&!l||n&&s&&u||!r&&u||!i)return 1;if(!n&&!a&&!l&&e1?r[i-1]:o,s=i>2?r[2]:o;for(a=e.length>3&&"function"==typeof a?(i--,a):o,s&&Ei(r[0],r[1],s)&&(a=i<3?o:a,i=1),t=Ae(t);++n-1?i[a?t[s]:s]:o}}function Uo(e){return ti((function(t){var r=t.length,n=r,a=zr.prototype.thru;for(e&&t.reverse();n--;){var s=t[n];if("function"!=typeof s)throw new be(i);if(a&&!c&&"wrapper"==ii(s))var c=new zr([],!0)}for(n=c?n:r;++n1&&v.reverse(),d&&pc))return!1;var l=a.get(e),p=a.get(t);if(l&&p)return l==t&&p==e;var f=-1,d=!0,y=2&r?new qr:o;for(a.set(e,t),a.set(t,e);++f-1&&e%1==0&&e1?"& ":"")+t[n],t=t.join(r>2?", ":" "),e.replace(ie,"{\n/* [wrapped with "+t+"] */\n")}(n,function(e,t){return vt(y,(function(r){var n="_."+r[0];t&r[1]&&!Nt(e,n)&&e.push(n)})),e.sort()}(function(e){var t=e.match(ae);return t?t[1].split(se):[]}(n),r)))}function xi(e){var t=0,r=0;return function(){var n=Er(),i=16-(n-r);if(r=n,i>0){if(++t>=800)return arguments[0]}else t=0;return e.apply(o,arguments)}}function Li(e,t){var r=-1,n=e.length,i=n-1;for(t=t===o?n:t;++r1?e[t-1]:o;return r="function"==typeof r?(e.pop(),r):o,aa(e,r)}));function da(e){var t=Ur(e);return t.__chain__=!0,t}function ya(e,t){return t(e)}var ha=ti((function(e){var t=e.length,r=t?e[0]:0,n=this.__wrapped__,i=function(t){return on(t,e)};return!(t>1||this.__actions__.length)&&n instanceof jr&&gi(r)?((n=n.slice(r,+r+(t?1:0))).__actions__.push({func:ya,args:[i],thisArg:o}),new zr(n,this.__chain__).thru((function(e){return t&&!e.length&&e.push(o),e}))):this.thru(i)})),ma=Io((function(e,t,r){xe.call(e,r)?++e[r]:nn(e,r,1)})),ga=Do(Wi),Ea=Do($i);function va(e,t){return($a(e)?vt:pn)(e,si(t,3))}function Ta(e,t){return($a(e)?Tt:fn)(e,si(t,3))}var Sa=Io((function(e,t,r){xe.call(e,r)?e[r].push(t):nn(e,r,[t])})),_a=Yn((function(e,t,r){var o=-1,i="function"==typeof t,a=Ha(e)?n(e.length):[];return pn(e,(function(e){a[++o]=i?gt(t,e,r):On(e,t,r)})),a})),Na=Io((function(e,t,r){nn(e,r,t)}));function Aa(e,t){return($a(e)?Ct:Dn)(e,si(t,3))}var Ca=Io((function(e,t,r){e[r?0:1].push(t)}),(function(){return[[],[]]})),wa=Yn((function(e,t){if(null==e)return[];var r=t.length;return r>1&&Ei(e,t[0],t[1])?t=[]:r>2&&Ei(t[0],t[1],t[2])&&(t=[t[0]]),jn(e,mn(t,1),[])})),ba=It||function(){return it.Date.now()};function Ra(e,t,r){return t=r?o:t,t=e&&null==t?e.length:t,Xo(e,u,o,o,o,o,t)}function Oa(e,t){var r;if("function"!=typeof t)throw new be(i);return e=hs(e),function(){return--e>0&&(r=t.apply(this,arguments)),e<=1&&(t=o),r}}var Ia=Yn((function(e,t,r){var n=1;if(r.length){var o=tr(r,ai(Ia));n|=c}return Xo(e,n,t,r,o)})),Ma=Yn((function(e,t,r){var n=3;if(r.length){var o=tr(r,ai(Ma));n|=c}return Xo(t,n,e,r,o)}));function Pa(e,t,r){var n,a,s,c,u,l,p=0,f=!1,d=!1,y=!0;if("function"!=typeof e)throw new be(i);function h(t){var r=n,i=a;return n=a=o,p=t,c=e.apply(i,r)}function m(e){return p=e,u=Ii(E,t),f?h(e):c}function g(e){var r=e-l;return l===o||r>=t||r<0||d&&e-p>=s}function E(){var e=ba();if(g(e))return v(e);u=Ii(E,function(e){var r=t-(e-l);return d?gr(r,s-(e-p)):r}(e))}function v(e){return u=o,y&&n?h(e):(n=a=o,c)}function T(){var e=ba(),r=g(e);if(n=arguments,a=this,l=e,r){if(u===o)return m(l);if(d)return So(u),u=Ii(E,t),h(l)}return u===o&&(u=Ii(E,t)),c}return t=gs(t)||0,ts(r)&&(f=!!r.leading,s=(d="maxWait"in r)?mr(gs(r.maxWait)||0,t):s,y="trailing"in r?!!r.trailing:y),T.cancel=function(){u!==o&&So(u),p=0,n=l=a=u=o},T.flush=function(){return u===o?c:v(ba())},T}var xa=Yn((function(e,t){return un(e,1,t)})),La=Yn((function(e,t,r){return un(e,gs(t)||0,r)}));function ka(e,t){if("function"!=typeof e||null!=t&&"function"!=typeof t)throw new be(i);var r=function(){var n=arguments,o=t?t.apply(this,n):n[0],i=r.cache;if(i.has(o))return i.get(o);var a=e.apply(this,n);return r.cache=i.set(o,a)||i,a};return r.cache=new(ka.Cache||$r),r}function Fa(e){if("function"!=typeof e)throw new be(i);return function(){var t=arguments;switch(t.length){case 0:return!e.call(this);case 1:return!e.call(this,t[0]);case 2:return!e.call(this,t[0],t[1]);case 3:return!e.call(this,t[0],t[1],t[2])}return!e.apply(this,t)}}ka.Cache=$r;var Da=vo((function(e,t){var r=(t=1==t.length&&$a(t[0])?Ct(t[0],Vt(si())):Ct(mn(t,1),Vt(si()))).length;return Yn((function(n){for(var o=-1,i=gr(n.length,r);++o=t})),Wa=In(function(){return arguments}())?In:function(e){return rs(e)&&xe.call(e,"callee")&&!et.call(e,"callee")},$a=n.isArray,qa=pt?Vt(pt):function(e){return rs(e)&&An(e)==M};function Ha(e){return null!=e&&es(e.length)&&!Ka(e)}function Ya(e){return rs(e)&&Ha(e)}var Qa=fr||gc,Xa=ft?Vt(ft):function(e){return rs(e)&&An(e)==E};function Ja(e){if(!rs(e))return!1;var t=An(e);return t==v||"[object DOMException]"==t||"string"==typeof e.message&&"string"==typeof e.name&&!is(e)}function Ka(e){if(!ts(e))return!1;var t=An(e);return t==T||t==S||"[object AsyncFunction]"==t||"[object Proxy]"==t}function Za(e){return"number"==typeof e&&e==hs(e)}function es(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=p}function ts(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}function rs(e){return null!=e&&"object"==typeof e}var ns=dt?Vt(dt):function(e){return rs(e)&&di(e)==_};function os(e){return"number"==typeof e||rs(e)&&An(e)==N}function is(e){if(!rs(e)||An(e)!=A)return!1;var t=qe(e);if(null===t)return!0;var r=xe.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&Pe.call(r)==De}var as=yt?Vt(yt):function(e){return rs(e)&&An(e)==w},ss=ht?Vt(ht):function(e){return rs(e)&&di(e)==b};function cs(e){return"string"==typeof e||!$a(e)&&rs(e)&&An(e)==R}function us(e){return"symbol"==typeof e||rs(e)&&An(e)==O}var ls=mt?Vt(mt):function(e){return rs(e)&&es(e.length)&&!!Ke[An(e)]},ps=$o(Fn),fs=$o((function(e,t){return e<=t}));function ds(e){if(!e)return[];if(Ha(e))return cs(e)?ir(e):Ro(e);if(at&&e[at])return function(e){for(var t,r=[];!(t=e.next()).done;)r.push(t.value);return r}(e[at]());var t=di(e);return(t==_?Zt:t==b?rr:zs)(e)}function ys(e){return e?(e=gs(e))===l||e===-1/0?17976931348623157e292*(e<0?-1:1):e==e?e:0:0===e?e:0}function hs(e){var t=ys(e),r=t%1;return t==t?r?t-r:t:0}function ms(e){return e?an(hs(e),0,d):0}function gs(e){if("number"==typeof e)return e;if(us(e))return f;if(ts(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=ts(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=jt(e);var r=ye.test(e);return r||me.test(e)?rt(e.slice(2),r?2:8):de.test(e)?f:+e}function Es(e){return Oo(e,xs(e))}function vs(e){return null==e?"":so(e)}var Ts=Mo((function(e,t){if(_i(t)||Ha(t))Oo(t,Ps(t),e);else for(var r in t)xe.call(t,r)&&Zr(e,r,t[r])})),Ss=Mo((function(e,t){Oo(t,xs(t),e)})),_s=Mo((function(e,t,r,n){Oo(t,xs(t),e,n)})),Ns=Mo((function(e,t,r,n){Oo(t,Ps(t),e,n)})),As=ti(on),Cs=Yn((function(e,t){e=Ae(e);var r=-1,n=t.length,i=n>2?t[2]:o;for(i&&Ei(t[0],t[1],i)&&(n=1);++r1),t})),Oo(e,ni(e),r),n&&(r=sn(r,7,Zo));for(var o=t.length;o--;)uo(r,t[o]);return r})),Ds=ti((function(e,t){return null==e?{}:function(e,t){return Vn(e,t,(function(t,r){return Rs(e,r)}))}(e,t)}));function Us(e,t){if(null==e)return{};var r=Ct(ni(e),(function(e){return[e]}));return t=si(t),Vn(e,r,(function(e,r){return t(e,r[0])}))}var Bs=Qo(Ps),Gs=Qo(xs);function zs(e){return null==e?[]:Wt(e,Ps(e))}var js=ko((function(e,t,r){return t=t.toLowerCase(),e+(r?Vs(t):t)}));function Vs(e){return Js(vs(e).toLowerCase())}function Ws(e){return(e=vs(e))&&e.replace(Ee,Qt).replace($e,"")}var $s=ko((function(e,t,r){return e+(r?"-":"")+t.toLowerCase()})),qs=ko((function(e,t,r){return e+(r?" ":"")+t.toLowerCase()})),Hs=Lo("toLowerCase"),Ys=ko((function(e,t,r){return e+(r?"_":"")+t.toLowerCase()})),Qs=ko((function(e,t,r){return e+(r?" ":"")+Js(t)})),Xs=ko((function(e,t,r){return e+(r?" ":"")+t.toUpperCase()})),Js=Lo("toUpperCase");function Ks(e,t,r){return e=vs(e),(t=r?o:t)===o?function(e){return Qe.test(e)}(e)?function(e){return e.match(He)||[]}(e):function(e){return e.match(ce)||[]}(e):e.match(t)||[]}var Zs=Yn((function(e,t){try{return gt(e,o,t)}catch(e){return Ja(e)?e:new Se(e)}})),ec=ti((function(e,t){return vt(t,(function(t){t=Ui(t),nn(e,t,Ia(e[t],e))})),e}));function tc(e){return function(){return e}}var rc=Uo(),nc=Uo(!0);function oc(e){return e}function ic(e){return Ln("function"==typeof e?e:sn(e,1))}var ac=Yn((function(e,t){return function(r){return On(r,e,t)}})),sc=Yn((function(e,t){return function(r){return On(e,r,t)}}));function cc(e,t,r){var n=Ps(t),o=Sn(t,n);null!=r||ts(t)&&(o.length||!n.length)||(r=t,t=e,e=this,o=Sn(t,Ps(t)));var i=!(ts(r)&&"chain"in r&&!r.chain),a=Ka(e);return vt(o,(function(r){var n=t[r];e[r]=n,a&&(e.prototype[r]=function(){var t=this.__chain__;if(i||t){var r=e(this.__wrapped__),o=r.__actions__=Ro(this.__actions__);return o.push({func:n,args:arguments,thisArg:e}),r.__chain__=t,r}return n.apply(e,wt([this.value()],arguments))})})),e}function uc(){}var lc=jo(Ct),pc=jo(St),fc=jo(Ot);function dc(e){return vi(e)?Dt(Ui(e)):function(e){return function(t){return _n(t,e)}}(e)}var yc=Wo(),hc=Wo(!0);function mc(){return[]}function gc(){return!1}var Ec,vc=zo((function(e,t){return e+t}),0),Tc=Ho("ceil"),Sc=zo((function(e,t){return e/t}),1),_c=Ho("floor"),Nc=zo((function(e,t){return e*t}),1),Ac=Ho("round"),Cc=zo((function(e,t){return e-t}),0);return Ur.after=function(e,t){if("function"!=typeof t)throw new be(i);return e=hs(e),function(){if(--e<1)return t.apply(this,arguments)}},Ur.ary=Ra,Ur.assign=Ts,Ur.assignIn=Ss,Ur.assignInWith=_s,Ur.assignWith=Ns,Ur.at=As,Ur.before=Oa,Ur.bind=Ia,Ur.bindAll=ec,Ur.bindKey=Ma,Ur.castArray=function(){if(!arguments.length)return[];var e=arguments[0];return $a(e)?e:[e]},Ur.chain=da,Ur.chunk=function(e,t,r){t=(r?Ei(e,t,r):t===o)?1:mr(hs(t),0);var i=null==e?0:e.length;if(!i||t<1)return[];for(var a=0,s=0,c=n(ur(i/t));ai?0:i+r),(n=n===o||n>i?i:hs(n))<0&&(n+=i),n=r>n?0:ms(n);r>>0)?(e=vs(e))&&("string"==typeof t||null!=t&&!as(t))&&!(t=so(t))&&Kt(e)?To(ir(e),0,r):e.split(t,r):[]},Ur.spread=function(e,t){if("function"!=typeof e)throw new be(i);return t=null==t?0:mr(hs(t),0),Yn((function(r){var n=r[t],o=To(r,0,t);return n&&wt(o,n),gt(e,this,o)}))},Ur.tail=function(e){var t=null==e?0:e.length;return t?to(e,1,t):[]},Ur.take=function(e,t,r){return e&&e.length?to(e,0,(t=r||t===o?1:hs(t))<0?0:t):[]},Ur.takeRight=function(e,t,r){var n=null==e?0:e.length;return n?to(e,(t=n-(t=r||t===o?1:hs(t)))<0?0:t,n):[]},Ur.takeRightWhile=function(e,t){return e&&e.length?po(e,si(t,3),!1,!0):[]},Ur.takeWhile=function(e,t){return e&&e.length?po(e,si(t,3)):[]},Ur.tap=function(e,t){return t(e),e},Ur.throttle=function(e,t,r){var n=!0,o=!0;if("function"!=typeof e)throw new be(i);return ts(r)&&(n="leading"in r?!!r.leading:n,o="trailing"in r?!!r.trailing:o),Pa(e,t,{leading:n,maxWait:t,trailing:o})},Ur.thru=ya,Ur.toArray=ds,Ur.toPairs=Bs,Ur.toPairsIn=Gs,Ur.toPath=function(e){return $a(e)?Ct(e,Ui):us(e)?[e]:Ro(Di(vs(e)))},Ur.toPlainObject=Es,Ur.transform=function(e,t,r){var n=$a(e),o=n||Qa(e)||ls(e);if(t=si(t,4),null==r){var i=e&&e.constructor;r=o?n?new i:[]:ts(e)&&Ka(i)?Br(qe(e)):{}}return(o?vt:vn)(e,(function(e,n,o){return t(r,e,n,o)})),r},Ur.unary=function(e){return Ra(e,1)},Ur.union=ra,Ur.unionBy=na,Ur.unionWith=oa,Ur.uniq=function(e){return e&&e.length?co(e):[]},Ur.uniqBy=function(e,t){return e&&e.length?co(e,si(t,2)):[]},Ur.uniqWith=function(e,t){return t="function"==typeof t?t:o,e&&e.length?co(e,o,t):[]},Ur.unset=function(e,t){return null==e||uo(e,t)},Ur.unzip=ia,Ur.unzipWith=aa,Ur.update=function(e,t,r){return null==e?e:lo(e,t,go(r))},Ur.updateWith=function(e,t,r,n){return n="function"==typeof n?n:o,null==e?e:lo(e,t,go(r),n)},Ur.values=zs,Ur.valuesIn=function(e){return null==e?[]:Wt(e,xs(e))},Ur.without=sa,Ur.words=Ks,Ur.wrap=function(e,t){return Ua(go(t),e)},Ur.xor=ca,Ur.xorBy=ua,Ur.xorWith=la,Ur.zip=pa,Ur.zipObject=function(e,t){return ho(e||[],t||[],Zr)},Ur.zipObjectDeep=function(e,t){return ho(e||[],t||[],Jn)},Ur.zipWith=fa,Ur.entries=Bs,Ur.entriesIn=Gs,Ur.extend=Ss,Ur.extendWith=_s,cc(Ur,Ur),Ur.add=vc,Ur.attempt=Zs,Ur.camelCase=js,Ur.capitalize=Vs,Ur.ceil=Tc,Ur.clamp=function(e,t,r){return r===o&&(r=t,t=o),r!==o&&(r=(r=gs(r))==r?r:0),t!==o&&(t=(t=gs(t))==t?t:0),an(gs(e),t,r)},Ur.clone=function(e){return sn(e,4)},Ur.cloneDeep=function(e){return sn(e,5)},Ur.cloneDeepWith=function(e,t){return sn(e,5,t="function"==typeof t?t:o)},Ur.cloneWith=function(e,t){return sn(e,4,t="function"==typeof t?t:o)},Ur.conformsTo=function(e,t){return null==t||cn(e,t,Ps(t))},Ur.deburr=Ws,Ur.defaultTo=function(e,t){return null==e||e!=e?t:e},Ur.divide=Sc,Ur.endsWith=function(e,t,r){e=vs(e),t=so(t);var n=e.length,i=r=r===o?n:an(hs(r),0,n);return(r-=t.length)>=0&&e.slice(r,i)==t},Ur.eq=za,Ur.escape=function(e){return(e=vs(e))&&Y.test(e)?e.replace(q,Xt):e},Ur.escapeRegExp=function(e){return(e=vs(e))&&re.test(e)?e.replace(te,"\\$&"):e},Ur.every=function(e,t,r){var n=$a(e)?St:dn;return r&&Ei(e,t,r)&&(t=o),n(e,si(t,3))},Ur.find=ga,Ur.findIndex=Wi,Ur.findKey=function(e,t){return Mt(e,si(t,3),vn)},Ur.findLast=Ea,Ur.findLastIndex=$i,Ur.findLastKey=function(e,t){return Mt(e,si(t,3),Tn)},Ur.floor=_c,Ur.forEach=va,Ur.forEachRight=Ta,Ur.forIn=function(e,t){return null==e?e:gn(e,si(t,3),xs)},Ur.forInRight=function(e,t){return null==e?e:En(e,si(t,3),xs)},Ur.forOwn=function(e,t){return e&&vn(e,si(t,3))},Ur.forOwnRight=function(e,t){return e&&Tn(e,si(t,3))},Ur.get=bs,Ur.gt=ja,Ur.gte=Va,Ur.has=function(e,t){return null!=e&&yi(e,t,wn)},Ur.hasIn=Rs,Ur.head=Hi,Ur.identity=oc,Ur.includes=function(e,t,r,n){e=Ha(e)?e:zs(e),r=r&&!n?hs(r):0;var o=e.length;return r<0&&(r=mr(o+r,0)),cs(e)?r<=o&&e.indexOf(t,r)>-1:!!o&&xt(e,t,r)>-1},Ur.indexOf=function(e,t,r){var n=null==e?0:e.length;if(!n)return-1;var o=null==r?0:hs(r);return o<0&&(o=mr(n+o,0)),xt(e,t,o)},Ur.inRange=function(e,t,r){return t=ys(t),r===o?(r=t,t=0):r=ys(r),function(e,t,r){return e>=gr(t,r)&&e=-9007199254740991&&e<=p},Ur.isSet=ss,Ur.isString=cs,Ur.isSymbol=us,Ur.isTypedArray=ls,Ur.isUndefined=function(e){return e===o},Ur.isWeakMap=function(e){return rs(e)&&di(e)==I},Ur.isWeakSet=function(e){return rs(e)&&"[object WeakSet]"==An(e)},Ur.join=function(e,t){return null==e?"":yr.call(e,t)},Ur.kebabCase=$s,Ur.last=Ji,Ur.lastIndexOf=function(e,t,r){var n=null==e?0:e.length;if(!n)return-1;var i=n;return r!==o&&(i=(i=hs(r))<0?mr(n+i,0):gr(i,n-1)),t==t?function(e,t,r){for(var n=r+1;n--;)if(e[n]===t)return n;return n}(e,t,i):Pt(e,kt,i,!0)},Ur.lowerCase=qs,Ur.lowerFirst=Hs,Ur.lt=ps,Ur.lte=fs,Ur.max=function(e){return e&&e.length?yn(e,oc,Cn):o},Ur.maxBy=function(e,t){return e&&e.length?yn(e,si(t,2),Cn):o},Ur.mean=function(e){return Ft(e,oc)},Ur.meanBy=function(e,t){return Ft(e,si(t,2))},Ur.min=function(e){return e&&e.length?yn(e,oc,Fn):o},Ur.minBy=function(e,t){return e&&e.length?yn(e,si(t,2),Fn):o},Ur.stubArray=mc,Ur.stubFalse=gc,Ur.stubObject=function(){return{}},Ur.stubString=function(){return""},Ur.stubTrue=function(){return!0},Ur.multiply=Nc,Ur.nth=function(e,t){return e&&e.length?zn(e,hs(t)):o},Ur.noConflict=function(){return it._===this&&(it._=Ue),this},Ur.noop=uc,Ur.now=ba,Ur.pad=function(e,t,r){e=vs(e);var n=(t=hs(t))?or(e):0;if(!t||n>=t)return e;var o=(t-n)/2;return Vo(lr(o),r)+e+Vo(ur(o),r)},Ur.padEnd=function(e,t,r){e=vs(e);var n=(t=hs(t))?or(e):0;return t&&nt){var n=e;e=t,t=n}if(r||e%1||t%1){var i=Tr();return gr(e+i*(t-e+tt("1e-"+((i+"").length-1))),t)}return qn(e,t)},Ur.reduce=function(e,t,r){var n=$a(e)?bt:Bt,o=arguments.length<3;return n(e,si(t,4),r,o,pn)},Ur.reduceRight=function(e,t,r){var n=$a(e)?Rt:Bt,o=arguments.length<3;return n(e,si(t,4),r,o,fn)},Ur.repeat=function(e,t,r){return t=(r?Ei(e,t,r):t===o)?1:hs(t),Hn(vs(e),t)},Ur.replace=function(){var e=arguments,t=vs(e[0]);return e.length<3?t:t.replace(e[1],e[2])},Ur.result=function(e,t,r){var n=-1,i=(t=Eo(t,e)).length;for(i||(i=1,e=o);++np)return[];var r=d,n=gr(e,d);t=si(t),e-=d;for(var o=zt(n,t);++r=a)return e;var c=r-or(n);if(c<1)return n;var u=s?To(s,0,c).join(""):e.slice(0,c);if(i===o)return u+n;if(s&&(c+=u.length-c),as(i)){if(e.slice(c).search(i)){var l,p=u;for(i.global||(i=Ce(i.source,vs(fe.exec(i))+"g")),i.lastIndex=0;l=i.exec(p);)var f=l.index;u=u.slice(0,f===o?c:f)}}else if(e.indexOf(so(i),c)!=c){var d=u.lastIndexOf(i);d>-1&&(u=u.slice(0,d))}return u+n},Ur.unescape=function(e){return(e=vs(e))&&H.test(e)?e.replace($,sr):e},Ur.uniqueId=function(e){var t=++Le;return vs(e)+t},Ur.upperCase=Xs,Ur.upperFirst=Js,Ur.each=va,Ur.eachRight=Ta,Ur.first=Hi,cc(Ur,(Ec={},vn(Ur,(function(e,t){xe.call(Ur.prototype,t)||(Ec[t]=e)})),Ec),{chain:!1}),Ur.VERSION="4.17.21",vt(["bind","bindKey","curry","curryRight","partial","partialRight"],(function(e){Ur[e].placeholder=Ur})),vt(["drop","take"],(function(e,t){jr.prototype[e]=function(r){r=r===o?1:mr(hs(r),0);var n=this.__filtered__&&!t?new jr(this):this.clone();return n.__filtered__?n.__takeCount__=gr(r,n.__takeCount__):n.__views__.push({size:gr(r,d),type:e+(n.__dir__<0?"Right":"")}),n},jr.prototype[e+"Right"]=function(t){return this.reverse()[e](t).reverse()}})),vt(["filter","map","takeWhile"],(function(e,t){var r=t+1,n=1==r||3==r;jr.prototype[e]=function(e){var t=this.clone();return t.__iteratees__.push({iteratee:si(e,3),type:r}),t.__filtered__=t.__filtered__||n,t}})),vt(["head","last"],(function(e,t){var r="take"+(t?"Right":"");jr.prototype[e]=function(){return this[r](1).value()[0]}})),vt(["initial","tail"],(function(e,t){var r="drop"+(t?"":"Right");jr.prototype[e]=function(){return this.__filtered__?new jr(this):this[r](1)}})),jr.prototype.compact=function(){return this.filter(oc)},jr.prototype.find=function(e){return this.filter(e).head()},jr.prototype.findLast=function(e){return this.reverse().find(e)},jr.prototype.invokeMap=Yn((function(e,t){return"function"==typeof e?new jr(this):this.map((function(r){return On(r,e,t)}))})),jr.prototype.reject=function(e){return this.filter(Fa(si(e)))},jr.prototype.slice=function(e,t){e=hs(e);var r=this;return r.__filtered__&&(e>0||t<0)?new jr(r):(e<0?r=r.takeRight(-e):e&&(r=r.drop(e)),t!==o&&(r=(t=hs(t))<0?r.dropRight(-t):r.take(t-e)),r)},jr.prototype.takeRightWhile=function(e){return this.reverse().takeWhile(e).reverse()},jr.prototype.toArray=function(){return this.take(d)},vn(jr.prototype,(function(e,t){var r=/^(?:filter|find|map|reject)|While$/.test(t),n=/^(?:head|last)$/.test(t),i=Ur[n?"take"+("last"==t?"Right":""):t],a=n||/^find/.test(t);i&&(Ur.prototype[t]=function(){var t=this.__wrapped__,s=n?[1]:arguments,c=t instanceof jr,u=s[0],l=c||$a(t),p=function(e){var t=i.apply(Ur,wt([e],s));return n&&f?t[0]:t};l&&r&&"function"==typeof u&&1!=u.length&&(c=l=!1);var f=this.__chain__,d=!!this.__actions__.length,y=a&&!f,h=c&&!d;if(!a&&l){t=h?t:new jr(this);var m=e.apply(t,s);return m.__actions__.push({func:ya,args:[p],thisArg:o}),new zr(m,f)}return y&&h?e.apply(this,s):(m=this.thru(p),y?n?m.value()[0]:m.value():m)})})),vt(["pop","push","shift","sort","splice","unshift"],(function(e){var t=Re[e],r=/^(?:push|sort|unshift)$/.test(e)?"tap":"thru",n=/^(?:pop|shift)$/.test(e);Ur.prototype[e]=function(){var e=arguments;if(n&&!this.__chain__){var o=this.value();return t.apply($a(o)?o:[],e)}return this[r]((function(r){return t.apply($a(r)?r:[],e)}))}})),vn(jr.prototype,(function(e,t){var r=Ur[t];if(r){var n=r.name+"";xe.call(Or,n)||(Or[n]=[]),Or[n].push({name:t,func:r})}})),Or[Bo(o,2).name]=[{name:"wrapper",func:o}],jr.prototype.clone=function(){var e=new jr(this.__wrapped__);return e.__actions__=Ro(this.__actions__),e.__dir__=this.__dir__,e.__filtered__=this.__filtered__,e.__iteratees__=Ro(this.__iteratees__),e.__takeCount__=this.__takeCount__,e.__views__=Ro(this.__views__),e},jr.prototype.reverse=function(){if(this.__filtered__){var e=new jr(this);e.__dir__=-1,e.__filtered__=!0}else(e=this.clone()).__dir__*=-1;return e},jr.prototype.value=function(){var e=this.__wrapped__.value(),t=this.__dir__,r=$a(e),n=t<0,o=r?e.length:0,i=function(e,t,r){for(var n=-1,o=r.length;++n=this.__values__.length;return{done:e,value:e?o:this.__values__[this.__index__++]}},Ur.prototype.plant=function(e){for(var t,r=this;r instanceof Gr;){var n=Gi(r);n.__index__=0,n.__values__=o,t?i.__wrapped__=n:t=n;var i=n;r=r.__wrapped__}return i.__wrapped__=e,t},Ur.prototype.reverse=function(){var e=this.__wrapped__;if(e instanceof jr){var t=e;return this.__actions__.length&&(t=new jr(this)),(t=t.reverse()).__actions__.push({func:ya,args:[ta],thisArg:o}),new zr(t,this.__chain__)}return this.thru(ta)},Ur.prototype.toJSON=Ur.prototype.valueOf=Ur.prototype.value=function(){return fo(this.__wrapped__,this.__actions__)},Ur.prototype.first=Ur.prototype.head,at&&(Ur.prototype[at]=function(){return this}),Ur}();it._=cr,(n=function(){return cr}.call(t,r,t,e))===o||(e.exports=n)}.call(this)},904:(e,t)=>{"use strict";var r;let n;Object.defineProperty(t,"__esModule",{value:!0}),t.setDomain=t.getDomain=t.Domain=void 0,function(e){e[e.FA=0]="FA",e[e.FORM=1]="FORM",e[e.ETS=2]="ETS"}(r||(r={})),t.Domain=r,t.setDomain=e=>{n=e},t.getDomain=()=>null!=n?n:r.FA},784:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.errorMap=void 0,t.errorMap=new Map([["fileError","Visual file is damaged"],["versionError","Version number of visual file does not match"],["modelError","Visual model in visual file is damaged"],["codegenError","Codegen visual file failed"]])},117:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ASTNode=void 0,t.ASTNode=class{accept(e){return e.visit(this)}}},862:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Cache=void 0,t.Cache=class{constructor(e,t=0){this.value="",this.indent=t,this.flag=!0,this.INDENT=e}indentOn(){this.flag=!0}indentOff(){this.flag=!1}incIndent(){this.indent++}decIndent(){this.indent--}checkIndent(){return this.indent<0}getIndents(){if(this.flag){let e="";for(let t=0;t{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Tag=void 0;const n=r(117);class o extends n.ASTNode{constructor(e,t,r,n,o){super(),this.defaultValue=new Map,this.mediaParams=new Map,this.mediaProperties=new Map,this.mediaKeyProperty=new Map,this.tagName=e,this.params=t,this.content=r,this.properties=n,this.forEachObj=o,this.ifBoolean=null}setMediaParams(e){this.mediaParams=e}setParams(e){this.params=e}setIfBoolean(e){this.ifBoolean=e}setTagName(e){this.tagName=e}setForEachObj(e){this.forEachObj=e}setMediaProperty(e,t){t.forEach(((t,r)=>{var n;this.mediaKeyProperty.has(r)||this.mediaKeyProperty.set(r,new Map),null===(n=this.mediaKeyProperty.get(r))||void 0===n||n.set(e,t)}))}setDefaultValue(e,t,r="undefined"){this.defaultValue.set(e,[r,t])}}t.Tag=o},623:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ASTNodeGenerator=void 0;const n=r(519),o=r(862),i=r(51),a=r(294);class s{constructor(e){this.cache=e,this.etsImport=new o.Cache(" ",1),this.etsVariable=new o.Cache(" ",1),this.etsFunction=new o.Cache(" ",1),this.aboutToAppear=new o.Cache(" ",2),this.needMediaQuery=!0}visit(e){e instanceof n.Tag&&(this.needMediaQuery&&this.genMediaQuery(e),this.genTag(e))}static getMethodGen(e){return void 0===s.instance?s.instance=new s(e):s.instance.setCache(e),s.instance}setCache(e){this.cache=e,this.etsImport=new o.Cache(" ",1),this.etsVariable=new o.Cache(" ",1),this.etsFunction=new o.Cache(" ",1),this.aboutToAppear=new o.Cache(" ",2),this.needMediaQuery=!0}genParams(e){if("string"==typeof e)this.cache.concat(e);else if(e.size>0){this.cache.concat(i.TokenClass.LBRA,i.TokenClass.SPACE);let t=0;e.forEach(((r,n)=>{this.cache.concat(n,i.TokenClass.COLON,i.TokenClass.SPACE,r),t++,t{this.cache.concat(n,i.TokenClass.COLON,i.TokenClass.SPACE,r),t++,t{e.accept(this),this.cache.indentOff(),this.cache.concat(i.TokenClass.NEW_LINE),this.cache.indentOn()})),this.cache.decIndent(),this.cache.indentOn()),this.cache.indentOn(),this.cache.concat(i.TokenClass.RBRA)),(null!==e.properties||null!==e.mediaProperties)&&(null!==e.content&&0!==e.content.length||this.cache.incIndent(),this.getProperties(e).forEach(((e,t)=>{this.cache.concat(i.TokenClass.NEW_LINE),this.cache.indentOn(),this.cache.concat(i.TokenClass.PROPERTY_START,t,i.TokenClass.TAG_START),this.cache.indentOff(),"string"==typeof e?this.cache.concat(e,i.TokenClass.TAG_END):this.genObjectProperty(e)})),null!==e.content&&0!==e.content.length||this.cache.decIndent()),this.genEnd(e)}genStart(e){this.genIfStart(e),this.genForTagStart(e)}genEnd(e){this.genForTagEnd(e),this.genIfEnd(e)}genForTagStart(e){var t;void 0!==(null===(t=e.forEachObj)||void 0===t?void 0:t.for)&&(this.cache.concat("ForEach",i.TokenClass.TAG_START,e.forEachObj.for.toString(),i.TokenClass.COMMA,i.TokenClass.NEW_LINE),this.cache.concat(i.TokenClass.TAG_START,e.forEachObj.item,i.TokenClass.COLON," any",i.TokenClass.COMMA," ",e.forEachObj.idx,i.TokenClass.COLON," number",i.TokenClass.TAG_END," => ",i.TokenClass.LBRA,i.TokenClass.NEW_LINE))}genForTagEnd(e){null!==e.forEachObj&&(this.cache.concat(i.TokenClass.RBRA),void 0!==e.forEachObj.key&&""!==e.forEachObj.key&&(this.cache.concat(i.TokenClass.COMMA,i.TokenClass.NEW_LINE),this.cache.indentOn(),this.cache.concat(i.TokenClass.TAG_START,e.forEachObj.item,i.TokenClass.COLON," any",i.TokenClass.COMMA," ",e.forEachObj.idx,i.TokenClass.COLON," number",i.TokenClass.TAG_END," => ",i.TokenClass.LBRA,i.TokenClass.NEW_LINE),this.cache.concat("return ",e.forEachObj.key.toString(),i.TokenClass.TAG_START,e.forEachObj.item,i.TokenClass.COMMA," ",e.forEachObj.idx,i.TokenClass.TAG_END,i.TokenClass.RBRA),this.cache.indentOff()),this.cache.concat(i.TokenClass.TAG_END))}genIfStart(e){null!==e.ifBoolean&&(this.cache.concat("if",i.TokenClass.SPACE,i.TokenClass.TAG_START,e.ifBoolean.toString(),i.TokenClass.TAG_END,i.TokenClass.SPACE,i.TokenClass.LBRA,i.TokenClass.NEW_LINE),this.cache.incIndent())}genIfEnd(e){null!==e.ifBoolean&&(this.cache.indentOn(),this.cache.decIndent(),this.cache.concat(i.TokenClass.NEW_LINE),this.cache.concat(i.TokenClass.RBRA),this.cache.indentOff())}genMediaQuery(e){const t=new Map,r=new Map;if(this.collectMediaQueryMap(e,t),this.collectDefaultValueMap(e,r),0===t.size&&0===r.size)return;const n=a.getUniqueName("mediaQuery"),s=a.getUniqueName("initForMediaQuery"),c=a.getUniqueName("mediaQueryCb"),u=a.getUniqueName("saveMediaQueryResult"),l=a.getUniqueName("updateForMediaQuery"),p=new o.Cache(i.TokenClass.INDENT,1),f=new o.Cache(i.TokenClass.INDENT,1),d=new o.Cache(i.TokenClass.INDENT,1),y=new o.Cache(i.TokenClass.INDENT,1),h=new o.Cache(i.TokenClass.INDENT,1),m=new o.Cache(i.TokenClass.INDENT,1),g=new o.Cache(i.TokenClass.INDENT,1),E=new o.Cache(i.TokenClass.INDENT,2);this.genVariableDeclare(r,p),this.genMediaQueryCb(c,f),this.genMediaQueryListener(t,d,y),this.genInitFuc(s,r,h),this.genMediaQueryCbFnc(u,l,t,m),this.genUpdateFnc(l,s,t,g),this.genAboutToAppear(c,u,t,E),this.etsImport.indentOff(),this.aboutToAppear.indentOff(),this.etsVariable.indentOff(),this.etsFunction.indentOff(),this.etsImport.indentOff(),this.etsImport.concat("import ",n," from '@ohos.mediaquery'"),this.aboutToAppear.concat(E.toString()),this.etsVariable.concat(p.toString(),f.toString(),d.toString(),y.toString()),this.etsFunction.concat(m.toString(),i.TokenClass.NEW_LINE,h.toString(),i.TokenClass.NEW_LINE,g.toString()),this.etsImport.indentOn(),this.aboutToAppear.indentOn(),this.etsVariable.indentOn(),this.etsFunction.indentOn(),this.needMediaQuery=!1}genVariableDeclare(e,t){e.forEach(((e,r)=>{t.concat(i.TokenClass.DECORATOR_STATE,i.TokenClass.SPACE,r.slice(5),i.TokenClass.COLON,i.TokenClass.SPACE,e[1],i.TokenClass.SPACE,i.TokenClass.ASSIGN,i.TokenClass.SPACE,i.TokenClass.UNDEFINED,i.TokenClass.NEW_LINE)}))}genMediaQueryCb(e,t){t.concat(e,i.TokenClass.SPACE,i.TokenClass.ASSIGN,i.TokenClass.SPACE,i.TokenClass.NULL,i.TokenClass.NEW_LINE)}genMediaQueryListener(e,t,r){const n=a.getUniqueName("mediaQuery");e.forEach(((e,o)=>{const s=a.getUniqueName(this.getMediaQueryVariableName(o));t.concat(s,i.TokenClass.COLON,i.TokenClass.SPACE,i.TokenClass.BOOLEAN,i.TokenClass.SPACE,i.TokenClass.ASSIGN,i.TokenClass.SPACE,i.TokenClass.FALSE,i.TokenClass.NEW_LINE),r.concat(`listener_${s}`,i.TokenClass.SPACE,i.TokenClass.ASSIGN,i.TokenClass.SPACE,n,i.TokenClass.PROPERTY_START,"matchMediaSync",i.TokenClass.TAG_START,`'${o}'`,i.TokenClass.TAG_END,i.TokenClass.NEW_LINE)}))}genInitFuc(e,t,r){r.concat(e,i.TokenClass.TAG_START,i.TokenClass.TAG_END,i.TokenClass.SPACE,i.TokenClass.LBRA,i.TokenClass.NEW_LINE),r.indentOn(),r.incIndent(),t.forEach(((e,t)=>{r.concat(t,i.TokenClass.SPACE,i.TokenClass.ASSIGN,i.TokenClass.SPACE,e[0],i.TokenClass.NEW_LINE)})),r.decIndent(),r.concat(i.TokenClass.RBRA,i.TokenClass.NEW_LINE)}genMediaQueryCbFnc(e,t,r,n){const o=Array.from(r.entries());n.concat(e,i.TokenClass.TAG_START,"mediaQueryResult",i.TokenClass.TAG_END,i.TokenClass.SPACE,i.TokenClass.LBRA,i.TokenClass.NEW_LINE),n.incIndent(),n.concat(i.TokenClass.SWITCH,i.TokenClass.SPACE,i.TokenClass.TAG_START,"mediaQueryResult.media",i.TokenClass.TAG_END,i.TokenClass.SPACE,i.TokenClass.LBRA,i.TokenClass.NEW_LINE),n.incIndent();for(let e=0;e{const r=a.getUniqueName(this.getMediaQueryVariableName(t));n.concat(i.TokenClass.IF,i.TokenClass.SPACE,i.TokenClass.TAG_START,i.TokenClass.THIS,i.TokenClass.PROPERTY_START,r,i.TokenClass.TAG_END,i.TokenClass.SPACE,i.TokenClass.LBRA,i.TokenClass.NEW_LINE),n.incIndent(),e.forEach(((e,t)=>{n.concat(t,i.TokenClass.SPACE,i.TokenClass.ASSIGN,i.TokenClass.SPACE,e,i.TokenClass.NEW_LINE)})),n.decIndent(),n.concat(i.TokenClass.RBRA,i.TokenClass.NEW_LINE)})),n.decIndent(),n.concat(i.TokenClass.RBRA,i.TokenClass.NEW_LINE)}genAboutToAppear(e,t,r,n){let o=1;n.concat(i.TokenClass.THIS,i.TokenClass.PROPERTY_START,e,i.TokenClass.SPACE,i.TokenClass.ASSIGN,i.TokenClass.SPACE,i.TokenClass.THIS,i.TokenClass.PROPERTY_START,`${t}.bind(this)`,i.TokenClass.NEW_LINE),r.forEach(((t,s)=>{const c=`listener_${a.getUniqueName(this.getMediaQueryVariableName(s))}`;n.indentOn(),n.concat(i.TokenClass.THIS,i.TokenClass.PROPERTY_START,c,i.TokenClass.PROPERTY_START,`on('change', this.${e})`),o0?e.mediaParams:e.params}getProperties(e){const t=new Map;return e.properties.forEach(((e,r)=>{t.set(r,e)})),e.mediaProperties.forEach(((e,r)=>{t.set(r,e)})),t}collectDefaultValueMap(e,t){void 0!==e.defaultValue&&e.defaultValue.forEach(((e,r)=>{t.set(r,e)})),null!==e.content&&0!==e.content.length&&e.content.forEach((e=>{this.collectDefaultValueMap(e,t)}))}collectMediaQueryMap(e,t){void 0!==e.mediaKeyProperty&&e.mediaKeyProperty.forEach(((e,r)=>{var n;const o=null!==(n=t.get(r))&&void 0!==n?n:new Map;e.forEach(((e,t)=>{o.set(t,e)})),t.set(r,o)})),null!==e.content&&0!==e.content.length&&e.content.forEach((e=>{this.collectMediaQueryMap(e,t)}))}getMediaQueryVariableName(e){const t="device-type: ",r="orientation: ",n=e.substring(e.indexOf(t),e.length),o=n.substring(t.length,n.indexOf(")")),i=e.substring(e.indexOf(r),e.length),a=i.substring(r.length,i.indexOf(")"));return`${o}${a.slice(0,1).toUpperCase()+a.slice(1).toLowerCase()}`}}t.ASTNodeGenerator=s,s.instance=void 0},413:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ETSBridge=void 0;const n=r(519),o=r(973),i=r(497);t.ETSBridge=class{constructor(){this.errors=0}error(e){console.error("Code generating error: "+e),this.errors+=1}getErrorCount(){return this.errors}visit(e){const t=new Map;let r=null;const a=new Map,s=new n.Tag(e.type,t,r,a,null);if(o.parseVisualModel(e,s),i.parseMediaVisualModel(e,s),e.children.length>0){r=[];for(const t of e.children)r.push(t.accept(this))}return s.content=r,s}}},459:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.genETS=void 0;const n=r(623),o=r(862);t.genETS=function(e){const t=n.ASTNodeGenerator.getMethodGen(new o.Cache(" ",2));return e.accept(t),{build:t.cache.toString(),etsImport:t.etsImport.toString(),etsVariable:t.etsVariable.toString(),etsFunction:t.etsFunction.toString(),aboutToAppear:t.aboutToAppear.toString()}}},435:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringWriter=void 0;const n=r(459);t.StringWriter=class{genETS(e){return n.genETS(e)}}},51:(e,t)=>{"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),t.TokenClass=void 0,(r=t.TokenClass||(t.TokenClass={}))[r.IDENTIFIER=0]="IDENTIFIER",r[r.STRING_LITERAL=1]="STRING_LITERAL",r[r.NUMBER=2]="NUMBER",r[r.CHARACTER=3]="CHARACTER",r[r.EOF=4]="EOF",r[r.INVALID=5]="INVALID",r.EMPTY_DATA="empty",r.ASSIGN="=",r.INDENT=" ",r.NEW_LINE="\n",r.CARRIAGE_RETURN="\r",r.SPACE=" ",r.LQUOTE="'",r.RQUOTE="'",r.TAG_START="(",r.TAG_END=")",r.EMPTY_TAG_END="/>",r.END_TAG_START="{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isMediaProperty=t.parseMediaVisualModel=void 0;const n=r(294),o=r(973),i=r(290),a=o.curry(((e,t)=>t.hasMediaProperty(e))),s=o.curry(((e,t,r)=>r.type===e&&r.hasMediaProperty(t)));function c(e){const t=e+"-visual",r=i.etsPropertyList;let n="";for(const e of r)void 0!==e.propertySet.properties&&(n=u(t,e.propertySet.properties)),e.propertySet.property===t&&(n=e.propertySet.etsType);return function(e=""){const t=new Map([["ETSBoolean","boolean"],["ETSNumber","number"],["ETSString","string"],["Rfloat","Resource"],["Rstring","Resource"],["Rcolor","Resource"],["Rmedia","Resource"],["Rrawfile","Resource"],["ETSArray","any[]"]]),r=new Array;return e.split("|").forEach((e=>{const n=t.get(e);"Resource"!==n&&r.push(null!=n?n:e)})),r.join(" | ")}(n)}function u(e,t){for(const r of t)if(r.property===e)return r.etsType;return""}function l(e,t,r){const n=t.get(r);return void 0!==n&&n.has(e)}function p(e){return isNaN(Number(e))?o.getEtsEnumValue("FontWeight.",e):e}function f(e){let t=o.getEtsEnumValue("FlexAlign.",e);return"flex-start"===e?t="FlexAlign.Start":"flex-end"===e&&(t="FlexAlign.End"),t}function d(e){return"TextOverflow."+o.firstUpperCase(e)}function y(e,t,r){var n,i;const a=new Map,s=null!==(n=e.mediaProperty)&&void 0!==n?n:new Map,c=null!==(i=e.dynamicMediaProperty)&&void 0!==i?i:new Map;return s.forEach(((e,n)=>{let i=e.get(t);const s=e.get(r);o.isEmptyOrUndefined(i)&&o.isEmptyOrUndefined(s)||(i="0"===i||o.isEmptyOrUndefined(i)?"0":i.substring(0,i.length-2),a.set(n,i))})),c.forEach(((e,r)=>{const n=e.get(t);o.isEmptyOrUndefined(n)||a.set(r,n)})),a}function h(e,t,r){var n,i,a,s;const c=null!==(n=e.property.get("left"))&&void 0!==n?n:e.dynamicProperty.get("left"),u=null!==(i=e.property.get("top"))&&void 0!==i?i:e.dynamicProperty.get("top"),l=t.get("left"),p=t.get("top"),f=r.get("left"),d=r.get("top");let y="undefined",h="undefined";return o.isEmptyOrUndefined(l)&&o.isEmptyOrUndefined(p)||(y=o.quoteString(null!==(a=null!=l?l:c)&&void 0!==a?a:"0"),h=o.quoteString(null!==(s=null!=p?p:u)&&void 0!==s?s:"0")),o.isEmptyOrUndefined(f)&&o.isEmptyOrUndefined(d)||(y=null!=f?f:y,h=null!=d?d:h),{leftValue:y,topValue:h}}function m(e,t){e.forEach(((e,r)=>{"undefined"!==e&&t.set(r,"undefined")}))}function g(e,t){var r,n;const i=new Map,a=t.split("-")[0];return(null!==(r=e.mediaProperty)&&void 0!==r?r:new Map).forEach(((r,n)=>{var s,c,u,l;const p=r.get(a),f=null===(c=null===(s=e.dynamicMediaProperty)||void 0===s?void 0:s.get(n))||void 0===c?void 0:c.get(a),d=null!==(l=null!==(u=r.get(t))&&void 0!==u?u:f)&&void 0!==l?l:p;void 0!==d&&i.set(n,o.quoteString(d))})),(null!==(n=e.dynamicMediaProperty)&&void 0!==n?n:new Map).forEach(((e,r)=>{var n;const o=e.get(a),s=null!==(n=e.get(t))&&void 0!==n?n:o;void 0!==s&&i.set(r,s)})),i}function E(e,t,r){var n,i;const a=new Map;return(null!==(n=e.mediaProperty)&&void 0!==n?n:new Map).forEach(((e,n)=>{let i=e.get(t);o.isEmptyOrUndefined(i)||("function"==typeof r&&(i=r(i)),o.isEmptyOrUndefined(i)||a.set(n,i))})),(null!==(i=e.dynamicMediaProperty)&&void 0!==i?i:new Map).forEach(((e,r)=>{let n=e.get(t);void 0===n||"content"!==t&&"label"!==t||(n=o.getContentName(n)),o.isEmptyOrUndefined(n)||a.set(r,n)})),a}function v(e,t){const r=`this.${o.getEtsPropName(e)}${o.firstUpperCase(o.getEtsPropName(t))}`;return`${r}_${n.getUniqueId(r)}`}function T(e,t,r){var n;const i=e.property.get(t),a=e.dynamicProperty.get(t);let s=null!==(n=new Map([["if","true"],["auto-play","false"],["interval","3000"]]).get(t))&&void 0!==n?n:"undefined";return o.isEmptyOrUndefined(i)||(s="function"==typeof r?r(i):i,s=o.isEmptyOrUndefined(s)?"undefined":s),o.isEmptyOrUndefined(a)||(s=a),s}const S=o.curry(((e,t,r)=>{const n=E(t,e,o.quoteString);if(0===n.size)return;const i=T(t,e,o.quoteString),a=v(t.id,e);r.setDefaultValue(a,c(e),i),r.setMediaProperty(a,n),r.mediaProperties.set(o.getEtsPropName(e),a)})),_=o.curry(((e,t,r)=>{const n=E(t,e);if(0===n.size)return;const i=T(t,e),a=v(t.id,e);r.setDefaultValue(a,c(e),i),r.setMediaProperty(a,n),r.mediaProperties.set(o.getEtsPropName(e),a)})),N=o.curry(((e,t,r)=>{const n=E(t,e);if(0===n.size)return;const i=T(t,e),a=v(t.id,e);r.setDefaultValue(a,c(e),i),r.setMediaProperty(a,n),r.mediaProperties.set(o.getEtsPropName(e),a)})),A=o.curry(((e,t,r,n)=>{const i=E(r,e,o.curry(o.getEtsEnumValue)(t));if(0===i.size)return;const a=T(r,e,o.curry(o.getEtsEnumValue)(t)),s=v(r.id,e);n.setDefaultValue(s,c(e),a),n.setMediaProperty(s,i),n.mediaProperties.set(o.getEtsPropName(e),s)})),C=o.curry(((e,t,r)=>{const n=E(t,e,o.quoteString);if(!(r.mediaParams instanceof Map)||0===n.size)return;const i=T(t,e,o.quoteString),a=v(t.id,e);r.setDefaultValue(a,c(e),i),r.setMediaProperty(a,n),r.mediaParams.set(o.getEtsPropName(e),a)})),w=o.curry(((e,t,r)=>{const n=E(t,e);if(!(r.mediaParams instanceof Map)||0===n.size)return;const i=T(t,e),a=v(t.id,e);r.setDefaultValue(a,c(e),i),r.setMediaProperty(a,n),r.mediaParams.set(o.getEtsPropName(e),a)})),b=o.curry(((e,t,r,n)=>{const i=E(r,e,o.curry(o.getEtsEnumValue)(t));if(!(n.mediaParams instanceof Map)||0===i.size)return;const a=T(r,e,o.curry(o.getEtsEnumValue)(t)),s=v(r.id,e);n.setDefaultValue(s,c(e),a),n.setMediaProperty(s,i),n.mediaParams.set(o.getEtsPropName(e),s)})),R=o.curry(((e,t,r)=>{const n=E(t,e,o.dealWithColor);if(0===n.size)return;const i=T(t,e,o.dealWithColor),a=v(t.id,e);r.setDefaultValue(a,c(e),i),r.setMediaProperty(a,n),r.mediaProperties.set(o.getEtsPropName(e),a)}));function O(e,t,r,n=!1){o.isEmptyOrUndefined(t)||r.set(e,n?t:o.quoteString(t))}t.parseMediaVisualModel=function(e,t){!function(e,t){var r,n,o;const i=null!==(r=e.dynamicProperty.get("for"))&&void 0!==r?r:"[1]",a=null!==(n=e.property.get("item"))&&void 0!==n?n:"item",s=null!==(o=e.property.get("idx"))&&void 0!==o?o:"idx",u=e.dynamicProperty.get("keyGenerator"),l=E(e,"for");if(0===l.size)return;const p=v(e.id,"for"),f={for:p,key:u,item:a,idx:s};t.setDefaultValue(p,c("for"),i),t.setMediaProperty(p,l),t.setForEachObj(f)}(e,t),function(e,t){const r=E(e,"if");if(0===r.size)return;const n=T(e,"if"),o=v(e.id,"if");t.setDefaultValue(o,c("if"),n),t.setMediaProperty(o,r),t.setIfBoolean(o)}(e,t);for(const r of V)("boolean"==typeof r[0]||r[0](e))&&r[1](e,t)};const I=o.curry(((e,t,r)=>{const n=new Map,i=t.property.get(e),a=t.dynamicProperty.get(e),s=null!=a?a:i,u=["top","bottom","left","right"];let l=0;for(const i of u){const a=`${e}-${i}`,u=t.property.get(a),p=t.dynamicProperty.get(a),f=g(t,a);let d=o.isEmptyOrUndefined(s)?"undefined":o.quoteString(s);if(o.isEmptyOrUndefined(u)||(d=o.quoteString(u)),o.isEmptyOrUndefined(p)||(d=p),f.size>0){const e=v(t.id,a);r.setDefaultValue(e,c(a),d),r.setMediaProperty(e,f),O(i,e,n,!0),l++}else O(i,d,n,!0)}l>0&&r.mediaProperties.set(e,n)}));function M(e){return new Set(["Cover","Contain","Auto"]).has(e)?o.getEtsEnumValue("ImageSize.",e):"undefined"}function P(e){const t=e.match(/^ *((0|[1-9][0-9]*)(px|vp|lpx|%))( *$| +((0|[1-9][0-9]*)(px|vp|lpx|%)) *$)/);return null===t?"undefined":void 0!==t[5]?`{ width: ${o.quoteString(t[1])}, height: ${o.quoteString(t[5])} }`:`{ width: ${o.quoteString(t[1])} }`}function x(e,t){var r,n;const i=new Map,a=new Map,s=k(t),c=F(t);return(null!==(r=e.mediaProperty)&&void 0!==r?r:new Map).forEach(((e,r)=>{const n=e.get(t);o.isEmptyOrUndefined(n)||(i.set(r,s(n)),a.set(r,c(n)))})),(null!==(n=e.dynamicMediaProperty)&&void 0!==n?n:new Map).forEach(((e,r)=>{const n=e.get(t);o.isEmptyOrUndefined(n)||(i.set(r,n),a.set(r,"undefined"))})),{enumValueMap:i,objValueMap:a}}function L(e,t){const r=e.property.get(t),n=e.dynamicProperty.get(t),i=k(t),a=F(t);let s="undefined",c="undefined";return o.isEmptyOrUndefined(r)||(s=i(r),c=a(r)),o.isEmptyOrUndefined(n)||(s=n,c="undefined"),{enumDefault:s,objDefault:c}}function k(e){return new Map([["background-image-size",M],["background-image-position",D]]).get(e)}function F(e){return new Map([["background-image-size",P],["background-image-position",U]]).get(e)}function D(e){return new Set(["TopStart","Top","TopEnd","Start","Center","End","BottomStart","Bottom","BottomEnd"]).has(e)?"Alignment."+e:"undefined"}function U(e){const t=e.match(/^ *((0|[1-9][0-9]*)(px|vp|lpx|%)) +((0|[1-9][0-9]*)(px|vp|lpx|%)) *$/);return null===t?"undefined":`{ x: ${o.quoteString(t[1])}, y: ${o.quoteString(t[4])} }`}const B=o.curry(((e,t,r,n)=>{const o=E(r,e,f);if(!(n.mediaProperties instanceof Map)||0===o.size)return;const i=T(r,e,f),a=v(r.id,e);n.setDefaultValue(a,c(e),i),n.setMediaProperty(a,o),n.mediaProperties.set("justifyContent",a)})),G=o.curry(((e,t,r,n)=>{const i=E(r,e,f);if(!(n.mediaParams instanceof Map)||0===i.size)return;const a=T(r,e,f),s=v(r.id,e);n.setDefaultValue(s,c(e),a),n.setMediaProperty(s,i),n.mediaParams.set(o.getEtsPropName(e),s)})),z=o.curry(((e,t)=>t.type===e));t.isMediaProperty=function(e,t){return!l(e,j,"common")&&!l(e,j,t)&&!l(e,j,"events")};const j=new Map([["common",new Set(["keyGenerator","item","idx"])],["events",new Set([...o.events])]]),V=[[a("width"),S("width")],[a("height"),S("height")],[function(e){return e.hasMediaProperty("constraint-size-min-width")||e.hasMediaProperty("constraint-size-max-width")||e.hasMediaProperty("constraint-size-min-height")||e.hasMediaProperty("constraint-size-min-height")},function(e,t){const r=new Map,n=["min-width","max-width","min-height","max-height"];for(const i of n){const n=`constraint-size-${i}`,a=E(e,n,o.quoteString),s=T(e,n,o.quoteString);if(a.size>0){const u=v(e.id,n);t.setDefaultValue(u,c(n),s),t.setMediaProperty(u,a),O(o.getEtsPropName(i),u,r,!0)}}r.size>0&&t.mediaProperties.set("constraintSize",r)}],[a("align"),A("align","Alignment.")],[a("direction"),A("direction","Direction.")],[function(e){return e.hasMediaProperty("left")||e.hasMediaProperty("top")},function(e,t){var r;const n=null!==(r=e.property.get("position"))&&void 0!==r?r:"relative",{leftValue:o,topValue:i}=h(e,e.property,e.dynamicProperty),{mediaPositionLeft:a,mediaPositionTop:s,mediaOffsetLeft:u,mediaOffsetTop:l}=function(e){var t,r;const n=new Map,o=new Map,i=new Map,a=new Map,s=null!==(t=e.mediaProperty)&&void 0!==t?t:new Map,c=null!==(r=e.dynamicMediaProperty)&&void 0!==r?r:new Map,u=new Set;for(const[e]of s)u.add(e);for(const[e]of c)u.add(e);return u.forEach((t=>{var r,s,c,u;const l=null!==(s=null===(r=e.mediaProperty)||void 0===r?void 0:r.get(t))&&void 0!==s?s:new Map,p=null!==(u=null===(c=e.dynamicMediaProperty)||void 0===c?void 0:c.get(t))&&void 0!==u?u:new Map,f=l.get("position"),{leftValue:d,topValue:y}=h(e,l,p);"absolute"===f?("undefined"!==d&&n.set(t,d),"undefined"!==y&&o.set(t,y)):("undefined"!==d&&i.set(t,d),"undefined"!==y&&a.set(t,y))})),{mediaPositionLeft:n,mediaPositionTop:o,mediaOffsetLeft:i,mediaOffsetTop:a}}(e),p=a.size>0||s.size>0||"absolute"===n,f=u.size>0||l.size>0||"relative"===n,d=v(e.id,"positionLeft"),y=v(e.id,"positionTop"),g=v(e.id,"offsetLeft"),E=v(e.id,"offsetTop");if(0!==a.size||0!==s.size||0!==l.size||0!==u.size){if(p&&f&&(m(a,u),m(u,a),m(s,l),m(l,s)),p){const e="absolute"===n?o:"undefined",r="absolute"===n?i:"undefined";t.setDefaultValue(d,c("left"),e),t.setDefaultValue(y,c("top"),r),t.setMediaProperty(d,a),t.setMediaProperty(y,s),t.mediaProperties.set("position",new Map([["x",d],["y",y]]))}if(f){const e="relative"===n?o:"undefined",r="relative"===n?i:"undefined";t.setDefaultValue(g,c("left"),e),t.setDefaultValue(E,c("top"),r),t.setMediaProperty(g,u),t.setMediaProperty(E,l),t.mediaProperties.set("offset",new Map([["x",g],["y",E]]))}}}],[a("aspect-ratio"),_("aspect-ratio")],[a("display-priority"),_("display-priority")],[a("flex-basis"),S("flex-basis")],[a("flex-grow"),_("flex-grow")],[a("flex-shrink"),_("flex-shrink")],[a("align-self"),function(e,t){const r=E(e,"align-self",o.dealWithAlignSelf);if(0===r.size)return;const n=T(e,"align-self",o.dealWithAlignSelf),i=v(e.id,"align-self");t.setDefaultValue(i,c("align-self"),n),t.setMediaProperty(i,r),t.mediaProperties.set("alignSelf",i)}],[a("border-style"),A("border-style","BorderStyle.")],[a("border-width"),S("border-width")],[a("border-color"),R("border-color")],[a("border-radius"),S("border-radius")],[a("background-color"),R("background-color")],[function(e){return e.hasMediaProperty("background-image-src")||e.hasMediaProperty("background-image-repeat")},function(e,t){const r=e.property.get("background-image-src"),n=e.property.get("background-image-repeat"),i=e.dynamicProperty.get("background-image-src"),a=e.dynamicProperty.get("background-image-repeat"),s=E(e,"background-image-src",o.dealWithSrc),u=E(e,"background-image-repeat",o.dealWithBackgroundRepeat);if(0===s.size&&0===u.size)return;let l=o.dealWithSrc(null!=r?r:"");if(o.isEmptyOrUndefined(i)||(l=i),s.size>0){const r=v(e.id,"background-image-src");t.setDefaultValue(r,c("background-image-src"),l),t.setMediaProperty(r,s),l=r}let p="undefined";if(!o.isEmptyOrUndefined(n)){const e=o.dealWithBackgroundRepeat(n);null!=e&&""!==e&&(p=e)}if(o.isEmptyOrUndefined(a)||(p=a),u.size>0){const r=v(e.id,"background-image-repeat");t.setDefaultValue(r,c("background-image-repeat"),p),t.setMediaProperty(r,u),p=r}t.mediaProperties.set("backgroundImage",l+", "+p)}],[a("background-image-size"),function(e,t){const{enumValueMap:r,objValueMap:n}=x(e,"background-image-size");if(0===r.size&&0===n.size)return;const{enumDefault:o,objDefault:i}=L(e,"background-image-size"),a=v(e.id,"background-image-size-enum"),s=v(e.id,"background-image-size-obj");t.setDefaultValue(a,"ImageSize",o),t.setDefaultValue(s,"SizeOptions",i),t.setMediaProperty(a,r),t.setMediaProperty(s,n),t.mediaProperties.set("backgroundImageSize",`${a} !== undefined ? ${a} : ${s}`)}],[a("background-image-position"),function(e,t){const{enumValueMap:r,objValueMap:n}=x(e,"background-image-position");if(0===r.size&&0===n.size)return;const{enumDefault:o,objDefault:i}=L(e,"background-image-position"),a=v(e.id,"background-image-position-enum"),s=v(e.id,"background-image-position-obj");t.setDefaultValue(a,"Alignment",o),t.setDefaultValue(s,"Position",i),t.setMediaProperty(a,r),t.setMediaProperty(s,n),t.mediaProperties.set("backgroundImagePosition",`${a} !== undefined ? ${a} : ${s}`)}],[a("opacity"),_("opacity")],[a("visibility"),A("visibility","Visibility.")],[a("enabled"),N("enabled")],[a("font-color"),R("font-color")],[a("font-size"),S("font-size")],[a("font-style"),A("font-style","FontStyle.")],[a("font-weight"),function(e,t){const r=E(e,"font-weight",o.dealWithFontWeight);if(0===r.size)return;const n=T(e,"font-weight",o.dealWithFontWeight),i=v(e.id,"font-weight");t.setDefaultValue(i,c("font-weight"),n),t.setMediaProperty(i,r),t.mediaProperties.set("fontWeight",i)}],[a("font-family"),S("font-family")],[function(e){return e.hasMediaProperty("margin")||e.hasMediaProperty("margin-left")||e.hasMediaProperty("margin-top")||e.hasMediaProperty("margin-right")||e.hasMediaProperty("margin-bottom")},I("margin")],[function(e){return e.hasMediaProperty("padding")||e.hasMediaProperty("padding-left")||e.hasMediaProperty("padding-top")||e.hasMediaProperty("padding-right")||e.hasMediaProperty("padding-bottom")},I("padding")],[s("button","label"),function(e,t){const r=e.property.get("label"),n=e.dynamicProperty.get("label"),i=E(e,"label",o.quoteString);if(0===i.size)return;let a="''";o.isEmptyOrUndefined(r)||(a=o.quoteString(r)),o.isEmptyOrUndefined(n)||(a=o.getContentName(n));const s=v(e.id,"label");t.setDefaultValue(s,c("label"),a),t.setMediaProperty(s,i),t.setMediaParams(s)}],[s("button","type"),A("type","ButtonType.")],[s("button","state-effect"),N("state-effect")],[s("divider","vertical"),N("vertical")],[s("divider","color"),R("color")],[s("divider","stroke-width"),S("stroke-width")],[s("divider","line-cap"),A("line-cap","LineCapStyle.")],[z("image"),function(e,t){var r;const n=null!==(r=e.property.get("src"))&&void 0!==r?r:"",i=e.dynamicProperty.get("src"),a=E(e,"src",o.quoteString);if(0===a.size)return;let s=o.dealWithSrc(n);o.isEmptyOrUndefined(i)||(s=i);const u=v(e.id,"src");t.setDefaultValue(u,c("src"),s),t.setMediaProperty(u,a),t.setMediaParams(u)}],[s("image","alt"),S("alt")],[s("image","object-fit"),A("object-fit","ImageFit.")],[s("image","object-repeat"),A("object-repeat","ImageRepeat.")],[s("image","interpolation"),A("interpolation","ImageInterpolation.")],[s("image","render-mode"),A("render-mode","ImageRenderMode.")],[function(e){return e.hasMediaProperty("source-size-width")||e.hasMediaProperty("source-size-height")},function(e,t){let r=e.property.get("source-size-width"),n=e.property.get("source-size-height");const i=e.dynamicProperty.get("source-size-width"),a=e.dynamicProperty.get("source-size-height"),s=y(e,"source-size-width","source-size-height"),u=y(e,"source-size-height","source-size-width");if(0===s.size)return;r="0"===r||o.isEmptyOrUndefined(r)?"0":r.substring(0,r.length-2),n="0"===n||o.isEmptyOrUndefined(n)?"0":n.substring(0,n.length-2),o.isEmptyOrUndefined(i)||(r=i),o.isEmptyOrUndefined(a)||(n=a);const l=v(e.id,"source-size-width"),p=v(e.id,"source-size-height");t.setDefaultValue(l,c("source-size-width"),r),t.setDefaultValue(p,c("source-size-height"),n),t.setMediaProperty(l,s),t.setMediaProperty(p,u);const f=new Map([["width",l],["height",p]]);t.mediaProperties.set("sourceSize",f)}],[function(e){return"progress"===e.type&&(e.hasMediaProperty("value")||e.hasMediaProperty("total")||e.hasMediaProperty("style"))},function(e,t){const r=e.property.get("value"),n=e.dynamicProperty.get("value"),i=E(e,"value");if(!(t.mediaParams instanceof Map)||0===i.size)return;let a=null!=r?r:"0";o.isEmptyOrUndefined(n)||(a=n);const s=v(e.id,"value");t.setDefaultValue(s,c("value"),a),t.setMediaProperty(s,i),t.mediaParams.set("value",s)}],[s("progress","total"),w("total")],[s("progress","style"),b("style","ProgressStyle.")],[s("progress","color"),R("color")],[s("slider","value"),w("value")],[s("slider","min"),w("min")],[s("slider","max"),w("max")],[s("slider","step"),w("step")],[s("slider","style"),b("style","SliderStyle.")],[s("slider","block-color"),R("block-color")],[s("slider","track-color"),R("track-color")],[s("slider","selected-color"),R("selected-color")],[s("slider","show-steps"),N("show-steps")],[s("slider","show-tips"),N("show-tips")],[s("text","content"),function(e,t){const r=e.property.get("content"),n=e.dynamicProperty.get("content"),i=E(e,"content",o.quoteString);if(0===i.size)return;let a="''";o.isEmptyOrUndefined(r)||(a=o.quoteString(r)),o.isEmptyOrUndefined(n)||(a=o.getContentName(n));const s=v(e.id,"content");t.setDefaultValue(s,c("content"),a),t.setMediaProperty(s,i),t.setMediaParams(s)}],[s("text","text-align"),A("text-align","TextAlign.")],[s("text","text-overflow"),function(e,t){const r=E(e,"text-overflow",d);if(0===r.size)return;const n=T(e,"text-overflow",d),o=v(e.id,"text-overflow");t.setDefaultValue(o,c("text-overflow"),n),t.setMediaProperty(o,r),t.mediaProperties.set("textOverflow",new Map([["overflow",o]]))}],[s("text","max-lines"),_("max-lines")],[s("text","line-height"),S("line-height")],[function(e){return"text"===e.type&&(e.hasMediaProperty("decoration-type")||e.hasMediaProperty("decoration-color"))},function(e,t){const r=E(e,"decoration-type",o.curry(o.getEtsEnumValue)("TextDecorationType.")),n=E(e,"decoration-color",o.dealWithColor);if(0===r.size&&0===n.size)return;let i=T(e,"decoration-type",o.curry(o.getEtsEnumValue)("TextDecorationType.")),a=T(e,"decoration-color",o.dealWithColor);if(r.size>0){const n=v(e.id,"decoration-type");t.setDefaultValue(n,c("decoration-type"),i),t.setMediaProperty(n,r),i=n}if(n.size>0){const r=v(e.id,"decoration-color");t.setDefaultValue(r,c("decoration-color"),a),t.setMediaProperty(r,n),a=r}const s=new Map([["type",i]]);t.mediaProperties.set("decoration",s),"undefined"!==a&&s.set("color",a)}],[s("text","baseline-offset"),S("baseline-offset")],[s("text","text-case"),A("text-case","TextCase.")],[s("column","space"),C("space")],[s("column","align-items-column"),function(e,t){const r=E(e,"align-items-column",o.dealWithColumnAlignItems);if(0===r.size)return;const n=T(e,"align-items-column",o.dealWithColumnAlignItems),i=v(e.id,"align-items-column");t.setDefaultValue(i,c("align-items-column"),n),t.setMediaProperty(i,r),t.mediaProperties.set("alignItems",i)}],[s("column","justify-content-rc"),B("justify-content-rc","FlexAlign.")],[s("row","space"),C("space")],[s("row","align-items-row"),function(e,t){const r=E(e,"align-items-row",o.dealWithRowAlignItems);if(0===r.size)return;const n=T(e,"align-items-row",o.dealWithRowAlignItems),i=v(e.id,"align-items-row");t.setDefaultValue(i,c("align-items-row"),n),t.setMediaProperty(i,r),t.mediaProperties.set("alignItems",i)}],[s("row","justify-content-rc"),B("justify-content-rc","FlexAlign.")],[s("flex","flex-direction"),function(e,t){const r=E(e,"flex-direction",o.curry(o.getEtsEnumValue)("FlexDirection."));if(!(t.mediaParams instanceof Map)||0===r.size)return;const n=T(e,"flex-direction",o.curry(o.getEtsEnumValue)("FlexDirection.")),i=v(e.id,"flex-direction");t.setDefaultValue(i,c("flex-direction"),n),t.setMediaProperty(i,r),t.mediaParams.set("direction",i)}],[s("flex","wrap"),function(e,t){const r=E(e,"wrap",o.dealWithWrap);if(!(t.mediaParams instanceof Map)||0===r.size)return;const n=T(e,"wrap",o.dealWithWrap),i=v(e.id,"wrap");t.setDefaultValue(i,c("wrap"),n),t.setMediaProperty(i,r),t.mediaParams.set("wrap",i)}],[s("flex","justify-content"),G("justify-content","FlexAlign.")],[s("flex","align-items-flex"),function(e,t){const r=E(e,"align-items-flex",o.dealWithFlexAlignItems);if(!(t.mediaParams instanceof Map)||0===r.size)return;const n=T(e,"align-items-flex",o.dealWithFlexAlignItems),i=v(e.id,"align-items-flex");t.setDefaultValue(i,c("align-items-flex"),n),t.setMediaProperty(i,r),t.mediaParams.set("alignItems",i)}],[s("flex","align-content"),G("align-content","FlexAlign.")],[s("list","space-list"),function(e,t){const r=E(e,"space-list");if(!(t.mediaParams instanceof Map)||0===r.size)return;const n=T(e,"space-list"),o=v(e.id,"space-list");t.setDefaultValue(o,c("space-list"),n),t.setMediaProperty(o,r),t.mediaParams.set("space",o)}],[s("list","initial-index"),w("initial-index")],[s("list","list-direction"),A("list-direction","Axis.")],[function(e){return"list"===e.type&&(e.hasMediaProperty("divider-stroke-width")||e.hasMediaProperty("divider-color")||e.hasMediaProperty("divider-start-margin")||e.hasMediaProperty("divider-end-margin"))},function(e,t){const r=[["divider-stroke-width",o.quoteString],["divider-color",o.dealWithColor],["divider-start-margin",o.quoteString],["divider-end-margin",o.quoteString]];let n=0;const i=new Map;for(const[a,s]of r){const r=E(e,a,s),u=o.getEtsPropName(a.replace("divider-",""));let l=T(e,a,s);if("undefined"===l&&"divider-stroke-width"===a&&(l="0"),r.size>0){const o=v(e.id,a);t.setDefaultValue(o,c(a),l),t.setMediaProperty(o,r),l=o,n++}i.set(u,l)}n>0&&t.mediaProperties.set("divider",i)}],[s("list","edit-mode"),N("edit-mode")],[s("list","edge-effect"),A("edge-effect","EdgeEffect.")],[s("list","chain-animation"),N("chain-animation")],[s("list-item","sticky"),A("sticky","Sticky.")],[s("list-item","editable"),N("editable")],[s("swiper","index"),_("index")],[s("swiper","auto-play"),N("auto-play")],[s("swiper","interval"),_("interval")],[s("swiper","indicator"),N("indicator")],[s("swiper","loop"),N("loop")],[s("swiper","duration"),_("duration")],[s("swiper","vertical"),N("vertical")],[s("swiper","item-space"),S("item-space")],[s("swiper","cached-count"),_("cached-count")],[s("swiper","disable-swipe"),N("disable-swipe")],[s("text-input","placeholder"),C("placeholder")],[s("text-input","textInput-type"),function(e,t){const r=E(e,"textInput-type",o.curry(o.getEtsEnumValue)("InputType."));if(0===r.size)return;const n=T(e,"textInput-type",o.curry(o.getEtsEnumValue)("InputType.")),i=v(e.id,"textInput-type");t.setDefaultValue(i,c("textInput-type"),n),t.setMediaProperty(i,r),t.mediaProperties.set("type",i)}],[s("text-input","placeholderColor"),R("placeholderColor")],[function(e){return"text-input"===e.type&&(e.hasMediaProperty("placeholderFont-size")||e.hasMediaProperty("placeholderFont-weight")||e.hasMediaProperty("placeholderFont-family")||e.hasMediaProperty("placeholderFont-style"))},function(e,t){const r=[["size",o.quoteString],["weight",p],["family",o.quoteString],["style",o.curry(o.getEtsEnumValue)("FontStyle.")]];let n=0;const i=new Map;for(const[o,a]of r){const r=`placeholderFont-${o}`,s=E(e,r,a);let u=T(e,r,a);if(s.size>0){const o=v(e.id,r);t.setDefaultValue(o,c(r),u),t.setMediaProperty(o,s),u=o,n++}i.set(o,u)}n>0&&t.mediaProperties.set("placeholderFont",i)}],[s("text-input","enterKeyType"),A("enterKeyType","EnterKeyType.")],[s("text-input","caretColor"),R("caretColor")],[s("text-input","maxLength"),_("maxLength")]]},973:(e,t)=>{"use strict";function r(e){return(...t)=>t.lengtht.property.has(e)||t.dynamicProperty.has(e))),o=r(((e,t,r)=>r.type===e&&(r.property.has(t)||r.dynamicProperty.has(t))));function i(e){return JSON.stringify(e)}function a(e,t,r){const n=t.dynamicProperty.get(e);return void 0!==n&&""!==n.trim()&&(r.properties.set(E(e),n),!0)}t.quoteString=i;const s=r(((e,t,r)=>{if(a(e,t,r))return;const n=t.property.get(e);void 0!==n&&r.properties.set(E(e),i(n))}));function c(e){return void 0===e||""===e}t.isEmptyOrUndefined=c;const u=r(((e,t,r)=>{if(a(e,t,r))return;const n=t.property.get(e);c(n)||r.properties.set(E(e),n)})),l=r(((e,t,r)=>{if(a(e,t,r))return;const n=t.property.get(e);c(n)||r.properties.set(E(e),n)})),p=r(((e,t,r,n)=>{if(a(e,r,n))return;const o=r.property.get(e);c(o)||n.properties.set(E(e),v(t,o))}));function f(e,t,r){const n=t.dynamicProperty.get(e);return void 0!==n&&""!==n.trim()&&r.params instanceof Map&&(r.params.set(E(e),n),!0)}const d=r(((e,t,r)=>{if(f(e,t,r))return;const n=t.property.get(e);void 0!==n&&r.params instanceof Map&&r.params.set(E(e),i(n))})),y=r(((e,t,r)=>{if(f(e,t,r))return;const n=t.property.get(e);!c(n)&&r.params instanceof Map&&r.params.set(E(e),n)})),h=r(((e,t,r,n)=>{if(f(e,r,n))return;const o=r.property.get(e);!c(o)&&n.params instanceof Map&&n.params.set(E(e),v(t,o))})),m=r(((e,t,r)=>{if(a(e,t,r))return;let n=t.property.get(e);c(n)||(n=T(n),r.properties.set(E(e),n))}));function g([e,...t]){return(null==e?void 0:e.toUpperCase())+t.join("")}function E(e){const t=e.split("-");let r=t[0];for(let e=1;ee[0].toUpperCase()+e.slice(1))).join(""));const n=function(e){var t,r;const n=e.dynamicProperty.get("for"),o=e.dynamicProperty.get("keyGenerator"),i=null!==(t=e.property.get("item"))&&void 0!==t?t:"item",a=null!==(r=e.property.get("idx"))&&void 0!==r?r:"idx";return void 0!==e.dynamicProperty.get("for")?{for:n,key:o,item:i,idx:a}:null}(e);r.setForEachObj(n);const o=void 0!==e.dynamicProperty.get("if")?e.dynamicProperty.get("if"):e.property.get("if");void 0===o?r.setIfBoolean(null):r.setIfBoolean(o);for(const t of L)("boolean"==typeof t[0]||t[0](e))&&t[1](e,r);!function(e,r){for(let n of t.events){const t=e.property.get(n);"onDisappear"===n&&(n="onDisAppear");const o=".bind(this)";void 0!==t&&""!==t&&("this"===t.split(".")[0]?r.properties.set(n,t+o):r.properties.set(n,t))}}(e,r)},t.events=["onClick","onTouch","onAppear","onDisappear","onKeyEvent","onAreaChange","onItemDelete","onScrollIndex","onItemDragEnter","onItemDragMove","onItemDragLeave","onItemDragStart","onItemDrop","onComplete","onError","onFinish","onChange","onSubmit","onEditChanged"],t.firstUpperCase=g,t.getEtsPropName=E,t.getEtsEnumValue=v,t.dealWithColor=T;const _=r(((e,t,r,n)=>{if(!(n.params instanceof Map))return;const o=r.dynamicProperty.get(e);if(!c(o))return void n.params.set(E(e),o);const i=r.property.get(e);if(c(i))return;let a=v(t,i);"flex-start"===i?a=t+"Start":"flex-end"===i&&(a=t+"End"),n.params.set(E(e),a)})),N=r(((e,t,r,n)=>{if(!(n.properties instanceof Map))return;const o=r.dynamicProperty.get(e);if(!c(o))return void n.properties.set("justifyContent",o);const i=r.property.get(e);if(c(i))return;let a=v(t,i);"flex-start"===i?a=t+"Start":"flex-end"===i&&(a=t+"End"),n.properties.set("justifyContent",a)})),A=r(((e,t)=>t.type===e));function C(e){return null===e.match(/\$(r|rawfile)\('(.*)'\)$/)?i(e):e}function w(e){let t=v("ItemAlign.",e);return"flex-start"===e?t="ItemAlign.Start":"flex-end"===e&&(t="ItemAlign.End"),t}function b(e){let t=v("ItemAlign.",e);return"flex-start"===e?t="ItemAlign.Start":"flex-end"===e&&(t="ItemAlign.End"),t}function R(e){let t=v("FlexWrap.",e);return"nowrap"===e&&(t="FlexWrap.NoWrap"),t}function O(e){let t=v("VerticalAlign.",e);return"flex-start"===e?t="VerticalAlign.Top":"flex-end"===e&&(t="VerticalAlign.Bottom"),t}function I(e){let t=v("HorizontalAlign.",e);return"flex-start"===e?t="HorizontalAlign.Start":"flex-end"===e&&(t="HorizontalAlign.End"),t}function M(e){return["lighter","normal","regular","medium","bold","bolder"].includes(e)?v("FontWeight.",e):e}function P(e){const t=new Map([["repeat-x","X"],["repeat-y","Y"],["repeat","XY"],["no-repeat","NoRepeat"]]).get(e);if(null!=t&&""!==t)return v("ImageRepeat.",t)}function x(e){return e.startsWith("$r(")?e:`\`\${${e}}\``}t.dealWithSrc=C,t.dealWithAlignSelf=w,t.dealWithFlexAlignItems=b,t.dealWithWrap=R,t.dealWithRowAlignItems=O,t.dealWithColumnAlignItems=I,t.dealWithFontWeight=M,t.dealWithBackgroundImagePosition=function(e){if(new Set(["TopStart","Top","TopEnd","Start","Center","End","BottomStart","Bottom","BottomEnd"]).has(e))return"Alignment."+e;const t=e.match(/^ *((0|[1-9][0-9]*)(px|vp|lpx|%)) +((0|[1-9][0-9]*)(px|vp|lpx|%)) *$/);return null!==t?`{ x: ${i(t[1])}, y: ${i(t[4])} }`:void 0},t.dealWithBackgroundImageSize=function(e){if(new Set(["Cover","Contain","Auto"]).has(e))return v("ImageSize.",e);const t=e.match(/^ *((0|[1-9][0-9]*)(px|vp|lpx|%))( *$| +((0|[1-9][0-9]*)(px|vp|lpx|%)) *$)/);return null!==t?void 0!==t[5]?`{ width: ${i(t[1])}, height: ${i(t[5])} }`:`{ width: ${i(t[1])} }`:void 0},t.dealWithBackgroundRepeat=P,t.getContentName=x;const L=[[n("width"),s("width")],[n("height"),s("height")],[function(e){return e.hasProperty("constraint-size-min-width")||e.hasProperty("constraint-size-max-width")||e.hasProperty("constraint-size-min-height")||e.hasProperty("constraint-size-max-height")},function(e,t){const r=new Map,n=e.getProperty("constraint-size-min-width"),o=e.getProperty("constraint-size-max-width"),i=e.getProperty("constraint-size-min-height"),a=e.getProperty("constraint-size-max-height");S("minWidth",n,r,e.dynamicProperty.has("constraint-size-min-width")),S("maxWidth",o,r,e.dynamicProperty.has("constraint-size-max-width")),S("minHeight",i,r,e.dynamicProperty.has("constraint-size-min-height")),S("maxHeight",a,r,e.dynamicProperty.has("constraint-size-max-height")),r.size>0&&t.properties.set("constraintSize",r)}],[n("align"),p("align","Alignment.")],[n("direction"),p("direction","Direction.")],[function(e){return e.hasProperty("left")||e.hasProperty("top")},function(e,t){const r="absolute"===e.property.get("position")?"position":"offset",n=e.property.get("left"),o=e.property.get("top"),a=e.dynamicProperty.get("left"),s=e.dynamicProperty.get("top");if(c(a)&&c(s)&&c(n)&&c(o))return;const u=new Map([["x",i(null!=n?n:"0")],["y",i(null!=o?o:"0")]]);c(a)||u.set("x",a),c(s)||u.set("y",s),t.properties.set(r,u)}],[n("aspect-ratio"),u("aspect-ratio")],[n("display-priority"),u("display-priority")],[n("flex-basis"),s("flex-basis")],[n("flex-grow"),u("flex-grow")],[n("flex-shrink"),u("flex-shrink")],[n("align-self"),function(e,t){const r=e.dynamicProperty.get("align-self");if(!c(r))return void t.properties.set("alignSelf",r);const n=e.property.get("align-self");if(c(n))return;const o=w(n);t.properties.set("alignSelf",o)}],[n("border-style"),p("border-style","BorderStyle.")],[n("border-width"),s("border-width")],[n("border-color"),m("border-color")],[n("border-radius"),s("border-radius")],[n("background-color"),m("background-color")],[function(e){return e.hasProperty("background-image-src")||e.hasProperty("background-image-repeat")},function(e,t){const r=e.property.get("background-image-src"),n=e.property.get("background-image-repeat"),o=e.dynamicProperty.get("background-image-src"),i=e.dynamicProperty.get("background-image-repeat");if(c(r)&&c(n)&&c(o)&&c(i))return;let a=C(null!=r?r:"");if(c(o)||(a=o),c(i)){if(!c(n)){const e=P(n);null!=e&&""!==e&&(a=a+", "+e)}}else a=a+", "+i;t.properties.set("backgroundImage",a)}],[n("background-image-size"),function(e,t){const r=e.dynamicProperty.get("background-image-size");if(!c(r))return void t.properties.set("backgroundImageSize",r);const n=e.property.get("background-image-size");if(c(n))return;if(new Set(["Cover","Contain","Auto"]).has(n))return void t.properties.set("backgroundImageSize",v("ImageSize.",n));const o=n.match(/^ *((0|[1-9][0-9]*)(px|vp|lpx|%))( *$| +((0|[1-9][0-9]*)(px|vp|lpx|%)) *$)/);null!==o&&(void 0!==o[5]?t.properties.set("backgroundImageSize",new Map([["width",i(o[1])],["height",i(o[5])]])):t.properties.set("backgroundImageSize",new Map([["width",i(o[1])]])))}],[n("background-image-position"),function(e,t){const r=e.dynamicProperty.get("background-image-position");if(!c(r))return void t.properties.set("backgroundImagePosition",r);const n=e.property.get("background-image-position");if(c(n))return;if(new Set(["TopStart","Top","TopEnd","Start","Center","End","BottomStart","Bottom","BottomEnd"]).has(n))return void t.properties.set("backgroundImagePosition","Alignment."+n);const o=n.match(/^ *((0|[1-9][0-9]*)(px|vp|lpx|%)) +((0|[1-9][0-9]*)(px|vp|lpx|%)) *$/);null!==o&&t.properties.set("backgroundImagePosition",new Map([["x",i(o[1])],["y",i(o[4])]]))}],[n("opacity"),u("opacity")],[n("visibility"),p("visibility","Visibility.")],[n("enabled"),l("enabled")],[n("font-color"),m("font-color")],[n("font-size"),s("font-size")],[n("font-style"),p("font-style","FontStyle.")],[n("font-weight"),function(e,t){const r=e.getProperty("font-weight");if(c(r))return;const n=M(r);t.properties.set("fontWeight",n)}],[n("font-family"),s("font-family")],[function(e){return e.hasProperty("margin")||e.hasProperty("margin-left")||e.hasProperty("margin-top")||e.hasProperty("margin-right")||e.hasProperty("margin-bottom")},function(e,t){var r,n,o,i;const a=new Map,s=e.getProperty("margin"),c=null!==(r=e.getProperty("margin-top"))&&void 0!==r?r:s,u=null!==(n=e.getProperty("margin-bottom"))&&void 0!==n?n:s,l=null!==(o=e.getProperty("margin-left"))&&void 0!==o?o:s,p=null!==(i=e.getProperty("margin-right"))&&void 0!==i?i:s,f=e.property.has("margin-top"),d=e.property.has("margin-bottom"),y=e.property.has("margin-left"),h=e.property.has("margin-right"),m=e.dynamicProperty.has("margin"),g=e.dynamicProperty.has("margin-top"),E=e.dynamicProperty.has("margin-bottom"),v=e.dynamicProperty.has("margin-left"),T=e.dynamicProperty.has("margin-right");S("top",c,a,g||!f&&m),S("bottom",u,a,E||!d&&m),S("left",l,a,v||!y&&m),S("right",p,a,T||!h&&m),a.size>0&&t.properties.set("margin",a)}],[function(e){return e.hasProperty("padding")||e.hasProperty("padding-left")||e.hasProperty("padding-top")||e.hasProperty("padding-right")||e.hasProperty("padding-bottom")},function(e,t){var r,n,o,i;const a=new Map,s=e.getProperty("padding"),c=null!==(r=e.getProperty("padding-top"))&&void 0!==r?r:s,u=null!==(n=e.getProperty("padding-bottom"))&&void 0!==n?n:s,l=null!==(o=e.getProperty("padding-left"))&&void 0!==o?o:s,p=null!==(i=e.getProperty("padding-right"))&&void 0!==i?i:s,f=e.property.has("padding-top"),d=e.property.has("padding-bottom"),y=e.property.has("padding-left"),h=e.property.has("padding-right"),m=e.dynamicProperty.has("padding"),g=e.dynamicProperty.has("padding-top"),E=e.dynamicProperty.has("padding-bottom"),v=e.dynamicProperty.has("padding-left"),T=e.dynamicProperty.has("padding-right");S("top",c,a,g||!f&&m),S("bottom",u,a,E||!d&&m),S("left",l,a,v||!y&&m),S("right",p,a,T||!h&&m),a.size>0&&t.properties.set("padding",a)}],[o("button","label"),function(e,t){const r=e.dynamicProperty.get("label");if(!c(r))return void t.setParams(x(r));const n=e.property.get("label");"string"==typeof n&&t.setParams(i(n))}],[o("button","type"),p("type","ButtonType.")],[o("button","state-effect"),l("state-effect")],[o("divider","vertical"),l("vertical")],[o("divider","color"),m("color")],[o("divider","stroke-width"),s("stroke-width")],[o("divider","line-cap"),p("line-cap","LineCapStyle.")],[A("image"),function(e,t){var r;const n=e.dynamicProperty.get("src");if(!c(n))return void t.setParams(n);const o=null!==(r=e.property.get("src"))&&void 0!==r?r:"";t.setParams(C(o))}],[o("image","alt"),s("alt")],[o("image","object-fit"),p("object-fit","ImageFit.")],[o("image","object-repeat"),p("object-repeat","ImageRepeat.")],[o("image","interpolation"),p("interpolation","ImageInterpolation.")],[o("image","render-mode"),p("render-mode","ImageRenderMode.")],[function(e){return e.hasProperty("source-size-width")||e.hasProperty("source-size-height")},function(e,t){let r=e.getProperty("source-size-width"),n=e.getProperty("source-size-height");if(c(r)&&c(n))return;const o=e.dynamicProperty.has("source-size-width"),i=e.dynamicProperty.has("source-size-height");r="0"===r||c(r)?"0":o?r:r.substring(0,r.length-2),n="0"===n||c(n)?"0":i?n:n.substring(0,n.length-2);const a=new Map([["width",r],["height",n]]);t.properties.set("sourceSize",a)}],[function(e){return"progress"===e.type&&(e.hasProperty("value")||e.hasProperty("total")||e.hasProperty("style"))},function(e,t){var r;f("value",e,t)||t.params instanceof Map&&t.params.set("value",null!==(r=e.getProperty("value"))&&void 0!==r?r:"0")}],[o("progress","total"),y("total")],[o("progress","style"),h("style","ProgressStyle.")],[o("progress","color"),m("color")],[o("slider","value"),y("value")],[o("slider","min"),y("min")],[o("slider","max"),y("max")],[o("slider","step"),y("step")],[o("slider","style"),h("style","SliderStyle.")],[o("slider","block-color"),m("block-color")],[o("slider","track-color"),m("track-color")],[o("slider","selected-color"),m("selected-color")],[o("slider","show-steps"),l("show-steps")],[o("slider","show-tips"),l("show-tips")],[o("text","content"),function(e,t){const r=e.property.get("content"),n=e.dynamicProperty.get("content");c(n)?"string"==typeof r&&t.setParams(i(r)):t.setParams(x(n))}],[o("text","text-align"),p("text-align","TextAlign.")],[o("text","text-overflow"),function(e,t){const r=e.dynamicProperty.get("text-overflow");if(!c(r))return void t.properties.set("textOverflow",new Map([["overflow",r]]));const n=e.property.get("text-overflow");c(n)||t.properties.set("textOverflow",new Map([["overflow","TextOverflow."+g(n)]]))}],[o("text","max-lines"),u("max-lines")],[o("text","line-height"),s("line-height")],[function(e){return"text"===e.type&&(e.hasProperty("decoration-type")||e.hasProperty("decoration-color"))},function(e,t){const r=e.property.get("decoration-type"),n=e.dynamicProperty.get("decoration-type"),o=e.property.get("decoration-color"),i=e.dynamicProperty.get("decoration-color");if(c(r)&&c(o)&&c(n)&&c(i))return;const a=new Map;c(n)?a.set("type",c(r)?"TextDecorationType.None":v("TextDecorationType.",r)):a.set("type",n),t.properties.set("decoration",a),c(i)?c(o)||a.set("color",T(o)):a.set("color",i)}],[o("text","baseline-offset"),s("baseline-offset")],[o("text","text-case"),p("text-case","TextCase.")],[o("column","space"),d("space")],[o("column","align-items-column"),function(e,t){const r=e.dynamicProperty.get("align-items-column");if(!c(r))return void t.properties.set("alignItems",r);const n=e.property.get("align-items-column");if(c(n))return;const o=I(n);t.properties.set("alignItems",o)}],[o("column","justify-content-rc"),N("justify-content-rc","FlexAlign.")],[o("row","space"),d("space")],[o("row","align-items-row"),function(e,t){const r=e.dynamicProperty.get("align-items-row");if(!c(r))return void t.properties.set("alignItems",r);const n=e.property.get("align-items-row");if(c(n))return;const o=O(n);t.properties.set("alignItems",o)}],[o("row","justify-content-rc"),N("justify-content-rc","FlexAlign.")],[o("flex","flex-direction"),function(e,t){if(!(t.params instanceof Map))return;const r=e.dynamicProperty.get("flex-direction");if(!c(r))return void t.params.set("direction",r);const n=e.property.get("flex-direction");c(n)||t.params.set("direction",v("FlexDirection.",n))}],[o("flex","wrap"),function(e,t){if(!(t.params instanceof Map))return;const r=e.dynamicProperty.get("wrap");if(!c(r))return void t.params.set("wrap",r);const n=e.property.get("wrap");if(c(n))return;const o=R(n);t.params.set("wrap",o)}],[o("flex","justify-content"),_("justify-content","FlexAlign.")],[o("flex","align-items-flex"),function(e,t){if(!(t.params instanceof Map))return;const r=e.dynamicProperty.get("align-items-flex");if(!c(r))return void t.params.set("alignItems",r);const n=e.property.get("align-items-flex");if(c(n))return;const o=b(n);t.params.set("alignItems",o)}],[o("flex","align-content"),_("align-content","FlexAlign.")],[o("list","space-list"),function(e,t){const r=e.dynamicProperty.get("space-list");if(void 0!==r&&""!==r.trim()&&t.params instanceof Map)return void t.params.set("space",r);const n=e.getProperty("space-list");!c(n)&&t.params instanceof Map&&t.params.set("space",n)}],[o("list","initial-index"),y("initial-index")],[o("list","list-direction"),p("list-direction","Axis.")],[function(e){return"list"===e.type&&(e.hasProperty("divider-stroke-width")||e.hasProperty("divider-color")||e.hasProperty("divider-start-margin")||e.hasProperty("divider-end-margin"))},function(e,t){const r=e.property.get("divider-stroke-width"),n=e.dynamicProperty.get("divider-stroke-width"),o=new Map([["strokeWidth",i(null!=r?r:"0")]]);c(n)||o.set("strokeWidth",n);const a=e.property.get("divider-color"),s=e.dynamicProperty.get("divider-color"),u=e.property.get("divider-start-margin"),l=e.dynamicProperty.get("divider-start-margin"),p=e.property.get("divider-end-margin"),f=e.dynamicProperty.get("divider-end-margin");c(s)?c(a)||o.set("color",T(a)):o.set("color",s),c(l)?c(u)||o.set("startMargin",i(u)):o.set("startMargin",l),c(f)?c(p)||o.set("endMargin",i(p)):o.set("endMargin",f),t.properties.set("divider",o)}],[o("list","edit-mode"),l("edit-mode")],[o("list","edge-effect"),p("edge-effect","EdgeEffect.")],[o("list","chain-animation"),l("chain-animation")],[o("list-item","sticky"),p("sticky","Sticky.")],[o("list-item","editable"),l("editable")],[o("swiper","index"),u("index")],[o("swiper","auto-play"),l("auto-play")],[o("swiper","interval"),u("interval")],[o("swiper","indicator"),l("indicator")],[o("swiper","loop"),l("loop")],[o("swiper","duration"),u("duration")],[o("swiper","vertical"),l("vertical")],[o("swiper","item-space"),s("item-space")],[o("swiper","cached-count"),u("cached-count")],[o("swiper","disable-swipe"),l("disable-swipe")],[o("text-input","placeholder"),d("placeholder")],[o("text-input","textInput-type"),function(e,t){const r=e.dynamicProperty.get("textInput-type");if(!c(r))return void t.properties.set("type",r);const n=e.property.get("textInput-type");c(n)||t.properties.set("type","InputType."+n)}],[o("text-input","placeholderColor"),m("placeholderColor")],[function(e){return"text-input"===e.type&&(e.hasProperty("placeholderFont-size")||e.hasProperty("placeholderFont-weight")||e.hasProperty("placeholderFont-family")||e.hasProperty("placeholderFont-style"))},function(e,t){const r=e.property.get("placeholderFont-size"),n=e.dynamicProperty.get("placeholderFont-size"),o=e.property.get("placeholderFont-weight"),a=e.dynamicProperty.get("placeholderFont-weight"),s=e.property.get("placeholderFont-family"),u=e.dynamicProperty.get("placeholderFont-family"),l=e.property.get("placeholderFont-style"),p=e.dynamicProperty.get("placeholderFont-style"),f=new Map;c(n)?c(r)||f.set("size",parseInt(r)):f.set("size",n),c(a)?c(o)||f.set("weight",isNaN(Number(o))?v("FontWeight.",o):o):f.set("weight",a),c(u)?c(s)||f.set("family",i(s)):f.set("family",u),c(p)?c(l)||f.set("style",v("FontStyle.",l)):f.set("style",p),t.properties.set("placeholderFont",f)}],[o("text-input","enterKeyType"),p("enterKeyType","EnterKeyType.")],[o("text-input","caretColor"),m("caretColor")],[o("text-input","maxLength"),u("maxLength")]]},243:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Style=t.Tag=void 0;const n=r(117);class o extends n.ASTNode{constructor(e,t,r){super(),this.tagName=e,this.attributes=t,this.content=r}}t.Tag=o;class i extends n.ASTNode{constructor(e,t,r,n){super(),this.mediaQuery=void 0,this.kind=e,this.name=t,this.content=r,this.mediaQuery=n}}t.Style=i},573:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ASTNodeGenerator=void 0;const n=r(243),o=r(334);class i{constructor(e){this.cache=e}visit(e){e instanceof n.Tag?this.genTag(e):e instanceof n.Style&&this.genStyle(e)}static getMethodGen(e){return void 0===i.instance?i.instance=new i(e):i.instance.setCache(e),i.instance}setCache(e){this.cache=e}genTag(e){if(this.cache.concat(o.TokenClass.TAG_START,e.tagName),this.cache.indentOff(),e.attributes.forEach(((e,t)=>{let r="";for(const t of e)r+='"'===t?""":"\n"===t?" ":t;this.cache.concat(o.TokenClass.SPACE,t,o.TokenClass.ASSIGN,o.TokenClass.LQUOTE,r,o.TokenClass.RQUOTE)})),null===e.content)this.cache.concat(o.TokenClass.EMPTY_TAG_END);else{if(this.cache.concat(o.TokenClass.TAG_END),"string"==typeof e.content){let t="";for(const r of e.content)t+="<"===r?"<":r;this.cache.concat(t)}else 0!==e.content.length&&(this.cache.concat(o.TokenClass.NEW_LINE),this.cache.indentOn(),this.cache.incIndent(),e.content.forEach((e=>{e.accept(this),this.cache.indentOff(),this.cache.concat(o.TokenClass.NEW_LINE),this.cache.indentOn()})),this.cache.decIndent(),this.cache.indentOn());this.cache.concat(o.TokenClass.END_TAG_START,e.tagName,o.TokenClass.TAG_END)}}genStyle(e){void 0!==e.mediaQuery&&(this.cache.concat("@media"),this.cache.indentOff(),this.cache.concat(o.TokenClass.SPACE,e.mediaQuery,o.TokenClass.SPACE,o.TokenClass.LBRA,o.TokenClass.NEW_LINE),this.cache.indentOn(),this.cache.incIndent()),"IDStyle"===e.kind&&(this.cache.concat(o.TokenClass.ID_STYLE_START),this.cache.indentOff()),this.cache.concat(e.name,o.TokenClass.SPACE,o.TokenClass.LBRA,o.TokenClass.NEW_LINE),this.cache.indentOn(),this.cache.incIndent(),e.content.forEach(((e,t)=>{this.cache.concat(t,o.TokenClass.COLON,o.TokenClass.SPACE,e,o.TokenClass.SEMICOLON,o.TokenClass.NEW_LINE)})),this.cache.decIndent(),this.cache.concat(o.TokenClass.RBRA,o.TokenClass.NEW_LINE),void 0!==e.mediaQuery&&(this.cache.decIndent(),this.cache.concat(o.TokenClass.RBRA,o.TokenClass.NEW_LINE)),this.cache.concat(o.TokenClass.NEW_LINE)}}t.ASTNodeGenerator=i,i.instance=void 0},844:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CSSBridge=t.HMLBridge=void 0;const n=r(243),o=r(571);t.HMLBridge=class{constructor(){this.errors=0}error(e){console.error("Code generating error: "+e),this.errors+=1}getErrorCount(){return this.errors}visit(e){const t=new Map([["id",e.id]]);let r="";for(let[n,i]of e.property)o.isAttribute(n,e.type)?("string"!=typeof i&&(i=JSON.stringify(i)),t.set(n,i)):o.isContent(n)&&(r=i);if(e.children.length>0){r=[];for(const t of e.children)r.push(t.accept(this))}const i=new n.Tag(e.type,t,r);return"wrapper"===t.get("id")?new n.Tag("div",new Map,[i]):i}},t.CSSBridge=class{constructor(){this.errors=0,this.styles=[]}error(e){console.error("Code generating error: "+e),this.errors+=1}getErrorCount(){return this.errors}genIDStyle(e){var t;const r=t=>{const r=new Map;for(const[n,i]of t)o.isStyle(n,e.type)&&r.set(n,i);return r},i=r(e.property);i.size>0&&this.styles.push(new n.Style("IDStyle",e.id,i)),(null!==(t=e.mediaProperty)&&void 0!==t?t:new Map).forEach(((t,o)=>{const i=r(t);i.size>0&&this.styles.push(new n.Style("IDStyle",e.id,i,o))}));for(const t of e.children)t.accept(this)}visit(e){return this.genIDStyle(e),this.styles}}},55:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.genFACSS=t.genFAHML=void 0;const n=r(573),o=r(862);t.genFAHML=function(e){const t=n.ASTNodeGenerator.getMethodGen(new o.Cache(" "));return e.accept(t),t.cache.toString()},t.genFACSS=function(e){const t=n.ASTNodeGenerator.getMethodGen(new o.Cache(" "));return e.forEach((e=>{e.accept(t)})),t.cache.toString()}},571:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isEvent=t.isData=t.isUnknown=t.isContent=t.isAttribute=t.isStyle=t.styleMap=void 0;const n=r(904),o=["width","height","min-width","min-height","max-width","max-height","padding","padding-start","padding-end","padding-top","padding-right","padding-bottom","padding-left","margin","margin-start","margin-end","margin-top","margin-right","margin-bottom","margin-left","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","border-bottom-color","border-bottom-right-radius","border-left-width","border-left-style","border-left-color","border-bottom-left-radius","background-color","background","background-image","background-size","background-position","background-repeat","display","opacity","visibility","flex","flex-grow","flex-shrink","flex-basis","position","display","top","right","bottom","left","display-index","flex-weight","aspect-ratio"],i=["font-size","font-family","font-style","font-weight"],a=["text-align","line-height","text-decoration","letter-spacing","max-lines","text-overflow","allow-scale","min-font-size","max-font-size","font-size-step","prefer-font-sizes","color",...i],s=["allow-scale","text-decoration","color",...i],c=["text-color","allow-scale","icon-width","icon-height","radius",...i],u=["texton-color","textoff-color","text-padding","allow-scale",...i],l=["column-height","text-color","allow-scale","letter-spacing","text-decoration","line-height","opacity",...i],p=["text-color","allow-scale","letter-spacing",...i];t.styleMap=new Map([["common",new Set([...o])],["div",new Set(["flex-direction","overflow","flex-wrap","justify-content","align-items","align-content","grid-template-columns","grid-template-rows","grid-row-start","grid-row-end","grid-column-start","grid-column-end","grid-gap","grid-columns-gap","grid-rows-gap"])],["text",new Set([...a])],["image",new Set(["object-fit","match-text-direction","fit-original-size"])],["span",new Set([...s])],["input",new Set(["font-size","font-family","font-weight","color","placeholder-color","allow-scale"])],["button",new Set([...c])],["switch",new Set([...u])],["refresh",new Set(["progress-color"])],["divider",new Set(["stroke-width","line-cap","color"])],["chart",new Set(["stroke-width","radius","start-angle","total-angle","center-x","center-y","colors","weights"])],["picker",new Set([...l])],["picker-view",new Set(["color","font-size","selected-color","selected-font-size","focus-color","focus-font-size","disappear-color","disappear-font-size","font-family"])],["slider",new Set(["color","selected-color","block-color"])],["swiper",new Set(["indicator-color","indicator-selected-color","indicator-size","indicator-top","indicator-right","indicator-bottom","indicator-left"])],["list",new Set(["flex-direction","columns","item-extent","fade-color"])],["list-item",new Set(["column-span"])],["progress",new Set(["color","stroke-width","background-color","secondary-color","scale-width","scale-number","start-angle","total-angle","center-x","center-y","radius"])],["select",new Set(["font-family"])],["menu",new Set([...p])],["option",new Set(["color","font-family","allow-scale","font-size","font-weight","text-decoration"])],["video",new Set(["object-fit"])],["clock",new Set(["font-family"])]]);const f=new Map([["common",new Set(["id","ref","disabled","focusable","data","if","for"])],["image",new Set(["src","alt"])],["button",new Set(["type","value","icon","waiting"])],["refresh",new Set(["offset","refreshing","type","lasttime","friction"])],["input",new Set(["type","checked","name","value","placeholder","maxlength","enterkeytype","headericon"])],["switch",new Set(["checked","showtext","texton","textoff"])],["option",new Set(["value","selected","icon"])],["chart",new Set(["type","percent","datasets","options"])],["picker",new Set(["type","range","selected","start","end","lunar","lunarSwitch","columns","hours","containSecond","value","vibrate"])],["picker-view",new Set(["type","range","selected","start","end","lunar","lunarSwitch","columns","hours","containSecond","indicatorprefix","indicatorsuffix","vibrate"])],["slider",new Set(["min","max","step","showtips","showsteps","mode","value"])],["divider",new Set(["vertical"])],["list",new Set(["scrollpage","cachedcount","scrollbar","scrolleffect","shapemode","indexer","itemscale","itemcenter","updateeffect","scrollvibrate","initialindex","initialoffset"])],["list-item",new Set(["type","primary","section","sticky","stickyradius","clickeffect"])],["swiper",new Set(["index","autoplay","interval","indicator","digital","indicatordisabled","loop","duration","vertical"])],["progress",new Set(["type","percent","secondarypercent","clockwise"])],["menu",new Set(["target","title","type"])],["clock",new Set(["clockconfig","showdigit","hourswest"])],["badge",new Set(["placement","count","visible","maxcount","config","label"])],["video",new Set(["muted","src","autoplay","poster","controls","loop","starttime","direction","speed"])],["tabs",new Set(["index","vertical"])],["tab-bar",new Set(["mode"])],["tab-content",new Set(["scrollable"])]]),d=new Map([["common",new Set(["ontouchstart","ontouchmove","ontouchcancel","ontouchend","onclick","onlongpress","onfocus","onblur","onkey","onswipe"])],["image",new Set(["oncomplete","onerror"])],["input",new Set(["onchange","onenterkeyclick"])],["select",new Set(["onchange"])],["refresh",new Set(["onrefresh","onpulldown"])],["swiper",new Set(["onchange","onrotation"])],["list",new Set(["onindexerchange","onscroll","onscrollbottom","onscrolltop","onscrollend","onscrolltouchup","onrequestitem"])],["list-item",new Set(["onsticky"])],["menu",new Set(["onselected","oncancel"])],["picker",new Set(["oncolumnchange","onchange","oncancel"])],["picker-view",new Set(["oncolumnchange","onchange"])],["video",new Set(["onprepared","onstart","onpause","onfinish","onerror","onseeking","onseeked","ontimeupdate","onfullscreenchange","onstop"])],["tabs",new Set(["onchange"])],["switch",new Set(["onchange"])],["dialog",new Set(["oncancel"])]]),y=new Map([["common",new Set(["onClick","onTouch","onAppear","onDisappear","onKeyEvent","onAreaChange"])],["image",new Set(["onComplete","onError","onFinish"])],["swiper",new Set(["onChange"])],["list",new Set(["onItemDelete","onScrollIndex","onItemDragEnter","onItemDragMove","onItemDragLeave","onItemDragStart","onItemDrop"])],["text-input",new Set(["onChange","onSubmit","onEditChanged"])]]);function h(e,t,r){const n=t.get(r);return void 0!==n&&n.has(e)}function m(e,r){return h(e,t.styleMap,"common")||h(e,t.styleMap,r)}function g(e,t){return n.getDomain()===n.Domain.ETS?h(e,y,"common")||h(e,y,t):E(e,t)||v(e,t)}function E(e,t){return h(e,f,"common")||h(e,f,t)}function v(e,t){return h(e,d,"common")||h(e,d,t)}t.isStyle=m,t.isAttribute=g,t.isContent=function(e){return"content"===e},t.isUnknown=function(e,t){return!m(e,t)&&!g(e,t)},t.isData=E,t.isEvent=v},334:(e,t)=>{"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),t.TokenClass=void 0,(r=t.TokenClass||(t.TokenClass={}))[r.IDENTIFIER=0]="IDENTIFIER",r[r.STRING_LITERAL=1]="STRING_LITERAL",r[r.NUMBER=2]="NUMBER",r[r.CHARACTER=3]="CHARACTER",r[r.EOF=4]="EOF",r[r.INVALID=5]="INVALID",r.EMPTY_DATA="empty",r.ASSIGN="=",r.NEW_LINE="\n",r.CARRIAGE_RETURN="\r",r.INDENT=" ",r.SPACE=" ",r.LQUOTE='"',r.RQUOTE='"',r.TAG_START="<",r.TAG_END=">",r.EMPTY_TAG_END="/>",r.END_TAG_START="{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.etsPropertyList=void 0;const n=r(958),o=r(513),i=["vp","px","%","lpx"],a=[{propertySector:o.Sector.FEATURE,propertySet:{name:"FontSize",property:"font-size-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.COMB_R_LENGTH,units:["fp","px","lpx"]}},{propertySector:o.Sector.FEATURE,propertySet:{name:"FontStyle",property:"font-style-visual",type:o.TypeName.SELECT,etsType:o.EtsType.FONT_STYLE,list:[o.CLEAN_VALUE_NODE,{name:"Normal",value:"normal"},{name:"Italic",value:"italic"}],defaults:"normal"}},{propertySector:o.Sector.FEATURE,propertySet:{name:"FontColor",property:"font-color-visual",type:o.TypeName.COLOR,etsType:o.EtsType.COMB_COLOR}},{propertySector:o.Sector.FEATURE,propertySet:{name:"FontWeight",property:"font-weight-visual",type:o.TypeName.SELECT,etsType:`${o.EtsType.FONT_WEIGHT}|${o.EtsType.NUMBER}`,list:[o.CLEAN_VALUE_NODE,{name:"Normal",value:"normal"},{name:"Lighter",value:"lighter"},{name:"Regular",value:"regular"},{name:"Medium",value:"medium"},{name:"Bold",value:"bold"},{name:"Bolder",value:"bolder"},{value:"100"},{value:"200"},{value:"300"},{value:"400"},{value:"500"},{value:"600"},{value:"700"},{value:"800"},{value:"900"}],defaults:"normal"}},{propertySector:o.Sector.FEATURE,propertySet:{name:"TextAlign",property:"text-align-visual",type:o.TypeName.SELECT,etsType:o.EtsType.TEXT_ALIGN,list:[o.CLEAN_VALUE_NODE,{name:"Start",value:"start"},{name:"Center",value:"center"},{name:"End",value:"end"}],defaults:"start"}},{propertySector:o.Sector.FEATURE,propertySet:{name:"LineHeight",property:"line-height-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.COMB_R_LENGTH,units:["fp","px","lpx"]}},{propertySector:o.Sector.FEATURE,propertySet:{name:"TextOverflow",property:"text-overflow-visual",type:o.TypeName.SELECT,etsType:o.EtsType.TEXT_OVERFLOW,list:[o.CLEAN_VALUE_NODE,{name:"Clip",value:"clip"},{name:"Ellipsis",value:"ellipsis"},{name:"None",value:"none"}],defaults:"clip"}},{propertySector:o.Sector.FEATURE,propertySet:{name:"BaselineOffset",property:"baseline-offset-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.COMB_R_LENGTH,units:["fp","px","lpx"]}},{propertySector:o.Sector.FEATURE,propertySet:{name:"DecorationType",property:"decoration-type-visual",type:o.TypeName.SELECT,etsType:o.EtsType.TEXT_DECORATION_TYPE,list:[o.CLEAN_VALUE_NODE,{name:"Underline",value:"underline"},{name:"LineThrough",value:"line-through"},{name:"Overline",value:"overline"},{name:"None",value:"none"}],defaults:"none"}},{propertySector:o.Sector.FEATURE,propertySet:{name:"DecorationColor",property:"decoration-color-visual",type:o.TypeName.COLOR,etsType:o.EtsType.COMB_COLOR}},{propertySector:o.Sector.FEATURE,propertySet:{name:"TextCase",property:"text-case-visual",type:o.TypeName.SELECT,etsType:o.EtsType.TEXT_CASE,list:[o.CLEAN_VALUE_NODE,{value:"Normal"},{value:"LowerCase"},{value:"UpperCase"}],defaults:"Normal"}},{propertySector:o.Sector.GENERAL,propertySet:{name:"ForEach",property:"for-visual",type:o.TypeName.BASE,etsType:o.EtsType.ARRAY,supportStaticProperty:!1,defaults:""}},{propertySector:o.Sector.GENERAL,propertySet:{name:"KeyGenerator",property:"keyGenerator-visual",type:o.TypeName.BASE,etsType:"Event",supportStaticProperty:!1,defaults:""}},{propertySector:o.Sector.GENERAL,propertySet:{name:"Item",property:"item-visual",type:o.TypeName.BASE,supportDynamicProperty:!1,info:"Variable Name for Item of ForEach Array"}},{propertySector:o.Sector.GENERAL,propertySet:{name:"Idx",property:"idx-visual",type:o.TypeName.BASE,supportDynamicProperty:!1,info:"Variable Name for Index of Corresponding Item In ForEach Array"}}],s=[{propertySector:o.Sector.FEATURE,propertySet:{name:"Placeholder",property:"placeholder-visual",type:o.TypeName.BASE,etsType:o.EtsType.COMB_CONTENT,defaults:""}},{propertySector:o.Sector.FEATURE,propertySet:{name:"Type",property:"textInput-type-visual",type:o.TypeName.SELECT,etsType:o.EtsType.INPUT_TYPE,list:[o.CLEAN_VALUE_NODE,{value:"Normal"},{value:"Password"},{value:"Email"},{value:"Number"}],defaults:"Normal"}},{propertySector:o.Sector.FEATURE,propertySet:{name:"PlaceholderColor",property:"placeholderColor-visual",type:o.TypeName.COLOR,etsType:o.EtsType.COMB_COLOR}},{propertySector:o.Sector.FEATURE,propertySet:{name:"PlaceholderFontSize",property:"placeholderFont-size-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.COMB_LENGTH,units:["fp"]}},{propertySector:o.Sector.FEATURE,propertySet:{name:"PlaceholderFontWeight",property:"placeholderFont-weight-visual",type:o.TypeName.SELECT,etsType:`${o.EtsType.FONT_WEIGHT}|${o.EtsType.NUMBER}`,list:[o.CLEAN_VALUE_NODE,{value:"Normal"},{value:"Lighter"},{value:"Regular"},{value:"Medium"},{value:"Bold"},{value:"Bolder"},{value:"100"},{value:"200"},{value:"300"},{value:"400"},{value:"500"},{value:"600"},{value:"700"},{value:"800"},{value:"900"}],defaults:"400"}},{propertySector:o.Sector.FEATURE,propertySet:{name:"PlaceholderFontFamily",property:"placeholderFont-family-visual",type:o.TypeName.BASE,etsType:o.EtsType.COMB_CONTENT,defaults:""}},{propertySector:o.Sector.FEATURE,propertySet:{name:"PlaceholderFontStyle",property:"placeholderFont-style-visual",type:o.TypeName.SELECT,etsType:o.EtsType.FONT_STYLE,list:[o.CLEAN_VALUE_NODE,{value:"Normal"},{value:"Italic"}],defaults:"Normal"}},{propertySector:o.Sector.FEATURE,propertySet:{name:"EnterKeyType",property:"enterKeyType-visual",type:o.TypeName.SELECT,etsType:o.EtsType.ENTER_KEY_TYPE,list:[o.CLEAN_VALUE_NODE,{value:"Go"},{value:"Search"},{value:"Send"},{value:"Next"},{value:"Done"}],defaults:"Done"}},{propertySector:o.Sector.FEATURE,propertySet:{name:"CaretColor",property:"caretColor-visual",type:o.TypeName.COLOR,etsType:o.EtsType.COMB_COLOR}},{propertySector:o.Sector.FEATURE,propertySet:{name:"MaxLength",property:"maxLength-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.NUMBER}}],c={type:o.TypeName.INTEGER,etsType:o.EtsType.COMB_R_LENGTH,units:["vp","px","lpx"],placeholder:"0"},u=[{propertySector:o.Sector.GENERAL,propertySet:{name:"Width",property:"width-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.COMB_R_LENGTH,units:i}},{propertySector:o.Sector.GENERAL,propertySet:{name:"Height",property:"height-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.COMB_R_LENGTH,units:i}},{propertySector:o.Sector.GENERAL,propertySet:{name:"MinWidth",property:"constraint-size-min-width-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.COMB_R_LENGTH,units:i}},{propertySector:o.Sector.GENERAL,propertySet:{name:"MinHeight",property:"constraint-size-min-height-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.COMB_R_LENGTH,units:i}},{propertySector:o.Sector.GENERAL,propertySet:{name:"MaxWidth",property:"constraint-size-max-width-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.COMB_R_LENGTH,units:i}},{propertySector:o.Sector.GENERAL,propertySet:{name:"MaxHeight",property:"constraint-size-max-height-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.COMB_R_LENGTH,units:i}},{propertySector:o.Sector.DIMENSION,propertySet:Object.assign({name:"Margin",property:"margin-visual"},c)},{propertySector:o.Sector.DIMENSION,propertySet:Object.assign({name:"Padding",property:"padding-visual"},c)},{propertySector:o.Sector.DIMENSION,propertySet:Object.assign({name:"MarginTop",property:"margin-top-visual"},c)},{propertySector:o.Sector.DIMENSION,propertySet:Object.assign({name:"MarginRight",property:"margin-right-visual"},c)},{propertySector:o.Sector.DIMENSION,propertySet:Object.assign({name:"MarginBottom",property:"margin-bottom-visual"},c)},{propertySector:o.Sector.DIMENSION,propertySet:Object.assign({name:"MarginLeft",property:"margin-left-visual"},c)},{propertySector:o.Sector.DIMENSION,propertySet:Object.assign({name:"PaddingTop",property:"padding-top-visual"},c)},{propertySector:o.Sector.DIMENSION,propertySet:Object.assign({name:"PaddingRight",property:"padding-right-visual"},c)},{propertySector:o.Sector.DIMENSION,propertySet:Object.assign({name:"PaddingBottom",property:"padding-bottom-visual"},c)},{propertySector:o.Sector.DIMENSION,propertySet:Object.assign({name:"PaddingLeft",property:"padding-left-visual"},c)}],l={type:o.TypeName.INTEGER,etsType:o.EtsType.COMB_R_LENGTH,units:i},p={type:o.TypeName.INTEGER,etsType:o.EtsType.COMB_R_LENGTH,units:i},f=[{propertySector:o.Sector.DIMENSION,propertySet:{name:"Border",property:"border-visual",type:o.TypeName.COMPOSITE,detached:1,properties:[Object.assign({name:"Width",property:"border-width-visual"},l),Object.assign({name:"Style",property:"border-style-visual"},o.commonParamsForBorder),{name:"Color",property:"border-color-visual",type:o.TypeName.COLOR,etsType:o.EtsType.COMB_COLOR},Object.assign({name:"Radius",property:"border-radius-visual"},p)]}}],d=[{propertySector:o.Sector.FEATURE,propertySet:Object.assign({name:"Vertical",property:"vertical-visual"},o.commonParamsForJudge)},{propertySector:o.Sector.FEATURE,propertySet:{name:"LineCap",property:"line-cap-visual",type:o.TypeName.SELECT,etsType:o.EtsType.LINE_CAP_STYLE,defaults:"butt",list:[o.CLEAN_VALUE_NODE,{name:"Butt",value:"butt"},{name:"Round",value:"round"},{name:"Square",value:"square"}]}},{propertySector:o.Sector.FEATURE,propertySet:{name:"StrokeWidth",property:"stroke-width-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.COMB_LENGTH,units:i}}],y=[{propertySector:o.Sector.FEATURE,propertySet:{name:"InitialIndex",property:"initial-index-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.NUMBER}},{propertySector:o.Sector.FEATURE,propertySet:{name:"ListDirection",property:"list-direction-visual",type:o.TypeName.SELECT,etsType:o.EtsType.AXIS,list:[o.CLEAN_VALUE_NODE,{name:"Vertical",value:"vertical"},{name:"Horizontal",value:"horizontal"}],defaults:"vertical"}},{propertySector:o.Sector.FEATURE,propertySet:{name:"Color",property:"divider-color-visual",type:o.TypeName.COLOR,etsType:o.EtsType.COMB_COLOR}},{propertySector:o.Sector.FEATURE,propertySet:{name:"StrokeWidth",property:"divider-stroke-width-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.COMB_LENGTH,units:i}},{propertySector:o.Sector.FEATURE,propertySet:{name:"StartMargin",property:"divider-start-margin-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.COMB_R_LENGTH,units:i}},{propertySector:o.Sector.FEATURE,propertySet:{name:"EndMargin",property:"divider-end-margin-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.COMB_R_LENGTH,units:i}},{propertySector:o.Sector.FEATURE,propertySet:{name:"EditMode",property:"edit-mode-visual",type:o.TypeName.SELECT,etsType:o.EtsType.BOOLEAN,list:[o.CLEAN_VALUE_NODE,{name:"true",value:"true"},{name:"false",value:"false"}],defaults:"false"}},{propertySector:o.Sector.FEATURE,propertySet:{name:"EdgeEffect",property:"edge-effect-visual",type:o.TypeName.SELECT,etsType:o.EtsType.EDGE_EFFECT,list:[o.CLEAN_VALUE_NODE,{name:"Spring",value:"spring"},{name:"None",value:"none"}],defaults:"spring"}},{propertySector:o.Sector.FEATURE,propertySet:{name:"ChainAnimation",property:"chain-animation-visual",type:o.TypeName.SELECT,etsType:o.EtsType.BOOLEAN,list:[o.CLEAN_VALUE_NODE,{name:"true",value:"true"},{name:"false",value:"false"}],defaults:"false"}}],h=[{propertySector:o.Sector.FEATURE,propertySet:{name:"Sticky",property:"sticky-visual",type:o.TypeName.SELECT,etsType:o.EtsType.STICKY,list:[o.CLEAN_VALUE_NODE,{name:"None",value:"none"},{name:"Normal",value:"normal"}],defaults:"none"}},{propertySector:o.Sector.FEATURE,propertySet:{name:"Editable",property:"editable-visual",type:o.TypeName.SELECT,etsType:o.EtsType.BOOLEAN,list:[o.CLEAN_VALUE_NODE,{name:"true",value:"true"},{name:"false",value:"false"}],defaults:"false"}}],m=[{propertySector:o.Sector.GENERAL,propertySet:{name:"BackgroundImageSrc",property:"background-image-src-visual",type:o.TypeName.BASE,etsType:o.EtsType.STRING}},{propertySector:o.Sector.GENERAL,propertySet:{name:"BackgroundImageRepeat",property:"background-image-repeat-visual",type:o.TypeName.SELECT,etsType:o.EtsType.IMAGE_REPERT,list:[o.CLEAN_VALUE_NODE,{name:"X",value:"repeat-x"},{name:"Y",value:"repeat-y"},{name:"XY",value:"repeat"},{name:"NoRepeat",value:"no-repeat"}]}},{propertySector:o.Sector.GENERAL,propertySet:{name:"BackgroundImageSize",property:"background-image-size-visual",type:o.TypeName.DATA_SELECT_INPUT,etsType:`${o.EtsType.IMAGE_SIZE}|${o.EtsType.STRING}`,list:[o.CLEAN_VALUE_NODE,{name:"Cover",value:"cover"},{name:"Contain",value:"contain"},{name:"Auto",value:"auto"}],defaults:"Auto"}},{propertySector:o.Sector.GENERAL,propertySet:{name:"BackgroundImagePosition",property:"background-image-position-visual",type:o.TypeName.DATA_SELECT_INPUT,etsType:`${o.EtsType.ALIGNMENT}|${o.EtsType.STRING}`,list:[o.CLEAN_VALUE_NODE,{name:"TopStart",value:"top left"},{name:"Top",value:"top center"},{name:"TopEnd",value:"top right"},{name:"Start",value:"center left"},{name:"Center",value:"center center"},{name:"End",value:"center right"},{name:"BottomStart",value:"bottom left"},{name:"Bottom",value:"bottom center"},{name:"BottomEnd",value:"bottom right"}],defaults:"0 0"}}],g=[{propertySector:o.Sector.GENERAL,propertySet:{name:"Location",property:"position-visual",type:o.TypeName.SELECT,defaults:"offset",supportDynamicProperty:!1,list:[o.CLEAN_VALUE_NODE,{name:"offset",value:"relative"},{name:"position",value:"absolute"}]}},{propertySector:o.Sector.GENERAL,propertySet:{name:"X",property:"left-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.COMB_R_LENGTH,defaults:0,units:["vp","px","lpx"]}},{propertySector:o.Sector.GENERAL,propertySet:{name:"Y",property:"top-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.COMB_R_LENGTH,defaults:0,units:["vp","px","lpx"]}}],E=[{propertySector:o.Sector.FLEX,propertySet:{name:"FlexBasis",property:"flex-basis-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.COMB_LENGTH,units:i,defaults:"auto",fixedValues:["auto"],info:"The initial main size of a flex item. It sets the size of the content box otherwise set with box-sizing."}},{propertySector:o.Sector.FLEX,propertySet:{name:"AlignSelf",property:"align-self-visual",type:o.TypeName.SELECT,etsType:o.EtsType.ITEM_ALIGN,defaults:"auto",list:[o.CLEAN_VALUE_NODE,{name:"Auto",value:"auto"},{name:"Start",value:"flex-start"},{name:"Center",value:"center"},{name:"End",value:"flex-end"},{name:"Stretch",value:"stretch"},{name:"Baseline",value:"baseline"}],info:"The alignment of items on the Cross Axis."}},{propertySector:o.Sector.FLEX,propertySet:{name:"Direction",property:"flex-direction-visual",type:o.TypeName.SELECT,etsType:o.EtsType.FLEX_DIRECTION,defaults:"row",list:[o.CLEAN_VALUE_NODE,{name:"Row",value:"row"},{name:"RowReverse",value:"row-reverse"},{name:"Column",value:"column"},{name:"ColumnReverse",value:"column-reverse"}],info:"The direction of flex."}},{propertySector:o.Sector.FLEX,propertySet:{name:"Wrap",property:"wrap-visual",type:o.TypeName.SELECT,etsType:o.EtsType.FLEX_WRAP,defaults:"nowrap",list:[o.CLEAN_VALUE_NODE,{name:"NoWrap",value:"nowrap"},{name:"Wrap",value:"wrap"},{name:"WrapReverse",value:"wrap-reverse"}],info:"Whether flex items are forced onto one line or multiple lines."}},{propertySector:o.Sector.FLEX,propertySet:{name:"JustifyContent",property:"justify-content-visual",type:o.TypeName.SELECT,etsType:o.EtsType.FLEX_ALIGN,defaults:"flex-start",list:[o.CLEAN_VALUE_NODE,{name:"Start",value:"flex-start"},{name:"Center",value:"center"},{name:"End",value:"flex-end"},{name:"SpaceBetween",value:"space-between"},{name:"SpaceAround",value:"space-around"},{name:"SpaceEvenly",value:"space-evenly"}],info:"Allocate the space between and around the elements along the main axis of the flexible container"}},{propertySector:o.Sector.FEATURE,propertySet:{name:"JustifyContent",property:"justify-content-rc-visual",type:o.TypeName.SELECT,etsType:o.EtsType.FLEX_ALIGN,defaults:"flex-start",list:[o.CLEAN_VALUE_NODE,{name:"Start",value:"flex-start"},{name:"Center",value:"center"},{name:"End",value:"flex-end"},{name:"SpaceBetween",value:"space-between"},{name:"SpaceAround",value:"space-around"},{name:"SpaceEvenly",value:"space-evenly"}],info:"Allocate the space between and around the elements along the main axis of the flexible container"}},{propertySector:o.Sector.FLEX,propertySet:{name:"AlignItems",property:"align-items-flex-visual",type:o.TypeName.SELECT,etsType:o.EtsType.ITEM_ALIGN,defaults:"stretch",list:[o.CLEAN_VALUE_NODE,{name:"Auto",value:"auto"},{name:"Start",value:"flex-start"},{name:"Center",value:"center"},{name:"End",value:"flex-end"},{name:"Stretch",value:"stretch"},{name:"Baseline",value:"baseline"}],info:"The alignment of items on the Cross Axis."}},{propertySector:o.Sector.FLEX,propertySet:{name:"AlignContent",property:"align-content-visual",type:o.TypeName.SELECT,etsType:o.EtsType.FLEX_ALIGN,defaults:"flex-start",list:[o.CLEAN_VALUE_NODE,{name:"Start",value:"flex-start"},{name:"Center",value:"center"},{name:"End",value:"flex-end"},{name:"SpaceBetween",value:"space-between"},{name:"SpaceAround",value:"space-around"},{name:"SpaceEvenly",value:"space-evenly"}],info:"Set the distribution of space between and around content items along a flexbox's cross-axis or a grid's block axis."}}],v=[{propertySector:o.Sector.FEATURE,propertySet:Object.assign({name:"AutoPlay",property:"auto-play-visual"},o.commonParamsForJudge)},{propertySector:o.Sector.FEATURE,propertySet:{name:"Interval",property:"interval-visual",type:o.TypeName.BASE,etsType:o.EtsType.NUMBER,defaults:3e3}},{propertySector:o.Sector.FEATURE,propertySet:Object.assign(Object.assign({name:"Loop",property:"loop-visual"},o.commonParamsForJudge),{defaults:!0})},{propertySector:o.Sector.FEATURE,propertySet:{name:"Duration",property:"duration-visual",type:o.TypeName.BASE,etsType:o.EtsType.NUMBER,defaults:400}},{propertySector:o.Sector.FEATURE,propertySet:{name:"ItemSpace",property:"item-space-visual",type:o.TypeName.BASE,etsType:o.EtsType.COMB_LENGTH,defaults:"0"}},{propertySector:o.Sector.FEATURE,propertySet:{name:"CachedCount",property:"cached-count-visual",type:o.TypeName.BASE,etsType:o.EtsType.NUMBER,defaults:1}},{propertySector:o.Sector.FEATURE,propertySet:Object.assign({name:"DisableSwipe",property:"disable-swipe-visual"},o.commonParamsForJudge)},{propertySector:o.Sector.FEATURE,propertySet:{name:"Index",property:"index-visual",type:o.TypeName.BASE,etsType:o.EtsType.NUMBER,defaults:0}},{propertySector:o.Sector.FEATURE,propertySet:Object.assign(Object.assign({name:"Indicator",property:"indicator-visual"},o.commonParamsForJudge),{defaults:!0})}];t.etsPropertyList=[...f,...u,...a,...s,...d,...g,...y,...h,...E,...v,...n.commonPropertyList,...m,{propertySector:o.Sector.ATOMIC,propertySet:{name:"DisplayPriority",property:"display-priority-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.NUMBER}},{propertySector:o.Sector.GENERAL,propertySet:{name:"Visibility",property:"visibility-visual",type:o.TypeName.SELECT,etsType:o.EtsType.VISIBILITY,defaults:"visible",list:[o.CLEAN_VALUE_NODE,{name:"Visible",value:"visible"},{name:"Hidden",value:"hidden"},{name:"None",value:"none"}]}},{propertySector:o.Sector.GENERAL,propertySet:{name:"Enabled",property:"enabled-visual",type:o.TypeName.SELECT,etsType:o.EtsType.BOOLEAN,defaults:"true",list:[{value:"true"},{value:"false"}]}},{propertySector:o.Sector.GENERAL,propertySet:{name:"Align",property:"align-visual",type:o.TypeName.SELECT,etsType:o.EtsType.ALIGNMENT,defaults:"center",list:[o.CLEAN_VALUE_NODE,{name:"TopStart",value:"top-start"},{name:"Top",value:"top"},{name:"TopEnd",value:"top-end"},{name:"Start",value:"start"},{name:"Center",value:"center"},{name:"End",value:"end"},{name:"BottomStart",value:"bottom-start"},{name:"Bottom",value:"bottom"},{name:"BottomEnd",value:"bottom-end"}]}},{propertySector:o.Sector.GENERAL,propertySet:{name:"If",property:"if-visual",type:o.TypeName.SELECT,etsType:o.EtsType.BOOLEAN,defaults:"",list:[{name:"true",value:"true"},{name:"false",value:"false"}]}},{propertySector:o.Sector.FEATURE,propertySet:{name:"Space",property:"space-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.COMB_LENGTH,units:["vp","px","lpx"],requires:{"display-visual":["flex","cleanValue"]},info:"Space between any two adjacent child components."}},{propertySector:o.Sector.FEATURE,propertySet:{name:"Space",property:"space-list-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.NUMBER,requires:{"display-visual":["flex","cleanValue"]},info:"Space between any two adjacent child components."}},{propertySector:o.Sector.FEATURE,propertySet:{name:"AlignItems",property:"align-items-row-visual",type:o.TypeName.SELECT,etsType:o.EtsType.VERTICAL_ALIGN,defaults:"center",requires:{"display-visual":["flex","cleanValue"]},list:[o.CLEAN_VALUE_NODE,{value:"flex-start",name:"top",etsEnumValue:"Top"},{value:"flex-end",name:"bottom",etsEnumValue:"Bottom"},{value:"center",name:"center",etsEnumValue:"Center"}],info:"Alignment mode of child components in the vertical direction."}},{propertySector:o.Sector.FEATURE,propertySet:{name:"AlignItems",property:"align-items-column-visual",type:o.TypeName.SELECT,etsType:o.EtsType.HORIZONTAL_ALIGN,defaults:"center",requires:{"display-visual":["flex","cleanValue"]},list:[o.CLEAN_VALUE_NODE,{value:"flex-start",name:"start",etsEnumValue:"Start"},{value:"flex-end",name:"end",etsEnumValue:"End"},{value:"center",name:"center",etsEnumValue:"Center"}],info:"Alignment mode of child components in the horizontal direction."}},{propertySector:o.Sector.FEATURE,propertySet:{name:"Src",property:"src-visual",type:o.TypeName.BASE,etsType:o.EtsType.COMB_SRC}},{propertySector:o.Sector.FEATURE,propertySet:{name:"Alt",property:"alt-visual",type:o.TypeName.BASE,etsType:o.EtsType.COMB_CONTENT}},{propertySector:o.Sector.FEATURE,propertySet:{name:"RenderMode",property:"render-mode-visual",type:o.TypeName.SELECT,etsType:o.EtsType.IMAGE_RENDER_MODE,defaults:"original",list:[o.CLEAN_VALUE_NODE,{name:"Original",value:"original"},{name:"Template",value:"template"}]}},{propertySector:o.Sector.FEATURE,propertySet:{name:"ObjectRepeat",property:"object-repeat-visual",type:o.TypeName.SELECT,etsType:o.EtsType.IMAGE_REPERT,defaults:"no-repeat",list:[o.CLEAN_VALUE_NODE,{name:"X",value:"X"},{name:"Y",value:"Y"},{name:"XY",value:"XY"},{name:"NoRepeat",value:"no-repeat"}]}},{propertySector:o.Sector.FEATURE,propertySet:{name:"ObjectFit",property:"object-fit-visual",type:o.TypeName.SELECT,etsType:o.EtsType.IMAGE_FIT,defaults:"cover",list:[o.CLEAN_VALUE_NODE,{name:"Cover",value:"cover"},{name:"Contain",value:"contain"},{name:"Fill",value:"fill"},{name:"None",value:"none"},{name:"ScaleDown",value:"scale-down"}]}},{propertySector:o.Sector.FEATURE,propertySet:{name:"InterPolation",property:"interpolation-visual",type:o.TypeName.SELECT,etsType:o.EtsType.IMAGE_INTERPOLATION,defaults:"none",list:[o.CLEAN_VALUE_NODE,{name:"None",value:"none"},{name:"High",value:"high"},{name:"Medium",value:"medium"},{name:"Low",value:"low"}]}},{propertySector:o.Sector.FEATURE,propertySet:{name:"SourceSizeWidth",property:"source-size-width-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.NUMBER,units:["px"]}},{propertySector:o.Sector.FEATURE,propertySet:{name:"SourceSizeHeight",property:"source-size-height-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.NUMBER,units:["px"]}},{propertySector:o.Sector.FEATURE,propertySet:{name:"Type",property:"type-visual",type:o.TypeName.SELECT,etsType:o.EtsType.BUTTON_TYPE,defaults:"capsule",list:[{name:"Normal",value:"normal"},{name:"Capsule",value:"capsule"},{name:"Circle",value:"circle"}]}},{propertySector:o.Sector.FEATURE,propertySet:{name:"StateEffect",property:"state-effect-visual",type:o.TypeName.SELECT,etsType:o.EtsType.BOOLEAN,defaults:"true",list:[{name:"true",value:"true"},{name:"false",value:"false"}]}},{propertySector:o.Sector.FEATURE,propertySet:{name:"Content",property:"content-visual",type:o.TypeName.ADJUSTABLE,etsType:o.EtsType.COMB_CONTENT}},{propertySector:o.Sector.FEATURE,propertySet:{name:"Label",property:"label-visual",type:o.TypeName.ADJUSTABLE,etsType:o.EtsType.COMB_CONTENT}}]},958:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.commonPropertyList=void 0;const n=r(513);t.commonPropertyList=[{propertySector:n.Sector.GENERAL,propertySet:{name:"BackgroundColor",property:"background-color-visual",type:n.TypeName.COLOR,etsType:n.EtsType.COMB_COLOR}},{propertySector:n.Sector.GENERAL,propertySet:{name:"Display",property:"display-visual",type:n.TypeName.SELECT,defaults:"flex",list:[n.CLEAN_VALUE_NODE,{value:"flex"},{value:"none"}]}},{propertySector:n.Sector.GENERAL,propertySet:{name:"Opacity",property:"opacity-visual",type:n.TypeName.SLIDER,etsType:n.EtsType.COMB_R_NUMBER,defaults:"1",step:.01,max:1,min:0}},{propertySector:n.Sector.GENERAL,propertySet:{name:"Overflow",property:"overflow-visual",type:n.TypeName.SELECT,defaults:"visible",list:[n.CLEAN_VALUE_NODE,{value:"visible"},{value:"hidden"},{value:"scroll"}]}},{propertySector:n.Sector.FLEX,propertySet:{name:"FlexGrow",property:"flex-grow-visual",type:n.TypeName.INTEGER,etsType:n.EtsType.NUMBER,defaults:"0",requiresParent:{display:["flex","cleanValue"]},info:"The flex grow factor of a flex item's main size"}},{propertySector:n.Sector.FLEX,propertySet:{name:"FlexShrink",property:"flex-shrink-visual",type:n.TypeName.INTEGER,etsType:n.EtsType.NUMBER,defaults:"1",requiresParent:{display:["flex","cleanValue"]},info:"The flex shrink factor of a flex item. If the size of all flex items is larger than the flex container, items will shrink"}},{propertySector:n.Sector.FLEX,propertySet:{name:"Columns",property:"columns-visual",type:n.TypeName.INTEGER,etsType:n.EtsType.NUMBER,defaults:1,info:"The column number of flex."}},{propertySector:n.Sector.GENERAL,propertySet:{name:"Header Logo",property:"headerLogo-visual",type:n.TypeName.BASE,defaults:""}},{propertySector:n.Sector.GENERAL,propertySet:{name:"Title",property:"title-visual",type:n.TypeName.BASE,defaults:""}},{propertySector:n.Sector.GENERAL,propertySet:{name:"Status",property:"status-visual",type:n.TypeName.BASE,defaults:""}},{propertySector:n.Sector.GENERAL,propertySet:{name:"Logo",property:"logo-visual",type:n.TypeName.BASE,defaults:""}},{propertySector:n.Sector.FEATURE,propertySet:{name:"Color",property:"color-visual",type:n.TypeName.COLOR,etsType:n.EtsType.COMB_COLOR}},{propertySector:n.Sector.FEATURE,propertySet:{name:"FontFamily",property:"font-family-visual",type:n.TypeName.BASE,etsType:n.EtsType.COMB_CONTENT,defaults:"sans-serif"}},{propertySector:n.Sector.FEATURE,propertySet:{name:"MaxLines",property:"max-lines-visual",type:n.TypeName.INTEGER,etsType:n.EtsType.NUMBER}},{propertySector:n.Sector.FEATURE,propertySet:{name:"TextColor",property:"text-color-visual",type:n.TypeName.COLOR,defaults:"rgba(0,0,0,0.9)"}},{propertySector:n.Sector.FEATURE,propertySet:{name:"FocusColor",property:"focus-color-visual",type:n.TypeName.COLOR}},{propertySector:n.Sector.FEATURE,propertySet:{name:"DisappearColor",property:"disappear-color-visual",type:n.TypeName.COLOR}},{propertySector:n.Sector.FEATURE,propertySet:{name:"IndicatorColor",property:"indicator-color-visual",type:n.TypeName.COLOR}},{propertySector:n.Sector.FEATURE,propertySet:{name:"IndicatorSelectedColor",property:"indicator-selected-color-visual",type:n.TypeName.COLOR,defaults:"#ff007dff"}},{propertySector:n.Sector.FEATURE,propertySet:{name:"IndicatorSize",property:"indicator-size-visual",type:n.TypeName.INTEGER,units:["px"]}},{propertySector:n.Sector.FEATURE,propertySet:Object.assign({name:"IndicatorTop",property:"indicator-top-visual"},n.commonParamsForIndicator)},{propertySector:n.Sector.FEATURE,propertySet:Object.assign({name:"IndicatorRight",property:"indicator-right-visual"},n.commonParamsForIndicator)},{propertySector:n.Sector.FEATURE,propertySet:Object.assign({name:"IndicatorBottom",property:"indicator-bottom-visual"},n.commonParamsForIndicator)},{propertySector:n.Sector.FEATURE,propertySet:Object.assign({name:"IndicatorLeft",property:"indicator-left-visual"},n.commonParamsForIndicator)},{propertySector:n.Sector.FEATURE,propertySet:{name:"AllowScale",property:"allow-scale-visual",type:n.TypeName.SELECT,defaults:"true",list:[n.CLEAN_VALUE_NODE,{value:"true"},{value:"false"}]}},{propertySector:n.Sector.GRID,propertySet:{name:"GridRowStart",property:"grid-row-start-visual",type:n.TypeName.INTEGER,requiresParent:{display:["grid"]},info:"The start position of its row in the grid area."}},{propertySector:n.Sector.GRID,propertySet:{name:"GridColumnStart",property:"grid-column-start-visual",type:n.TypeName.INTEGER,requiresParent:{display:["grid"]},info:"The start position of its column in the grid area."}},{propertySector:n.Sector.GRID,propertySet:{name:"GridRowEnd",property:"grid-row-end-visual",type:n.TypeName.INTEGER,requiresParent:{display:["grid"]},info:"The end position of its row in the grid area."}},{propertySector:n.Sector.GRID,propertySet:{name:"GridColumnEnd",property:"grid-column-end-visual",type:n.TypeName.INTEGER,requiresParent:{display:["grid"]},info:"The end position of its column in the grid area."}},{propertySector:n.Sector.GRID,propertySet:{name:"GridTemplateRows",property:"grid-template-rows-visual",type:n.TypeName.BASE,defaults:"1fr",requires:{"display-visual":["grid"]},info:"The number of items in the grid rows."}},{propertySector:n.Sector.GRID,propertySet:{name:"GridTemplateColumns",property:"grid-template-columns-visual",type:n.TypeName.BASE,defaults:"1fr",requires:{"display-visual":["grid"]},info:"The number of items in the grid columns."}},{propertySector:n.Sector.GRID,propertySet:{name:"GridRowsGap",property:"grid-rows-gap-visual",type:n.TypeName.INTEGER,defaults:"0px",units:["px"],requires:{"display-visual":["grid"]},info:"The size of the gap between an element's grid rows."}},{propertySector:n.Sector.GRID,propertySet:{name:"GridColumnsGap",property:"grid-columns-gap-visual",type:n.TypeName.INTEGER,defaults:"0px",units:["px"],requires:{"display-visual":["grid"]},info:"The size of the gap between an element's columns."}},{propertySector:n.Sector.GRID,propertySet:{name:"GridGap",property:"grid-gap-visual",type:n.TypeName.INTEGER,units:["px"],requires:{"display-visual":["grid"]},info:"The gaps between rows and columns. It is a shorthand for row-gap and column-gap."}},{propertySector:n.Sector.FEATURE,propertySet:Object.assign({name:"MatchTextDirection",property:"match-text-direction-visual"},n.commonParamsForJudge)},{propertySector:n.Sector.FEATURE,propertySet:Object.assign({name:"FitOriginalSize",property:"fit-original-size-visual"},n.commonParamsForJudge)},{propertySector:n.Sector.FEATURE,propertySet:{name:"IconWidth",property:"icon-width-visual",type:n.TypeName.INTEGER,units:["px"]}},{propertySector:n.Sector.FEATURE,propertySet:{name:"IconHeight",property:"icon-height-visual",type:n.TypeName.INTEGER,units:["px"]}},{propertySector:n.Sector.FEATURE,propertySet:{name:"TextonColor",property:"texton-color-visual",type:n.TypeName.COLOR,defaults:"#000000"}},{propertySector:n.Sector.FEATURE,propertySet:{name:"TextoffColor",property:"textoff-color-visual",type:n.TypeName.COLOR,defaults:"#000000"}},{propertySector:n.Sector.FEATURE,propertySet:{name:"TextPadding",property:"text-padding-visual",type:n.TypeName.INTEGER,defaults:0,units:["px"]}},{propertySector:n.Sector.FEATURE,propertySet:{name:"SelectedColor",property:"selected-color-visual",type:n.TypeName.COLOR,defaults:"rgba(0,125,255,1)"}},{propertySector:n.Sector.FEATURE,propertySet:{name:"BlockColor",property:"block-color-visual",type:n.TypeName.COLOR,defaults:"#ffffff"}},{propertySector:n.Sector.FEATURE,propertySet:{name:"Radius",property:"radius-visual",type:n.TypeName.INTEGER,units:["px"]}},{propertySector:n.Sector.FEATURE,propertySet:{name:"StartAngle",property:"start-angle-visual",type:n.TypeName.INTEGER,defaults:240}},{propertySector:n.Sector.FEATURE,propertySet:{name:"TotalAngle",property:"total-angle-visual",type:n.TypeName.INTEGER,defaults:240}},{propertySector:n.Sector.FEATURE,propertySet:{name:"CenterX",property:"center-x-visual",type:n.TypeName.INTEGER}},{propertySector:n.Sector.FEATURE,propertySet:{name:"CenterY",property:"center-y-visual",type:n.TypeName.INTEGER}},{propertySector:n.Sector.FEATURE,propertySet:{name:"Colors",property:"colors-visual",type:n.TypeName.BASE}},{propertySector:n.Sector.FEATURE,propertySet:{name:"Weights",property:"weights-visual",type:n.TypeName.BASE}},{propertySector:n.Sector.FEATURE,propertySet:{name:"PlaceHolderColor",property:"placeholder-color-visual",type:n.TypeName.COLOR,defaults:"gray"}},{propertySector:n.Sector.FEATURE,propertySet:{name:"ProgressColor",property:"progress-color-visual",type:n.TypeName.COLOR,etsType:n.EtsType.COMB_COLOR,defaults:"black"}},{propertySector:n.Sector.FEATURE,propertySet:{name:"ItemExtent",property:"item-extent-visual",type:n.TypeName.INTEGER,units:["px","%"]}},{propertySector:n.Sector.FEATURE,propertySet:{name:"FadeColor",property:"fade-color-visual",type:n.TypeName.COLOR,defaults:"grey"}},{propertySector:n.Sector.FLEX,propertySet:{name:"ColumnSpan",property:"column-span-visual",type:n.TypeName.INTEGER,defaults:1,min:1,info:"The number of span."}},{propertySector:n.Sector.ATOMIC,propertySet:{name:"FlexWeight",property:"flex-weight-visual",type:n.TypeName.INTEGER}},{propertySector:n.Sector.ATOMIC,propertySet:{name:"AspectRatio",property:"aspect-ratio-visual",type:n.TypeName.INTEGER,etsType:n.EtsType.NUMBER}},{propertySector:n.Sector.FEATURE,propertySet:{name:"SecondaryColor",property:"secondary-color-visual",type:n.TypeName.COLOR,requires:{type:["horizontal","ring","scale-ring"]}}},{propertySector:n.Sector.FEATURE,propertySet:{name:"ScaleWidth",property:"scale-width-visual",type:n.TypeName.INTEGER,requires:{type:["ring","scale-ring"]}}},{propertySector:n.Sector.FEATURE,propertySet:{name:"ScaleNumber",property:"scale-number-visual",type:n.TypeName.INTEGER,defaults:120,requires:{type:["ring","scale-ring"]}}},{propertySector:n.Sector.FEATURE,propertySet:{name:"Value",property:"value-visual",type:n.TypeName.INTEGER,etsType:n.EtsType.NUMBER,defaults:0}},{propertySector:n.Sector.FEATURE,propertySet:{name:"Total",property:"total-visual",type:n.TypeName.INTEGER,etsType:n.EtsType.NUMBER,defaults:100}},{propertySector:n.Sector.FEATURE,propertySet:{name:"Style",property:"style-visual",type:n.TypeName.SELECT,etsType:n.EtsType.PROGRESS_STYLE,defaults:"Linear",list:[{value:"Linear"}]}}]},513:(e,t)=>{"use strict";var r,n,o;Object.defineProperty(t,"__esModule",{value:!0}),t.EtsType=t.commonParamsForBorderRadius=t.commonParamsForIndicator=t.commonParamsForInteger=t.commonParamsForJudge=t.commonParamsForBorder=t.CLEAN_VALUE_NODE=t.TypeName=t.Sector=void 0,function(e){e.GENERAL="general",e.DIMENSION="dimension",e.FEATURE="feature",e.FLEX="flex",e.GRID="grid",e.ATOMIC="atomic"}(r||(r={})),t.Sector=r,function(e){e.BASE="base",e.INTEGER="integer",e.SELECT="select",e.COLOR="color",e.COMPOSITE="composite",e.SLIDER="slider",e.DATA_SELECT_INPUT="dataSelectInput",e.ADJUSTABLE="adjustable"}(n||(n={})),t.TypeName=n,function(e){e.ARRAY="ETSArray",e.BOOLEAN="ETSBoolean",e.NUMBER="ETSNumber",e.OBJECT="ETSObject",e.STRING="ETSString",e.R_FLOAT="Rfloat",e.R_STRING="Rstring",e.R_COLOR="Rcolor",e.R_MEDIA="Rmedia",e.R_RAWFILE="Rrawfile",e.ALIGNMENT="Alignment",e.AXIS="Axis",e.BORDER_STYLE="BorderStyle",e.BUTTON_TYPE="ButtonType",e.COLOR="Color",e.DIRECTION="Direction",e.EDGE_EFFECT="EdgeEffect",e.ENTER_KEY_TYPE="EnterKeyType",e.FLEX_ALIGN="FlexAlign",e.FLEX_DIRECTION="FlexDirection",e.FLEX_WRAP="FlexWrap",e.FONT_STYLE="FontStyle",e.FONT_WEIGHT="FontWeight",e.HORIZONTAL_ALIGN="HorizontalAlign",e.IMAGE_FIT="ImageFit",e.IMAGE_INTERPOLATION="ImageInterpolation",e.IMAGE_RENDER_MODE="ImageRenderMode",e.IMAGE_REPERT="ImageRepeat",e.IMAGE_SIZE="ImageSize",e.INPUT_TYPE="InputType",e.ITEM_ALIGN="ItemAlign",e.LINE_CAP_STYLE="LineCapStyle",e.PROGRESS_STYLE="ProgressStyle",e.STICKY="Sticky",e.TEXT_ALIGN="TextAlign",e.TEXT_OVERFLOW="TextOverflow",e.TEXT_DECORATION_TYPE="TextDecorationType",e.TEXT_CASE="TextCase",e.VERTICAL_ALIGN="VerticalAlign",e.VISIBILITY="Visibility",e.COMB_COLOR="ETSString|ETSNumber|Color|Rcolor",e.COMB_LENGTH="ETSString|ETSNumber",e.COMB_R_NUMBER="ETSNumber|Rfloat",e.COMB_R_LENGTH="ETSString|ETSNumber|Rfloat",e.COMB_CONTENT="ETSString|Rstring",e.COMB_SRC="ETSString|Rmedia|Rrawfile"}(o||(o={})),t.EtsType=o;const i={value:"cleanValue",name:"---Clean Value---"};t.CLEAN_VALUE_NODE=i;const a={type:n.SELECT,etsType:o.BORDER_STYLE,list:[i,{value:"dotted",etsEnumValue:"Dotted"},{value:"dashed",etsEnumValue:"Dashed"},{value:"solid",etsEnumValue:"Solid"}]};t.commonParamsForBorder=a;const s={type:n.SELECT,etsType:o.BOOLEAN,defaults:"false",list:[i,{value:"true"},{value:"false"}]};t.commonParamsForJudge=s;const c={type:n.INTEGER,units:["px"],placeholder:"0px"};t.commonParamsForInteger=c;const u={type:n.INTEGER,units:["px","%"]};t.commonParamsForIndicator=u;const l={type:n.INTEGER,units:["px"]};t.commonParamsForBorderRadius=l},282:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TagTypeMap=void 0,t.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"],["select","Container"],["tabs","Container"],["tab-bar","Container"],["tab-content","Container"]])},294:(e,t)=>{"use strict";function r(e){let t=function(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");let r="";for(let t=0;t=4&&(t=t.substr(t.length/2-2,4)),t}Object.defineProperty(t,"__esModule",{value:!0}),t.getUniqueName=t.getUniqueId=t.removeFromArray=t.getDataName=void 0,t.getDataName=function(e){if("string"==typeof e&&e.startsWith("{{")&&e.endsWith("}}"))return e.substring(2,e.length-2)},t.removeFromArray=function(e,t){const r=[...e];return t.forEach((e=>{const t=r.indexOf(e);-1!==t&&r.splice(t,1)})),r},t.getUniqueId=r,t.getUniqueName=function(e){return`${e}_${r(e)}`}},207:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.formManager=void 0;const n=r(891),o=r(945);t.formManager={removeData(e){this.getFormModel().data.delete(e)},addData(e){e instanceof Map?e.forEach(((e,t)=>{this.getFormModel().data.set(t,e)})):Object.keys(e).forEach((t=>{this.getFormModel().data.set(t,e[t])}))},updateAllData(e){this.getFormModel().data.clear(),this.addData(e)},addAction(e,t,r,n){const i=new Map;void 0!==r&&Object.keys(r).forEach((e=>{i.set(e,r[e])}));const a=new Map;void 0!==n&&Object.keys(n).forEach((e=>{a.set(e,n[e])})),this.getFormModel().actions.set(e,new o.FormAction(t,i,a))},updateAllActions(e){this.getFormModel().actions.clear(),e.forEach(((e,t)=>{const r=void 0===e.params?e.params:this.objectToMap(e.params),n=void 0===e.want?e.want:this.objectToMap(e.want),i=new o.FormAction(e.actionType,r,n);this.getFormModel().actions.set(t,i)}))},removeAction(e){this.getFormModel().actions.delete(e)},addActionParams(e,t){var r,n;const i=null!==(r=this.getFormModel().actions.get(e))&&void 0!==r?r:new o.FormAction(e),a=null!==(n=i.params)&&void 0!==n?n:new Map;Object.keys(t).forEach((e=>{a.set(e,t[e])})),i.params=a},removeActionParam(e,t){var r;const n=this.getFormModel().actions.get(e);null===(r=null==n?void 0:n.params)||void 0===r||r.delete(t)},getFormModel:()=>n.getInstance().formData,codegenToJson:function(){const e=n.getInstance().formData,t=this.mapToObject(e.data),r={actions:{},data:{}};return r.data=t,e.actions.forEach(((e,t)=>{r.actions[t]={},r.actions[t].action=e.action,e.params instanceof Map&&e.params.size>0&&(r.actions[t].params=this.mapToObject(e.params)),e.want instanceof Map&&e.want.size>0&&(r.actions[t].want=this.mapToObject(e.want))})),JSON.stringify(r,null,4)},clear(){n.getInstance().formData.data.clear(),n.getInstance().formData.actions.clear()},mapToObject:e=>void 0===e?{}:Array.from(e.entries()).reduce(((e,[t,r])=>Object.assign(Object.assign({},e),{[t]:r})),{}),objectToMap(e){const t=new Map;return Object.keys(e).forEach(((r,n)=>{t.set(r,e[r])})),t}}},945:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FormAction=t.FormModel=void 0,t.FormModel=class{constructor(){this.data=new Map,this.actions=new Map}},t.FormAction=class{constructor(e,t,r){this.action=e,this.params=t,this.want=r}}},509:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deserializeForVersion1=t.rootToVisualContent=t.visualToRootContent=t.serializeForVersion1=void 0;const n=r(891),o=r(933),i=r(571),a=r(282),s=r(945),c=r(977),u=new Map;function l(e){u.set("textMap",new Map);const t=p(null!=e?e:n.getInstance().visualModel);return JSON.stringify({VisualVersion:"1",content:JSON.stringify(t),extraData:JSON.stringify(y(u))})}function p(e){const t=Array.from(e.property).filter((t=>i.isAttribute(t[0],e.type)));t.push(["id",e.id]);const r=Array.from(e.property).filter((t=>i.isStyle(t[0],e.type)));let n=a.TagTypeMap.get(e.type);void 0===n&&(n="Base");let o=e.property.has("content")?e.property.get("content"):[];if(e.children.length>0){if("string"==typeof o){const t=u.get("textMap");t instanceof Map&&t.set(e.id,o)}o=e.children.map((e=>p(e)))}return{id:e.id,tagName:e.type,attributes:t,idStyle:r,type:n,content:o}}function f(e,t){let r;if(t instanceof Map){const n=t.get("textMap");n instanceof Map&&(r=n.get(e.id))}const n=new o.VisualModel({id:e.id,type:e.tagName,property:new Map([...e.attributes,...e.idStyle])});return"string"==typeof r&&n.property.set("content",r),n.property.delete("id"),"string"==typeof e.content&&n.property.set("content",e.content),Array.isArray(e.content)&&(n.children=e.content.map((e=>f(e,t)))),n}function d(e){if(e instanceof Array&&e.length>0&&"$$map"===e[0]){e.shift();const t=new Map;for(const[r,n]of e)t.set(r,d(n));return t}return e}function y(e){if(e instanceof Map){const t=["$$map"];for(const[r,n]of e)t.push([r,y(n)]);return t}return e}t.serializeForVersion1=l,t.visualToRootContent=function(e){try{return l(JSON.parse(e,c.reviver).visualModel)}catch(e){console.error("convert visual model to root model failed")}return e},t.rootToVisualContent=function(e){const t=JSON.parse(e),r=JSON.parse(t.content);let n='["$$map",["textMap",["$$map"]]]';"string"==typeof t.extraData&&(n=JSON.parse(t.extraData));const o=f(r,d(n));return o.property.has("flex-direction")||o.property.set("flex-direction","column"),JSON.stringify({document:{VisualVersion:"12",type:"FA"},visualModel:o,formData:new s.FormModel},c.replacer)},t.deserializeForVersion1=function(e){try{const t=JSON.parse(e),r=JSON.parse(t.content);let o='["$$map",["textMap",["$$map"]]]';"string"==typeof t.extraData&&(o=JSON.parse(t.extraData)),n.getInstance().visualModel=f(r,d(o)),n.getInstance().visualModel.property.has("flex-direction")||n.getInstance().visualModel.property.set("flex-direction","column")}catch(e){console.error("convert error")}}},891:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setInstance=t.getInstance=void 0;const n=r(933),o=r(945),i=r(904),a={document:{VisualVersion:"12",type:"FA"},visualModel:new n.VisualModel({type:"div",id:"wrapper"}),formData:new o.FormModel};t.getInstance=function(){return a},t.setInstance=function(e){for(const t in a)Object.prototype.hasOwnProperty.call(e,t)&&(a[t]=e[t]);const t=a.document.type;i.setDomain("ETS"===t?i.Domain.ETS:"FORM"===t?i.Domain.FORM:i.Domain.FA)}},977:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.reviver=t.replacer=t.deserialize=t.serialize=void 0;const n=r(933),o=r(891),i=r(509);function a(e,t){if(t instanceof Map)return{dataType:"Map",value:Object.fromEntries(t.entries())};if(t instanceof Set)return{dataType:"Set",value:Array.from(t.entries())};if(t instanceof n.VisualModel){const e=new n.VisualModel({type:"none"}),r={};for(const n in e)Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=t[n]);return{dataType:"VisualModel",value:r}}return t}function s(e,t){if("object"==typeof t&&null!=t){if("Map"===t.dataType)return new Map(Object.entries(t.value));if("Set"===t.dataType)return new Set(t.value);if("VisualModel"===t.dataType){const e=new n.VisualModel({type:""});Object.assign(e,t.value),t=e}}return t}t.serialize=function(e,t){return 1===e?i.serializeForVersion1(t):JSON.stringify(null!=t?t:o.getInstance(),a,4)},t.deserialize=function(e){if("1"===JSON.parse(e).VisualVersion)return i.deserializeForVersion1(e);const t=JSON.parse(e,s);o.setInstance(t)},t.replacer=a,t.reviver=s},933:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.VisualModel=void 0;const r="-visual";t.VisualModel=class{constructor(e){if(this.propertyStorage=void 0,this.dynamicPropertyStorage=void 0,this.mediaProperty=void 0,this.dynamicMediaProperty=void 0,this.mediaPropertyStorage=void 0,this.dynamicMediaPropertyStorage=void 0,this.property=void 0!==e.property?e.property:new Map,this.dynamicProperty=void 0!==e.dynamicProperty?e.dynamicProperty:new Map,this.children=void 0!==e.children?e.children:[],"wrapper"===e.type)return this.id="wrapper",void(this.type="div");e.type.endsWith(r)&&(e.type=e.type.substring(0,e.type.length-r.length)),this.id=void 0!==e.id?e.id:"",this.type=e.type}getProperty(e){const t=this.dynamicProperty.get(e);return void 0!==t&&""!==t?t:this.property.get(e)}hasMediaProperty(e){if(void 0!==this.mediaProperty)for(const[,t]of this.mediaProperty)if(null==t?void 0:t.has(e))return!0;if(void 0!==this.dynamicMediaProperty)for(const[,t]of this.dynamicMediaProperty)if(null==t?void 0:t.has(e))return!0;return!1}hasProperty(e){return this.dynamicProperty.has(e)||this.property.has(e)}accept(e){return e.visit(this)}}}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var i=t[n]={id:n,loaded:!1,exports:{}};return e[n].call(i.exports,i,i.exports,r),i.loaded=!0,i.exports}r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.nmd=e=>(e.paths=[],e.children||(e.children=[]),e);var n={};(()=>{"use strict";var e=n;Object.defineProperty(e,"__esModule",{value:!0});const t=r(784),o=r(891),i=r(977),a=r(844),s=r(55),c=r(207),u=r(413),l=r(435),p=r(486),f={build:"",etsImport:"",etsVariable:"",etsFunction:"",aboutToAppear:""};function d(e,r){var n;try{i.deserialize(e);const t=o.getInstance().document.VisualVersion,n=/^([1-9]+[0-9]*)$/;if(void 0===t)r.errorType="versionError";else{const e=t.match(n);(null===e||parseInt(e[1])>12)&&(r.errorType="versionError")}}catch(e){r.errorType="fileError"}""!==r.errorType&&(r.errorMessage=null!==(n=t.errorMap.get(r.errorType))&&void 0!==n?n:"Codegen visual file failed")}e.genHmlAndCss=function(e){const r={hmlCss:{hml:"",css:"",json:""},errorType:"",errorMessage:""};if(d(e,r),""!==r.errorType)return r.hmlCss.hml="",r.hmlCss.css="",r;try{const e=function(e){const t={hml:"",css:"",json:""},r=new a.HMLBridge,n=e.accept(r),o=s.genFAHML(n);t.hml=r.getErrorCount()>0?"error":o;const i=new a.CSSBridge,c=e.accept(i),u=s.genFACSS(c);return t.css=i.getErrorCount()>0?"error":u,t}(o.getInstance().visualModel);"error"!==e.hml&&"error"!==e.css||(r.errorType="codegenError"),r.hmlCss=e,"FORM"===o.getInstance().document.type&&(r.hmlCss.json=c.formManager.codegenToJson())}catch(e){r.errorType="modelError"}return""!==r.errorType&&(r.errorMessage=t.errorMap.get(r.errorType),r.hmlCss.hml="",r.hmlCss.css=""),r},e.genETS=function(e){var r;const n={ets:p.cloneDeep(f),errorType:"",errorMessage:""};if(d(e,n),""!==n.errorType)return n.ets=p.cloneDeep(f),n;try{const e=function(e){const t=new u.ETSBridge,r=e.accept(t),n=(new l.StringWriter).genETS(r);return t.getErrorCount()>0?"error":n}(o.getInstance().visualModel);"error"===e&&(n.errorType="codegenError"),n.ets=e}catch(e){n.errorType="modelError"}return""!==n.errorType&&(n.errorMessage=null!==(r=t.errorMap.get(n.errorType))&&void 0!==r?r:"Codegen visual file failed",n.ets=p.cloneDeep(f)),n}})();var o=exports;for(var i in n)o[i]=n[i];n.__esModule&&Object.defineProperty(o,"__esModule",{value:!0})})(); \ No newline at end of file +(()=>{var e={6486:function(e,t,r){var o;e=r.nmd(e),function(){var n,a="Expected a function",i="__lodash_hash_undefined__",s="__lodash_placeholder__",p=32,l=128,c=1/0,u=9007199254740991,y=NaN,d=4294967295,f=[["ary",l],["bind",1],["bindKey",2],["curry",8],["curryRight",16],["flip",512],["partial",p],["partialRight",64],["rearg",256]],m="[object Arguments]",g="[object Array]",h="[object Boolean]",E="[object Date]",T="[object Error]",S="[object Function]",P="[object GeneratorFunction]",v="[object Map]",b="[object Number]",_="[object Object]",N="[object Promise]",C="[object RegExp]",O="[object Set]",A="[object String]",M="[object Symbol]",w="[object WeakMap]",R="[object ArrayBuffer]",x="[object DataView]",L="[object Float32Array]",I="[object Float64Array]",F="[object Int8Array]",k="[object Int16Array]",B="[object Int32Array]",D="[object Uint8Array]",U="[object Uint8ClampedArray]",V="[object Uint16Array]",z="[object Uint32Array]",G=/\b__p \+= '';/g,j=/\b(__p \+=) '' \+/g,W=/(__e\(.*?\)|\b__t\)) \+\n'';/g,$=/&(?:amp|lt|gt|quot|#39);/g,q=/[&<>"']/g,H=RegExp($.source),Y=RegExp(q.source),X=/<%-([\s\S]+?)%>/g,J=/<%([\s\S]+?)%>/g,K=/<%=([\s\S]+?)%>/g,Q=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Z=/^\w*$/,ee=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,te=/[\\^$.*+?()[\]{}|]/g,re=RegExp(te.source),oe=/^\s+/,ne=/\s/,ae=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,ie=/\{\n\/\* \[wrapped with (.+)\] \*/,se=/,? & /,pe=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,le=/[()=,{}\[\]\/\s]/,ce=/\\(\\)?/g,ue=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,ye=/\w*$/,de=/^[-+]0x[0-9a-f]+$/i,fe=/^0b[01]+$/i,me=/^\[object .+?Constructor\]$/,ge=/^0o[0-7]+$/i,he=/^(?:0|[1-9]\d*)$/,Ee=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,Te=/($^)/,Se=/['\n\r\u2028\u2029\\]/g,Pe="\\ud800-\\udfff",ve="\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff",be="\\u2700-\\u27bf",_e="a-z\\xdf-\\xf6\\xf8-\\xff",Ne="A-Z\\xc0-\\xd6\\xd8-\\xde",Ce="\\ufe0e\\ufe0f",Oe="\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",Ae="["+Pe+"]",Me="["+Oe+"]",we="["+ve+"]",Re="\\d+",xe="["+be+"]",Le="["+_e+"]",Ie="[^"+Pe+Oe+Re+be+_e+Ne+"]",Fe="\\ud83c[\\udffb-\\udfff]",ke="[^"+Pe+"]",Be="(?:\\ud83c[\\udde6-\\uddff]){2}",De="[\\ud800-\\udbff][\\udc00-\\udfff]",Ue="["+Ne+"]",Ve="\\u200d",ze="(?:"+Le+"|"+Ie+")",Ge="(?:"+Ue+"|"+Ie+")",je="(?:['’](?:d|ll|m|re|s|t|ve))?",We="(?:['’](?:D|LL|M|RE|S|T|VE))?",$e="(?:"+we+"|"+Fe+")?",qe="["+Ce+"]?",He=qe+$e+"(?:"+Ve+"(?:"+[ke,Be,De].join("|")+")"+qe+$e+")*",Ye="(?:"+[xe,Be,De].join("|")+")"+He,Xe="(?:"+[ke+we+"?",we,Be,De,Ae].join("|")+")",Je=RegExp("['’]","g"),Ke=RegExp(we,"g"),Qe=RegExp(Fe+"(?="+Fe+")|"+Xe+He,"g"),Ze=RegExp([Ue+"?"+Le+"+"+je+"(?="+[Me,Ue,"$"].join("|")+")",Ge+"+"+We+"(?="+[Me,Ue+ze,"$"].join("|")+")",Ue+"?"+ze+"+"+je,Ue+"+"+We,"\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])","\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",Re,Ye].join("|"),"g"),et=RegExp("["+Ve+Pe+ve+Ce+"]"),tt=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,rt=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],ot=-1,nt={};nt[L]=nt[I]=nt[F]=nt[k]=nt[B]=nt[D]=nt[U]=nt[V]=nt[z]=!0,nt[m]=nt[g]=nt[R]=nt[h]=nt[x]=nt[E]=nt[T]=nt[S]=nt[v]=nt[b]=nt[_]=nt[C]=nt[O]=nt[A]=nt[w]=!1;var at={};at[m]=at[g]=at[R]=at[x]=at[h]=at[E]=at[L]=at[I]=at[F]=at[k]=at[B]=at[v]=at[b]=at[_]=at[C]=at[O]=at[A]=at[M]=at[D]=at[U]=at[V]=at[z]=!0,at[T]=at[S]=at[w]=!1;var it={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},st=parseFloat,pt=parseInt,lt="object"==typeof r.g&&r.g&&r.g.Object===Object&&r.g,ct="object"==typeof self&&self&&self.Object===Object&&self,ut=lt||ct||Function("return this")(),yt=t&&!t.nodeType&&t,dt=yt&&e&&!e.nodeType&&e,ft=dt&&dt.exports===yt,mt=ft&<.process,gt=function(){try{return dt&&dt.require&&dt.require("util").types||mt&&mt.binding&&mt.binding("util")}catch(e){}}(),ht=gt&>.isArrayBuffer,Et=gt&>.isDate,Tt=gt&>.isMap,St=gt&>.isRegExp,Pt=gt&>.isSet,vt=gt&>.isTypedArray;function bt(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)}function _t(e,t,r,o){for(var n=-1,a=null==e?0:e.length;++n-1}function wt(e,t,r){for(var o=-1,n=null==e?0:e.length;++o-1;);return r}function Zt(e,t){for(var r=e.length;r--&&Ut(t,e[r],0)>-1;);return r}function er(e,t){for(var r=e.length,o=0;r--;)e[r]===t&&++o;return o}var tr=Wt({À:"A",Á:"A",Â:"A",Ã:"A",Ä:"A",Å:"A",à:"a",á:"a",â:"a",ã:"a",ä:"a",å:"a",Ç:"C",ç:"c",Ð:"D",ð:"d",È:"E",É:"E",Ê:"E",Ë:"E",è:"e",é:"e",ê:"e",ë:"e",Ì:"I",Í:"I",Î:"I",Ï:"I",ì:"i",í:"i",î:"i",ï:"i",Ñ:"N",ñ:"n",Ò:"O",Ó:"O",Ô:"O",Õ:"O",Ö:"O",Ø:"O",ò:"o",ó:"o",ô:"o",õ:"o",ö:"o",ø:"o",Ù:"U",Ú:"U",Û:"U",Ü:"U",ù:"u",ú:"u",û:"u",ü:"u",Ý:"Y",ý:"y",ÿ:"y",Æ:"Ae",æ:"ae",Þ:"Th",þ:"th",ß:"ss",Ā:"A",Ă:"A",Ą:"A",ā:"a",ă:"a",ą:"a",Ć:"C",Ĉ:"C",Ċ:"C",Č:"C",ć:"c",ĉ:"c",ċ:"c",č:"c",Ď:"D",Đ:"D",ď:"d",đ:"d",Ē:"E",Ĕ:"E",Ė:"E",Ę:"E",Ě:"E",ē:"e",ĕ:"e",ė:"e",ę:"e",ě:"e",Ĝ:"G",Ğ:"G",Ġ:"G",Ģ:"G",ĝ:"g",ğ:"g",ġ:"g",ģ:"g",Ĥ:"H",Ħ:"H",ĥ:"h",ħ:"h",Ĩ:"I",Ī:"I",Ĭ:"I",Į:"I",İ:"I",ĩ:"i",ī:"i",ĭ:"i",į:"i",ı:"i",Ĵ:"J",ĵ:"j",Ķ:"K",ķ:"k",ĸ:"k",Ĺ:"L",Ļ:"L",Ľ:"L",Ŀ:"L",Ł:"L",ĺ:"l",ļ:"l",ľ:"l",ŀ:"l",ł:"l",Ń:"N",Ņ:"N",Ň:"N",Ŋ:"N",ń:"n",ņ:"n",ň:"n",ŋ:"n",Ō:"O",Ŏ:"O",Ő:"O",ō:"o",ŏ:"o",ő:"o",Ŕ:"R",Ŗ:"R",Ř:"R",ŕ:"r",ŗ:"r",ř:"r",Ś:"S",Ŝ:"S",Ş:"S",Š:"S",ś:"s",ŝ:"s",ş:"s",š:"s",Ţ:"T",Ť:"T",Ŧ:"T",ţ:"t",ť:"t",ŧ:"t",Ũ:"U",Ū:"U",Ŭ:"U",Ů:"U",Ű:"U",Ų:"U",ũ:"u",ū:"u",ŭ:"u",ů:"u",ű:"u",ų:"u",Ŵ:"W",ŵ:"w",Ŷ:"Y",ŷ:"y",Ÿ:"Y",Ź:"Z",Ż:"Z",Ž:"Z",ź:"z",ż:"z",ž:"z",IJ:"IJ",ij:"ij",Œ:"Oe",œ:"oe",ʼn:"'n",ſ:"s"}),rr=Wt({"&":"&","<":"<",">":">",'"':""","'":"'"});function or(e){return"\\"+it[e]}function nr(e){return et.test(e)}function ar(e){var t=-1,r=Array(e.size);return e.forEach((function(e,o){r[++t]=[o,e]})),r}function ir(e,t){return function(r){return e(t(r))}}function sr(e,t){for(var r=-1,o=e.length,n=0,a=[];++r",""":'"',"'":"'"}),fr=function e(t){var r,o=(t=null==t?ut:fr.defaults(ut.Object(),t,fr.pick(ut,rt))).Array,ne=t.Date,Pe=t.Error,ve=t.Function,be=t.Math,_e=t.Object,Ne=t.RegExp,Ce=t.String,Oe=t.TypeError,Ae=o.prototype,Me=ve.prototype,we=_e.prototype,Re=t["__core-js_shared__"],xe=Me.toString,Le=we.hasOwnProperty,Ie=0,Fe=(r=/[^.]+$/.exec(Re&&Re.keys&&Re.keys.IE_PROTO||""))?"Symbol(src)_1."+r:"",ke=we.toString,Be=xe.call(_e),De=ut._,Ue=Ne("^"+xe.call(Le).replace(te,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Ve=ft?t.Buffer:n,ze=t.Symbol,Ge=t.Uint8Array,je=Ve?Ve.allocUnsafe:n,We=ir(_e.getPrototypeOf,_e),$e=_e.create,qe=we.propertyIsEnumerable,He=Ae.splice,Ye=ze?ze.isConcatSpreadable:n,Xe=ze?ze.iterator:n,Qe=ze?ze.toStringTag:n,et=function(){try{var e=ca(_e,"defineProperty");return e({},"",{}),e}catch(e){}}(),it=t.clearTimeout!==ut.clearTimeout&&t.clearTimeout,lt=ne&&ne.now!==ut.Date.now&&ne.now,ct=t.setTimeout!==ut.setTimeout&&t.setTimeout,yt=be.ceil,dt=be.floor,mt=_e.getOwnPropertySymbols,gt=Ve?Ve.isBuffer:n,kt=t.isFinite,Wt=Ae.join,mr=ir(_e.keys,_e),gr=be.max,hr=be.min,Er=ne.now,Tr=t.parseInt,Sr=be.random,Pr=Ae.reverse,vr=ca(t,"DataView"),br=ca(t,"Map"),_r=ca(t,"Promise"),Nr=ca(t,"Set"),Cr=ca(t,"WeakMap"),Or=ca(_e,"create"),Ar=Cr&&new Cr,Mr={},wr=Ua(vr),Rr=Ua(br),xr=Ua(_r),Lr=Ua(Nr),Ir=Ua(Cr),Fr=ze?ze.prototype:n,kr=Fr?Fr.valueOf:n,Br=Fr?Fr.toString:n;function Dr(e){if(rs(e)&&!$i(e)&&!(e instanceof Gr)){if(e instanceof zr)return e;if(Le.call(e,"__wrapped__"))return Va(e)}return new zr(e)}var Ur=function(){function e(){}return function(t){if(!ts(t))return{};if($e)return $e(t);e.prototype=t;var r=new e;return e.prototype=n,r}}();function Vr(){}function zr(e,t){this.__wrapped__=e,this.__actions__=[],this.__chain__=!!t,this.__index__=0,this.__values__=n}function Gr(e){this.__wrapped__=e,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=d,this.__views__=[]}function jr(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t=t?e:t)),e}function io(e,t,r,o,a,i){var s,p=1&t,l=2&t,c=4&t;if(r&&(s=a?r(e,o,a,i):r(e)),s!==n)return s;if(!ts(e))return e;var u=$i(e);if(u){if(s=function(e){var t=e.length,r=new e.constructor(t);return t&&"string"==typeof e[0]&&Le.call(e,"index")&&(r.index=e.index,r.input=e.input),r}(e),!p)return An(e,s)}else{var y=da(e),d=y==S||y==P;if(Xi(e))return vn(e,p);if(y==_||y==m||d&&!a){if(s=l||d?{}:ma(e),!p)return l?function(e,t){return Mn(e,ya(e),t)}(e,function(e,t){return e&&Mn(t,Ls(t),e)}(s,e)):function(e,t){return Mn(e,ua(e),t)}(e,ro(s,e))}else{if(!at[y])return a?e:{};s=function(e,t,r){var o,n=e.constructor;switch(t){case R:return bn(e);case h:case E:return new n(+e);case x:return function(e,t){var r=t?bn(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.byteLength)}(e,r);case L:case I:case F:case k:case B:case D:case U:case V:case z:return _n(e,r);case v:return new n;case b:case A:return new n(e);case C:return function(e){var t=new e.constructor(e.source,ye.exec(e));return t.lastIndex=e.lastIndex,t}(e);case O:return new n;case M:return o=e,kr?_e(kr.call(o)):{}}}(e,y,p)}}i||(i=new Hr);var f=i.get(e);if(f)return f;i.set(e,s),ss(e)?e.forEach((function(o){s.add(io(o,t,r,o,e,i))})):os(e)&&e.forEach((function(o,n){s.set(n,io(o,t,r,n,e,i))}));var g=u?n:(c?l?oa:ra:l?Ls:xs)(e);return Nt(g||e,(function(o,n){g&&(o=e[n=o]),Zr(s,n,io(o,t,r,n,e,i))})),s}function so(e,t,r){var o=r.length;if(null==e)return!o;for(e=_e(e);o--;){var a=r[o],i=t[a],s=e[a];if(s===n&&!(a in e)||!i(s))return!1}return!0}function po(e,t,r){if("function"!=typeof e)throw new Oe(a);return wa((function(){e.apply(n,r)}),t)}function lo(e,t,r,o){var n=-1,a=Mt,i=!0,s=e.length,p=[],l=t.length;if(!s)return p;r&&(t=Rt(t,Xt(r))),o?(a=wt,i=!1):t.length>=200&&(a=Kt,i=!1,t=new qr(t));e:for(;++n-1},Wr.prototype.set=function(e,t){var r=this.__data__,o=eo(r,e);return o<0?(++this.size,r.push([e,t])):r[o][1]=t,this},$r.prototype.clear=function(){this.size=0,this.__data__={hash:new jr,map:new(br||Wr),string:new jr}},$r.prototype.delete=function(e){var t=pa(this,e).delete(e);return this.size-=t?1:0,t},$r.prototype.get=function(e){return pa(this,e).get(e)},$r.prototype.has=function(e){return pa(this,e).has(e)},$r.prototype.set=function(e,t){var r=pa(this,e),o=r.size;return r.set(e,t),this.size+=r.size==o?0:1,this},qr.prototype.add=qr.prototype.push=function(e){return this.__data__.set(e,i),this},qr.prototype.has=function(e){return this.__data__.has(e)},Hr.prototype.clear=function(){this.__data__=new Wr,this.size=0},Hr.prototype.delete=function(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r},Hr.prototype.get=function(e){return this.__data__.get(e)},Hr.prototype.has=function(e){return this.__data__.has(e)},Hr.prototype.set=function(e,t){var r=this.__data__;if(r instanceof Wr){var o=r.__data__;if(!br||o.length<199)return o.push([e,t]),this.size=++r.size,this;r=this.__data__=new $r(o)}return r.set(e,t),this.size=r.size,this};var co=xn(To),uo=xn(So,!0);function yo(e,t){var r=!0;return co(e,(function(e,o,n){return r=!!t(e,o,n)})),r}function fo(e,t,r){for(var o=-1,a=e.length;++o0&&r(s)?t>1?go(s,t-1,r,o,n):xt(n,s):o||(n[n.length]=s)}return n}var ho=Ln(),Eo=Ln(!0);function To(e,t){return e&&ho(e,t,xs)}function So(e,t){return e&&Eo(e,t,xs)}function Po(e,t){return At(t,(function(t){return Qi(e[t])}))}function vo(e,t){for(var r=0,o=(t=En(t,e)).length;null!=e&&rt}function Co(e,t){return null!=e&&Le.call(e,t)}function Oo(e,t){return null!=e&&t in _e(e)}function Ao(e,t,r){for(var a=r?wt:Mt,i=e[0].length,s=e.length,p=s,l=o(s),c=1/0,u=[];p--;){var y=e[p];p&&t&&(y=Rt(y,Xt(t))),c=hr(y.length,c),l[p]=!r&&(t||i>=120&&y.length>=120)?new qr(p&&y):n}y=e[0];var d=-1,f=l[0];e:for(;++d=s?p:p*("desc"==r[o]?-1:1)}return e.index-t.index}(e,t,r)}));o--;)e[o]=e[o].value;return e}(n)}function jo(e,t,r){for(var o=-1,n=t.length,a={};++o-1;)s!==e&&He.call(s,p,1),He.call(e,p,1);return e}function $o(e,t){for(var r=e?t.length:0,o=r-1;r--;){var n=t[r];if(r==o||n!==a){var a=n;ha(n)?He.call(e,n,1):cn(e,n)}}return e}function qo(e,t){return e+dt(Sr()*(t-e+1))}function Ho(e,t){var r="";if(!e||t<1||t>u)return r;do{t%2&&(r+=e),(t=dt(t/2))&&(e+=e)}while(t);return r}function Yo(e,t){return Ra(Na(e,t,np),e+"")}function Xo(e){return Xr(zs(e))}function Jo(e,t){var r=zs(e);return Ia(r,ao(t,0,r.length))}function Ko(e,t,r,o){if(!ts(e))return e;for(var a=-1,i=(t=En(t,e)).length,s=i-1,p=e;null!=p&&++aa?0:a+t),(r=r>a?a:r)<0&&(r+=a),a=t>r?0:r-t>>>0,t>>>=0;for(var i=o(a);++n>>1,i=e[a];null!==i&&!ls(i)&&(r?i<=t:i=200){var l=t?null:Yn(e);if(l)return pr(l);i=!1,n=Kt,p=new qr}else p=t?[]:s;e:for(;++o=o?e:tn(e,t,r)}var Pn=it||function(e){return ut.clearTimeout(e)};function vn(e,t){if(t)return e.slice();var r=e.length,o=je?je(r):new e.constructor(r);return e.copy(o),o}function bn(e){var t=new e.constructor(e.byteLength);return new Ge(t).set(new Ge(e)),t}function _n(e,t){var r=t?bn(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}function Nn(e,t){if(e!==t){var r=e!==n,o=null===e,a=e==e,i=ls(e),s=t!==n,p=null===t,l=t==t,c=ls(t);if(!p&&!c&&!i&&e>t||i&&s&&l&&!p&&!c||o&&s&&l||!r&&l||!a)return 1;if(!o&&!i&&!c&&e1?r[a-1]:n,s=a>2?r[2]:n;for(i=e.length>3&&"function"==typeof i?(a--,i):n,s&&Ea(r[0],r[1],s)&&(i=a<3?n:i,a=1),t=_e(t);++o-1?a[i?t[s]:s]:n}}function Dn(e){return ta((function(t){var r=t.length,o=r,i=zr.prototype.thru;for(e&&t.reverse();o--;){var s=t[o];if("function"!=typeof s)throw new Oe(a);if(i&&!p&&"wrapper"==aa(s))var p=new zr([],!0)}for(o=p?o:r;++o1&&T.reverse(),d&&up))return!1;var c=i.get(e),u=i.get(t);if(c&&u)return c==t&&u==e;var y=-1,d=!0,f=2&r?new qr:n;for(i.set(e,t),i.set(t,e);++y-1&&e%1==0&&e1?"& ":"")+t[o],t=t.join(r>2?", ":" "),e.replace(ae,"{\n/* [wrapped with "+t+"] */\n")}(o,function(e,t){return Nt(f,(function(r){var o="_."+r[0];t&r[1]&&!Mt(e,o)&&e.push(o)})),e.sort()}(function(e){var t=e.match(ie);return t?t[1].split(se):[]}(o),r)))}function La(e){var t=0,r=0;return function(){var o=Er(),a=16-(o-r);if(r=o,a>0){if(++t>=800)return arguments[0]}else t=0;return e.apply(n,arguments)}}function Ia(e,t){var r=-1,o=e.length,a=o-1;for(t=t===n?o:t;++r1?e[t-1]:n;return r="function"==typeof r?(e.pop(),r):n,ii(e,r)}));function di(e){var t=Dr(e);return t.__chain__=!0,t}function fi(e,t){return t(e)}var mi=ta((function(e){var t=e.length,r=t?e[0]:0,o=this.__wrapped__,a=function(t){return no(t,e)};return!(t>1||this.__actions__.length)&&o instanceof Gr&&ha(r)?((o=o.slice(r,+r+(t?1:0))).__actions__.push({func:fi,args:[a],thisArg:n}),new zr(o,this.__chain__).thru((function(e){return t&&!e.length&&e.push(n),e}))):this.thru(a)})),gi=wn((function(e,t,r){Le.call(e,r)?++e[r]:oo(e,r,1)})),hi=Bn(Wa),Ei=Bn($a);function Ti(e,t){return($i(e)?Nt:co)(e,sa(t,3))}function Si(e,t){return($i(e)?Ct:uo)(e,sa(t,3))}var Pi=wn((function(e,t,r){Le.call(e,r)?e[r].push(t):oo(e,r,[t])})),vi=Yo((function(e,t,r){var n=-1,a="function"==typeof t,i=Hi(e)?o(e.length):[];return co(e,(function(e){i[++n]=a?bt(t,e,r):Mo(e,t,r)})),i})),bi=wn((function(e,t,r){oo(e,r,t)}));function _i(e,t){return($i(e)?Rt:Bo)(e,sa(t,3))}var Ni=wn((function(e,t,r){e[r?0:1].push(t)}),(function(){return[[],[]]})),Ci=Yo((function(e,t){if(null==e)return[];var r=t.length;return r>1&&Ea(e,t[0],t[1])?t=[]:r>2&&Ea(t[0],t[1],t[2])&&(t=[t[0]]),Go(e,go(t,1),[])})),Oi=lt||function(){return ut.Date.now()};function Ai(e,t,r){return t=r?n:t,t=e&&null==t?e.length:t,Jn(e,l,n,n,n,n,t)}function Mi(e,t){var r;if("function"!=typeof t)throw new Oe(a);return e=ms(e),function(){return--e>0&&(r=t.apply(this,arguments)),e<=1&&(t=n),r}}var wi=Yo((function(e,t,r){var o=1;if(r.length){var n=sr(r,ia(wi));o|=p}return Jn(e,o,t,r,n)})),Ri=Yo((function(e,t,r){var o=3;if(r.length){var n=sr(r,ia(Ri));o|=p}return Jn(t,o,e,r,n)}));function xi(e,t,r){var o,i,s,p,l,c,u=0,y=!1,d=!1,f=!0;if("function"!=typeof e)throw new Oe(a);function m(t){var r=o,a=i;return o=i=n,u=t,p=e.apply(a,r)}function g(e){return u=e,l=wa(E,t),y?m(e):p}function h(e){var r=e-c;return c===n||r>=t||r<0||d&&e-u>=s}function E(){var e=Oi();if(h(e))return T(e);l=wa(E,function(e){var r=t-(e-c);return d?hr(r,s-(e-u)):r}(e))}function T(e){return l=n,f&&o?m(e):(o=i=n,p)}function S(){var e=Oi(),r=h(e);if(o=arguments,i=this,c=e,r){if(l===n)return g(c);if(d)return Pn(l),l=wa(E,t),m(c)}return l===n&&(l=wa(E,t)),p}return t=hs(t)||0,ts(r)&&(y=!!r.leading,s=(d="maxWait"in r)?gr(hs(r.maxWait)||0,t):s,f="trailing"in r?!!r.trailing:f),S.cancel=function(){l!==n&&Pn(l),u=0,o=c=i=l=n},S.flush=function(){return l===n?p:T(Oi())},S}var Li=Yo((function(e,t){return po(e,1,t)})),Ii=Yo((function(e,t,r){return po(e,hs(t)||0,r)}));function Fi(e,t){if("function"!=typeof e||null!=t&&"function"!=typeof t)throw new Oe(a);var r=function(){var o=arguments,n=t?t.apply(this,o):o[0],a=r.cache;if(a.has(n))return a.get(n);var i=e.apply(this,o);return r.cache=a.set(n,i)||a,i};return r.cache=new(Fi.Cache||$r),r}function ki(e){if("function"!=typeof e)throw new Oe(a);return function(){var t=arguments;switch(t.length){case 0:return!e.call(this);case 1:return!e.call(this,t[0]);case 2:return!e.call(this,t[0],t[1]);case 3:return!e.call(this,t[0],t[1],t[2])}return!e.apply(this,t)}}Fi.Cache=$r;var Bi=Tn((function(e,t){var r=(t=1==t.length&&$i(t[0])?Rt(t[0],Xt(sa())):Rt(go(t,1),Xt(sa()))).length;return Yo((function(o){for(var n=-1,a=hr(o.length,r);++n=t})),Wi=wo(function(){return arguments}())?wo:function(e){return rs(e)&&Le.call(e,"callee")&&!qe.call(e,"callee")},$i=o.isArray,qi=ht?Xt(ht):function(e){return rs(e)&&_o(e)==R};function Hi(e){return null!=e&&es(e.length)&&!Qi(e)}function Yi(e){return rs(e)&&Hi(e)}var Xi=gt||hp,Ji=Et?Xt(Et):function(e){return rs(e)&&_o(e)==E};function Ki(e){if(!rs(e))return!1;var t=_o(e);return t==T||"[object DOMException]"==t||"string"==typeof e.message&&"string"==typeof e.name&&!as(e)}function Qi(e){if(!ts(e))return!1;var t=_o(e);return t==S||t==P||"[object AsyncFunction]"==t||"[object Proxy]"==t}function Zi(e){return"number"==typeof e&&e==ms(e)}function es(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=u}function ts(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}function rs(e){return null!=e&&"object"==typeof e}var os=Tt?Xt(Tt):function(e){return rs(e)&&da(e)==v};function ns(e){return"number"==typeof e||rs(e)&&_o(e)==b}function as(e){if(!rs(e)||_o(e)!=_)return!1;var t=We(e);if(null===t)return!0;var r=Le.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&xe.call(r)==Be}var is=St?Xt(St):function(e){return rs(e)&&_o(e)==C},ss=Pt?Xt(Pt):function(e){return rs(e)&&da(e)==O};function ps(e){return"string"==typeof e||!$i(e)&&rs(e)&&_o(e)==A}function ls(e){return"symbol"==typeof e||rs(e)&&_o(e)==M}var cs=vt?Xt(vt):function(e){return rs(e)&&es(e.length)&&!!nt[_o(e)]},us=$n(ko),ys=$n((function(e,t){return e<=t}));function ds(e){if(!e)return[];if(Hi(e))return ps(e)?ur(e):An(e);if(Xe&&e[Xe])return function(e){for(var t,r=[];!(t=e.next()).done;)r.push(t.value);return r}(e[Xe]());var t=da(e);return(t==v?ar:t==O?pr:zs)(e)}function fs(e){return e?(e=hs(e))===c||e===-1/0?17976931348623157e292*(e<0?-1:1):e==e?e:0:0===e?e:0}function ms(e){var t=fs(e),r=t%1;return t==t?r?t-r:t:0}function gs(e){return e?ao(ms(e),0,d):0}function hs(e){if("number"==typeof e)return e;if(ls(e))return y;if(ts(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=ts(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=Yt(e);var r=fe.test(e);return r||ge.test(e)?pt(e.slice(2),r?2:8):de.test(e)?y:+e}function Es(e){return Mn(e,Ls(e))}function Ts(e){return null==e?"":pn(e)}var Ss=Rn((function(e,t){if(va(t)||Hi(t))Mn(t,xs(t),e);else for(var r in t)Le.call(t,r)&&Zr(e,r,t[r])})),Ps=Rn((function(e,t){Mn(t,Ls(t),e)})),vs=Rn((function(e,t,r,o){Mn(t,Ls(t),e,o)})),bs=Rn((function(e,t,r,o){Mn(t,xs(t),e,o)})),_s=ta(no),Ns=Yo((function(e,t){e=_e(e);var r=-1,o=t.length,a=o>2?t[2]:n;for(a&&Ea(t[0],t[1],a)&&(o=1);++r1),t})),Mn(e,oa(e),r),o&&(r=io(r,7,Zn));for(var n=t.length;n--;)cn(r,t[n]);return r})),Bs=ta((function(e,t){return null==e?{}:function(e,t){return jo(e,t,(function(t,r){return As(e,r)}))}(e,t)}));function Ds(e,t){if(null==e)return{};var r=Rt(oa(e),(function(e){return[e]}));return t=sa(t),jo(e,r,(function(e,r){return t(e,r[0])}))}var Us=Xn(xs),Vs=Xn(Ls);function zs(e){return null==e?[]:Jt(e,xs(e))}var Gs=Fn((function(e,t,r){return t=t.toLowerCase(),e+(r?js(t):t)}));function js(e){return Ks(Ts(e).toLowerCase())}function Ws(e){return(e=Ts(e))&&e.replace(Ee,tr).replace(Ke,"")}var $s=Fn((function(e,t,r){return e+(r?"-":"")+t.toLowerCase()})),qs=Fn((function(e,t,r){return e+(r?" ":"")+t.toLowerCase()})),Hs=In("toLowerCase"),Ys=Fn((function(e,t,r){return e+(r?"_":"")+t.toLowerCase()})),Xs=Fn((function(e,t,r){return e+(r?" ":"")+Ks(t)})),Js=Fn((function(e,t,r){return e+(r?" ":"")+t.toUpperCase()})),Ks=In("toUpperCase");function Qs(e,t,r){return e=Ts(e),(t=r?n:t)===n?function(e){return tt.test(e)}(e)?function(e){return e.match(Ze)||[]}(e):function(e){return e.match(pe)||[]}(e):e.match(t)||[]}var Zs=Yo((function(e,t){try{return bt(e,n,t)}catch(e){return Ki(e)?e:new Pe(e)}})),ep=ta((function(e,t){return Nt(t,(function(t){t=Da(t),oo(e,t,wi(e[t],e))})),e}));function tp(e){return function(){return e}}var rp=Dn(),op=Dn(!0);function np(e){return e}function ap(e){return Io("function"==typeof e?e:io(e,1))}var ip=Yo((function(e,t){return function(r){return Mo(r,e,t)}})),sp=Yo((function(e,t){return function(r){return Mo(e,r,t)}}));function pp(e,t,r){var o=xs(t),n=Po(t,o);null!=r||ts(t)&&(n.length||!o.length)||(r=t,t=e,e=this,n=Po(t,xs(t)));var a=!(ts(r)&&"chain"in r&&!r.chain),i=Qi(e);return Nt(n,(function(r){var o=t[r];e[r]=o,i&&(e.prototype[r]=function(){var t=this.__chain__;if(a||t){var r=e(this.__wrapped__),n=r.__actions__=An(this.__actions__);return n.push({func:o,args:arguments,thisArg:e}),r.__chain__=t,r}return o.apply(e,xt([this.value()],arguments))})})),e}function lp(){}var cp=Gn(Rt),up=Gn(Ot),yp=Gn(Ft);function dp(e){return Ta(e)?jt(Da(e)):function(e){return function(t){return vo(t,e)}}(e)}var fp=Wn(),mp=Wn(!0);function gp(){return[]}function hp(){return!1}var Ep,Tp=zn((function(e,t){return e+t}),0),Sp=Hn("ceil"),Pp=zn((function(e,t){return e/t}),1),vp=Hn("floor"),bp=zn((function(e,t){return e*t}),1),_p=Hn("round"),Np=zn((function(e,t){return e-t}),0);return Dr.after=function(e,t){if("function"!=typeof t)throw new Oe(a);return e=ms(e),function(){if(--e<1)return t.apply(this,arguments)}},Dr.ary=Ai,Dr.assign=Ss,Dr.assignIn=Ps,Dr.assignInWith=vs,Dr.assignWith=bs,Dr.at=_s,Dr.before=Mi,Dr.bind=wi,Dr.bindAll=ep,Dr.bindKey=Ri,Dr.castArray=function(){if(!arguments.length)return[];var e=arguments[0];return $i(e)?e:[e]},Dr.chain=di,Dr.chunk=function(e,t,r){t=(r?Ea(e,t,r):t===n)?1:gr(ms(t),0);var a=null==e?0:e.length;if(!a||t<1)return[];for(var i=0,s=0,p=o(yt(a/t));ia?0:a+r),(o=o===n||o>a?a:ms(o))<0&&(o+=a),o=r>o?0:gs(o);r>>0)?(e=Ts(e))&&("string"==typeof t||null!=t&&!is(t))&&!(t=pn(t))&&nr(e)?Sn(ur(e),0,r):e.split(t,r):[]},Dr.spread=function(e,t){if("function"!=typeof e)throw new Oe(a);return t=null==t?0:gr(ms(t),0),Yo((function(r){var o=r[t],n=Sn(r,0,t);return o&&xt(n,o),bt(e,this,n)}))},Dr.tail=function(e){var t=null==e?0:e.length;return t?tn(e,1,t):[]},Dr.take=function(e,t,r){return e&&e.length?tn(e,0,(t=r||t===n?1:ms(t))<0?0:t):[]},Dr.takeRight=function(e,t,r){var o=null==e?0:e.length;return o?tn(e,(t=o-(t=r||t===n?1:ms(t)))<0?0:t,o):[]},Dr.takeRightWhile=function(e,t){return e&&e.length?yn(e,sa(t,3),!1,!0):[]},Dr.takeWhile=function(e,t){return e&&e.length?yn(e,sa(t,3)):[]},Dr.tap=function(e,t){return t(e),e},Dr.throttle=function(e,t,r){var o=!0,n=!0;if("function"!=typeof e)throw new Oe(a);return ts(r)&&(o="leading"in r?!!r.leading:o,n="trailing"in r?!!r.trailing:n),xi(e,t,{leading:o,maxWait:t,trailing:n})},Dr.thru=fi,Dr.toArray=ds,Dr.toPairs=Us,Dr.toPairsIn=Vs,Dr.toPath=function(e){return $i(e)?Rt(e,Da):ls(e)?[e]:An(Ba(Ts(e)))},Dr.toPlainObject=Es,Dr.transform=function(e,t,r){var o=$i(e),n=o||Xi(e)||cs(e);if(t=sa(t,4),null==r){var a=e&&e.constructor;r=n?o?new a:[]:ts(e)&&Qi(a)?Ur(We(e)):{}}return(n?Nt:To)(e,(function(e,o,n){return t(r,e,o,n)})),r},Dr.unary=function(e){return Ai(e,1)},Dr.union=ri,Dr.unionBy=oi,Dr.unionWith=ni,Dr.uniq=function(e){return e&&e.length?ln(e):[]},Dr.uniqBy=function(e,t){return e&&e.length?ln(e,sa(t,2)):[]},Dr.uniqWith=function(e,t){return t="function"==typeof t?t:n,e&&e.length?ln(e,n,t):[]},Dr.unset=function(e,t){return null==e||cn(e,t)},Dr.unzip=ai,Dr.unzipWith=ii,Dr.update=function(e,t,r){return null==e?e:un(e,t,hn(r))},Dr.updateWith=function(e,t,r,o){return o="function"==typeof o?o:n,null==e?e:un(e,t,hn(r),o)},Dr.values=zs,Dr.valuesIn=function(e){return null==e?[]:Jt(e,Ls(e))},Dr.without=si,Dr.words=Qs,Dr.wrap=function(e,t){return Di(hn(t),e)},Dr.xor=pi,Dr.xorBy=li,Dr.xorWith=ci,Dr.zip=ui,Dr.zipObject=function(e,t){return mn(e||[],t||[],Zr)},Dr.zipObjectDeep=function(e,t){return mn(e||[],t||[],Ko)},Dr.zipWith=yi,Dr.entries=Us,Dr.entriesIn=Vs,Dr.extend=Ps,Dr.extendWith=vs,pp(Dr,Dr),Dr.add=Tp,Dr.attempt=Zs,Dr.camelCase=Gs,Dr.capitalize=js,Dr.ceil=Sp,Dr.clamp=function(e,t,r){return r===n&&(r=t,t=n),r!==n&&(r=(r=hs(r))==r?r:0),t!==n&&(t=(t=hs(t))==t?t:0),ao(hs(e),t,r)},Dr.clone=function(e){return io(e,4)},Dr.cloneDeep=function(e){return io(e,5)},Dr.cloneDeepWith=function(e,t){return io(e,5,t="function"==typeof t?t:n)},Dr.cloneWith=function(e,t){return io(e,4,t="function"==typeof t?t:n)},Dr.conformsTo=function(e,t){return null==t||so(e,t,xs(t))},Dr.deburr=Ws,Dr.defaultTo=function(e,t){return null==e||e!=e?t:e},Dr.divide=Pp,Dr.endsWith=function(e,t,r){e=Ts(e),t=pn(t);var o=e.length,a=r=r===n?o:ao(ms(r),0,o);return(r-=t.length)>=0&&e.slice(r,a)==t},Dr.eq=zi,Dr.escape=function(e){return(e=Ts(e))&&Y.test(e)?e.replace(q,rr):e},Dr.escapeRegExp=function(e){return(e=Ts(e))&&re.test(e)?e.replace(te,"\\$&"):e},Dr.every=function(e,t,r){var o=$i(e)?Ot:yo;return r&&Ea(e,t,r)&&(t=n),o(e,sa(t,3))},Dr.find=hi,Dr.findIndex=Wa,Dr.findKey=function(e,t){return Bt(e,sa(t,3),To)},Dr.findLast=Ei,Dr.findLastIndex=$a,Dr.findLastKey=function(e,t){return Bt(e,sa(t,3),So)},Dr.floor=vp,Dr.forEach=Ti,Dr.forEachRight=Si,Dr.forIn=function(e,t){return null==e?e:ho(e,sa(t,3),Ls)},Dr.forInRight=function(e,t){return null==e?e:Eo(e,sa(t,3),Ls)},Dr.forOwn=function(e,t){return e&&To(e,sa(t,3))},Dr.forOwnRight=function(e,t){return e&&So(e,sa(t,3))},Dr.get=Os,Dr.gt=Gi,Dr.gte=ji,Dr.has=function(e,t){return null!=e&&fa(e,t,Co)},Dr.hasIn=As,Dr.head=Ha,Dr.identity=np,Dr.includes=function(e,t,r,o){e=Hi(e)?e:zs(e),r=r&&!o?ms(r):0;var n=e.length;return r<0&&(r=gr(n+r,0)),ps(e)?r<=n&&e.indexOf(t,r)>-1:!!n&&Ut(e,t,r)>-1},Dr.indexOf=function(e,t,r){var o=null==e?0:e.length;if(!o)return-1;var n=null==r?0:ms(r);return n<0&&(n=gr(o+n,0)),Ut(e,t,n)},Dr.inRange=function(e,t,r){return t=fs(t),r===n?(r=t,t=0):r=fs(r),function(e,t,r){return e>=hr(t,r)&&e=-9007199254740991&&e<=u},Dr.isSet=ss,Dr.isString=ps,Dr.isSymbol=ls,Dr.isTypedArray=cs,Dr.isUndefined=function(e){return e===n},Dr.isWeakMap=function(e){return rs(e)&&da(e)==w},Dr.isWeakSet=function(e){return rs(e)&&"[object WeakSet]"==_o(e)},Dr.join=function(e,t){return null==e?"":Wt.call(e,t)},Dr.kebabCase=$s,Dr.last=Ka,Dr.lastIndexOf=function(e,t,r){var o=null==e?0:e.length;if(!o)return-1;var a=o;return r!==n&&(a=(a=ms(r))<0?gr(o+a,0):hr(a,o-1)),t==t?function(e,t,r){for(var o=r+1;o--;)if(e[o]===t)return o;return o}(e,t,a):Dt(e,zt,a,!0)},Dr.lowerCase=qs,Dr.lowerFirst=Hs,Dr.lt=us,Dr.lte=ys,Dr.max=function(e){return e&&e.length?fo(e,np,No):n},Dr.maxBy=function(e,t){return e&&e.length?fo(e,sa(t,2),No):n},Dr.mean=function(e){return Gt(e,np)},Dr.meanBy=function(e,t){return Gt(e,sa(t,2))},Dr.min=function(e){return e&&e.length?fo(e,np,ko):n},Dr.minBy=function(e,t){return e&&e.length?fo(e,sa(t,2),ko):n},Dr.stubArray=gp,Dr.stubFalse=hp,Dr.stubObject=function(){return{}},Dr.stubString=function(){return""},Dr.stubTrue=function(){return!0},Dr.multiply=bp,Dr.nth=function(e,t){return e&&e.length?zo(e,ms(t)):n},Dr.noConflict=function(){return ut._===this&&(ut._=De),this},Dr.noop=lp,Dr.now=Oi,Dr.pad=function(e,t,r){e=Ts(e);var o=(t=ms(t))?cr(e):0;if(!t||o>=t)return e;var n=(t-o)/2;return jn(dt(n),r)+e+jn(yt(n),r)},Dr.padEnd=function(e,t,r){e=Ts(e);var o=(t=ms(t))?cr(e):0;return t&&ot){var o=e;e=t,t=o}if(r||e%1||t%1){var a=Sr();return hr(e+a*(t-e+st("1e-"+((a+"").length-1))),t)}return qo(e,t)},Dr.reduce=function(e,t,r){var o=$i(e)?Lt:$t,n=arguments.length<3;return o(e,sa(t,4),r,n,co)},Dr.reduceRight=function(e,t,r){var o=$i(e)?It:$t,n=arguments.length<3;return o(e,sa(t,4),r,n,uo)},Dr.repeat=function(e,t,r){return t=(r?Ea(e,t,r):t===n)?1:ms(t),Ho(Ts(e),t)},Dr.replace=function(){var e=arguments,t=Ts(e[0]);return e.length<3?t:t.replace(e[1],e[2])},Dr.result=function(e,t,r){var o=-1,a=(t=En(t,e)).length;for(a||(a=1,e=n);++ou)return[];var r=d,o=hr(e,d);t=sa(t),e-=d;for(var n=Ht(o,t);++r=i)return e;var p=r-cr(o);if(p<1)return o;var l=s?Sn(s,0,p).join(""):e.slice(0,p);if(a===n)return l+o;if(s&&(p+=l.length-p),is(a)){if(e.slice(p).search(a)){var c,u=l;for(a.global||(a=Ne(a.source,Ts(ye.exec(a))+"g")),a.lastIndex=0;c=a.exec(u);)var y=c.index;l=l.slice(0,y===n?p:y)}}else if(e.indexOf(pn(a),p)!=p){var d=l.lastIndexOf(a);d>-1&&(l=l.slice(0,d))}return l+o},Dr.unescape=function(e){return(e=Ts(e))&&H.test(e)?e.replace($,dr):e},Dr.uniqueId=function(e){var t=++Ie;return Ts(e)+t},Dr.upperCase=Js,Dr.upperFirst=Ks,Dr.each=Ti,Dr.eachRight=Si,Dr.first=Ha,pp(Dr,(Ep={},To(Dr,(function(e,t){Le.call(Dr.prototype,t)||(Ep[t]=e)})),Ep),{chain:!1}),Dr.VERSION="4.17.21",Nt(["bind","bindKey","curry","curryRight","partial","partialRight"],(function(e){Dr[e].placeholder=Dr})),Nt(["drop","take"],(function(e,t){Gr.prototype[e]=function(r){r=r===n?1:gr(ms(r),0);var o=this.__filtered__&&!t?new Gr(this):this.clone();return o.__filtered__?o.__takeCount__=hr(r,o.__takeCount__):o.__views__.push({size:hr(r,d),type:e+(o.__dir__<0?"Right":"")}),o},Gr.prototype[e+"Right"]=function(t){return this.reverse()[e](t).reverse()}})),Nt(["filter","map","takeWhile"],(function(e,t){var r=t+1,o=1==r||3==r;Gr.prototype[e]=function(e){var t=this.clone();return t.__iteratees__.push({iteratee:sa(e,3),type:r}),t.__filtered__=t.__filtered__||o,t}})),Nt(["head","last"],(function(e,t){var r="take"+(t?"Right":"");Gr.prototype[e]=function(){return this[r](1).value()[0]}})),Nt(["initial","tail"],(function(e,t){var r="drop"+(t?"":"Right");Gr.prototype[e]=function(){return this.__filtered__?new Gr(this):this[r](1)}})),Gr.prototype.compact=function(){return this.filter(np)},Gr.prototype.find=function(e){return this.filter(e).head()},Gr.prototype.findLast=function(e){return this.reverse().find(e)},Gr.prototype.invokeMap=Yo((function(e,t){return"function"==typeof e?new Gr(this):this.map((function(r){return Mo(r,e,t)}))})),Gr.prototype.reject=function(e){return this.filter(ki(sa(e)))},Gr.prototype.slice=function(e,t){e=ms(e);var r=this;return r.__filtered__&&(e>0||t<0)?new Gr(r):(e<0?r=r.takeRight(-e):e&&(r=r.drop(e)),t!==n&&(r=(t=ms(t))<0?r.dropRight(-t):r.take(t-e)),r)},Gr.prototype.takeRightWhile=function(e){return this.reverse().takeWhile(e).reverse()},Gr.prototype.toArray=function(){return this.take(d)},To(Gr.prototype,(function(e,t){var r=/^(?:filter|find|map|reject)|While$/.test(t),o=/^(?:head|last)$/.test(t),a=Dr[o?"take"+("last"==t?"Right":""):t],i=o||/^find/.test(t);a&&(Dr.prototype[t]=function(){var t=this.__wrapped__,s=o?[1]:arguments,p=t instanceof Gr,l=s[0],c=p||$i(t),u=function(e){var t=a.apply(Dr,xt([e],s));return o&&y?t[0]:t};c&&r&&"function"==typeof l&&1!=l.length&&(p=c=!1);var y=this.__chain__,d=!!this.__actions__.length,f=i&&!y,m=p&&!d;if(!i&&c){t=m?t:new Gr(this);var g=e.apply(t,s);return g.__actions__.push({func:fi,args:[u],thisArg:n}),new zr(g,y)}return f&&m?e.apply(this,s):(g=this.thru(u),f?o?g.value()[0]:g.value():g)})})),Nt(["pop","push","shift","sort","splice","unshift"],(function(e){var t=Ae[e],r=/^(?:push|sort|unshift)$/.test(e)?"tap":"thru",o=/^(?:pop|shift)$/.test(e);Dr.prototype[e]=function(){var e=arguments;if(o&&!this.__chain__){var n=this.value();return t.apply($i(n)?n:[],e)}return this[r]((function(r){return t.apply($i(r)?r:[],e)}))}})),To(Gr.prototype,(function(e,t){var r=Dr[t];if(r){var o=r.name+"";Le.call(Mr,o)||(Mr[o]=[]),Mr[o].push({name:t,func:r})}})),Mr[Un(n,2).name]=[{name:"wrapper",func:n}],Gr.prototype.clone=function(){var e=new Gr(this.__wrapped__);return e.__actions__=An(this.__actions__),e.__dir__=this.__dir__,e.__filtered__=this.__filtered__,e.__iteratees__=An(this.__iteratees__),e.__takeCount__=this.__takeCount__,e.__views__=An(this.__views__),e},Gr.prototype.reverse=function(){if(this.__filtered__){var e=new Gr(this);e.__dir__=-1,e.__filtered__=!0}else(e=this.clone()).__dir__*=-1;return e},Gr.prototype.value=function(){var e=this.__wrapped__.value(),t=this.__dir__,r=$i(e),o=t<0,n=r?e.length:0,a=function(e,t,r){for(var o=-1,n=r.length;++o=this.__values__.length;return{done:e,value:e?n:this.__values__[this.__index__++]}},Dr.prototype.plant=function(e){for(var t,r=this;r instanceof Vr;){var o=Va(r);o.__index__=0,o.__values__=n,t?a.__wrapped__=o:t=o;var a=o;r=r.__wrapped__}return a.__wrapped__=e,t},Dr.prototype.reverse=function(){var e=this.__wrapped__;if(e instanceof Gr){var t=e;return this.__actions__.length&&(t=new Gr(this)),(t=t.reverse()).__actions__.push({func:fi,args:[ti],thisArg:n}),new zr(t,this.__chain__)}return this.thru(ti)},Dr.prototype.toJSON=Dr.prototype.valueOf=Dr.prototype.value=function(){return dn(this.__wrapped__,this.__actions__)},Dr.prototype.first=Dr.prototype.head,Xe&&(Dr.prototype[Xe]=function(){return this}),Dr}();ut._=fr,(o=function(){return fr}.call(t,r,t,e))===n||(e.exports=o)}.call(this)},6483:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseSourceCode=t.visualVersion=void 0;const o=r(7977),n=r(2891),a=r(3784);t.visualVersion=12,t.parseSourceCode=function(e,r){var i;try{(0,o.deserialize)(e);const a=(0,n.getInstance)().document.VisualVersion,i=/^([1-9]+[0-9]*)$/;if(void 0===a)r.errorType="versionError";else{const e=a.match(i);(null===e||parseInt(e[1])>t.visualVersion)&&(r.errorType="versionError")}}catch(e){r.errorType="fileError"}""!==r.errorType&&(r.errorMessage=null!==(i=a.errorMap.get(r.errorType))&&void 0!==i?i:"Codegen visual file failed")}},904:(e,t)=>{"use strict";var r;let o;Object.defineProperty(t,"__esModule",{value:!0}),t.setDomain=t.getDomain=t.Domain=void 0,function(e){e[e.FA=0]="FA",e[e.FORM=1]="FORM",e[e.ETS=2]="ETS"}(r||(r={})),t.Domain=r,t.setDomain=e=>{o=e},t.getDomain=()=>null!=o?o:r.FA},3784:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.errorMap=void 0,t.errorMap=new Map([["fileError","Visual file is damaged"],["versionError","Version number of visual file does not match"],["modelError","Visual model in visual file is damaged"],["codegenError","Codegen visual file failed"]])},4117:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ASTNode=void 0,t.ASTNode=class{accept(e){return e.visit(this)}}},1862:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Cache=void 0,t.Cache=class{constructor(e,t=0){this.value="",this.indent=t,this.flag=!0,this.INDENT=e}indentOn(){this.flag=!0}indentOff(){this.flag=!1}incIndent(){this.indent++}decIndent(){this.indent--}checkIndent(){return this.indent<0}getIndents(){if(this.flag){let e="";for(let t=0;t{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Tag=void 0;const o=r(4117);class n extends o.ASTNode{constructor(e,t,r,o,n){super(),this.builders=new Map,this.defaultValue=new Map,this.mediaParams=new Map,this.mediaProperties=new Map,this.mediaKeyProperty=new Map,this.tagName=e,this.params=t,this.content=r,this.properties=o,this.forEachObj=n,this.ifBoolean=null,this.isCustomTag=!1}setMediaParams(e){this.mediaParams=e}setParams(e){this.params=e}setIfBoolean(e){this.ifBoolean=e}setTagName(e){this.tagName=e}setForEachObj(e){this.forEachObj=e}setMediaProperty(e,t){t.forEach(((t,r)=>{var o;this.mediaKeyProperty.has(r)||this.mediaKeyProperty.set(r,new Map),null===(o=this.mediaKeyProperty.get(r))||void 0===o||o.set(e,t)}))}setDefaultValue(e,t,r="undefined",o=""){this.defaultValue.set(e,[r,t,o])}}t.Tag=n},5623:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ASTNodeGenerator=void 0;const o=r(9519),n=r(1862),a=r(5051),i=r(4294),s=r(6486),p=r(9459);class l{constructor(e){this.cache=e,this.etsImport=new n.Cache(" ",0),this.etsVariable=new n.Cache(" ",1),this.etsFunction=new n.Cache(" ",1),this.etsBuilder=new n.Cache(" ",1),this.aboutToAppear=new n.Cache(" ",2),this.needMediaQuery=!0,this.customComponents=new Set}visit(e){e instanceof o.Tag&&(e.isCustomTag?this.genCustomTag(e):(this.needMediaQuery&&this.genMediaQuery(e),this.genTag(e)))}static getMethodGen(e){return void 0===l.instance?l.instance=new l(e):l.instance.setCache(e),l.instance}setCache(e){this.cache=e,this.etsImport=new n.Cache(" ",0),this.etsVariable=new n.Cache(" ",1),this.etsFunction=new n.Cache(" ",1),this.etsBuilder=new n.Cache(" ",1),this.aboutToAppear=new n.Cache(" ",2),this.needMediaQuery=!0,this.customComponents=new Set}genParams(e){const t=this.getParams(e);this.isCustomComponent(e)?this.genCustomParams(t):this.genCommonParams(t)}genCommonParams(e){if("string"==typeof e)this.cache.concat(e);else if(e.size>0){this.cache.concat(a.TokenClass.LBRA,a.TokenClass.SPACE);let t=0;e.forEach(((r,o)=>{this.cache.concat(o,a.TokenClass.COLON,a.TokenClass.SPACE,r),t++,t{this.cache.indentOff(),this.cache.concat(a.TokenClass.NEW_LINE),this.cache.indentOn(),this.cache.concat(t,a.TokenClass.COLON,a.TokenClass.SPACE,e,a.TokenClass.COMMA)})),this.cache.indentOff(),this.cache.concat(a.TokenClass.NEW_LINE),this.cache.indentOn(),this.cache.decIndent(),this.cache.concat(a.TokenClass.RBRA),this.cache.indentOff())}genObjectProperty(e){let t=0;this.cache.concat(a.TokenClass.LBRA,a.TokenClass.SPACE),e.forEach(((r,o)=>{this.cache.concat(o,a.TokenClass.COLON,a.TokenClass.SPACE,r),t++,t{e.accept(this),this.cache.indentOff(),this.cache.concat(a.TokenClass.NEW_LINE),this.cache.indentOn()})),this.cache.decIndent(),this.cache.indentOn()),this.cache.indentOn(),this.cache.concat(a.TokenClass.RBRA)),(null!==e.properties||null!==e.mediaProperties)&&(null!==e.content&&0!==e.content.length||this.cache.incIndent(),this.getProperties(e).forEach(((e,t)=>{this.cache.concat(a.TokenClass.NEW_LINE),this.cache.indentOn(),this.cache.concat(a.TokenClass.PROPERTY_START,t,a.TokenClass.TAG_START),this.cache.indentOff(),"string"==typeof e?this.cache.concat(e,a.TokenClass.TAG_END):this.genObjectProperty(e)})),null!==e.content&&0!==e.content.length||this.cache.decIndent()),this.genEnd(e),this.genBuildersFunction(e)}genStart(e){this.genIfStart(e),this.genForTagStart(e),this.genCustomImport(e)}genEnd(e){this.genForTagEnd(e),this.genIfEnd(e)}genForTagStart(e){var t;void 0!==(null===(t=e.forEachObj)||void 0===t?void 0:t.for)&&(this.cache.concat("ForEach",a.TokenClass.TAG_START,e.forEachObj.for.toString(),a.TokenClass.COMMA,a.TokenClass.NEW_LINE),this.cache.concat(a.TokenClass.TAG_START,e.forEachObj.item,a.TokenClass.COLON," any",a.TokenClass.COMMA," ",e.forEachObj.idx,a.TokenClass.COLON," number",a.TokenClass.TAG_END," => ",a.TokenClass.LBRA,a.TokenClass.NEW_LINE))}genForTagEnd(e){null!==e.forEachObj&&(this.cache.concat(a.TokenClass.RBRA),void 0!==e.forEachObj.key&&""!==e.forEachObj.key&&(this.cache.concat(a.TokenClass.COMMA,a.TokenClass.NEW_LINE),this.cache.indentOn(),this.cache.concat(a.TokenClass.TAG_START,e.forEachObj.item,a.TokenClass.COLON," any",a.TokenClass.COMMA," ",e.forEachObj.idx,a.TokenClass.COLON," number",a.TokenClass.TAG_END," => ",a.TokenClass.LBRA,a.TokenClass.NEW_LINE),this.cache.concat("return ",e.forEachObj.key.toString(),a.TokenClass.TAG_START,e.forEachObj.item,a.TokenClass.COMMA," ",e.forEachObj.idx,a.TokenClass.TAG_END,a.TokenClass.RBRA),this.cache.indentOff()),this.cache.concat(a.TokenClass.TAG_END))}genIfStart(e){null!==e.ifBoolean&&(this.cache.concat("if",a.TokenClass.SPACE,a.TokenClass.TAG_START,e.ifBoolean.toString(),a.TokenClass.TAG_END,a.TokenClass.SPACE,a.TokenClass.LBRA,a.TokenClass.NEW_LINE),this.cache.incIndent())}genIfEnd(e){null!==e.ifBoolean&&(this.cache.indentOn(),this.cache.decIndent(),this.cache.concat(a.TokenClass.NEW_LINE),this.cache.concat(a.TokenClass.RBRA),this.cache.indentOff())}genMediaQuery(e){const t=new Map,r=new Map;if(this.collectMediaQueryMap(e,t),this.collectDefaultValueMap(e,r),0===t.size&&0===r.size)return;const o=(0,i.getUniqueName)("mediaQuery"),s=(0,i.getUniqueName)("initForMediaQuery"),p=(0,i.getUniqueName)("mediaQueryCb"),l=(0,i.getUniqueName)("saveMediaQueryResult"),c=(0,i.getUniqueName)("updateForMediaQuery"),u=new n.Cache(a.TokenClass.INDENT,1),y=new n.Cache(a.TokenClass.INDENT,1),d=new n.Cache(a.TokenClass.INDENT,1),f=new n.Cache(a.TokenClass.INDENT,1),m=new n.Cache(a.TokenClass.INDENT,1),g=new n.Cache(a.TokenClass.INDENT,1),h=new n.Cache(a.TokenClass.INDENT,1),E=new n.Cache(a.TokenClass.INDENT,2);this.genVariableDeclare(r,u,a.TokenClass.UNDEFINED),this.genMediaQueryCb(p,y),this.genMediaQueryListener(t,d,f),this.genInitFuc(s,r,m),this.genMediaQueryCbFnc(l,c,t,g),this.genUpdateFnc(c,s,t,h),this.genAboutToAppear(p,l,t,E),this.etsImport.indentOff(),this.aboutToAppear.indentOff(),this.etsVariable.indentOff(),this.etsFunction.indentOff(),this.etsImport.indentOff(),this.etsImport.concat("import ",o," from '@ohos.mediaquery'",a.TokenClass.NEW_LINE),this.aboutToAppear.concat(E.toString()),this.etsVariable.concat(u.toString(),y.toString(),d.toString(),f.toString()),this.etsFunction.concat(g.toString(),a.TokenClass.NEW_LINE,m.toString(),a.TokenClass.NEW_LINE,h.toString()),this.etsImport.indentOn(),this.aboutToAppear.indentOn(),this.etsVariable.indentOn(),this.etsFunction.indentOn(),this.needMediaQuery=!1}genBuildersFunction(e){e.builders.forEach(((e,t)=>{this.etsBuilder.indentOff(),this.etsBuilder.concat(a.TokenClass.NEW_LINE),this.etsBuilder.indentOn(),this.etsBuilder.concat(a.TokenClass.DECORATOR_Builder,a.TokenClass.SPACE,t,a.TokenClass.TAG_START,a.TokenClass.TAG_END),this.etsBuilder.indentOff();const r=(0,p.genBuilderEts)(e);this.etsBuilder.concat(a.TokenClass.SPACE,a.TokenClass.LBRA,a.TokenClass.NEW_LINE),this.etsBuilder.indentOn(),this.etsBuilder.concat(r.cache.toString(),a.TokenClass.NEW_LINE),this.etsBuilder.concat(a.TokenClass.RBRA,a.TokenClass.NEW_LINE),this.etsBuilder.indentOff(),this.etsBuilder.concat(r.etsBuilder.toString())}))}genCustomTag(e){this.genVariableDeclare(e.defaultValue,this.cache)}genVariableDeclare(e,t,r){t.indentOn(),e.forEach(((e,o)=>{const n=e[2];""!==n&&(t.concat(n,a.TokenClass.SPACE),t.indentOff()),t.concat(o.slice(5),a.TokenClass.COLON,a.TokenClass.SPACE,e[1]),t.indentOff();const i=null!=r?r:e[0];null!=i&&t.concat(a.TokenClass.SPACE,a.TokenClass.ASSIGN,a.TokenClass.SPACE,i),t.concat(a.TokenClass.NEW_LINE),t.indentOn()}))}genMediaQueryCb(e,t){t.concat(e,a.TokenClass.SPACE,a.TokenClass.ASSIGN,a.TokenClass.SPACE,a.TokenClass.NULL,a.TokenClass.NEW_LINE)}genMediaQueryListener(e,t,r){const o=(0,i.getUniqueName)("mediaQuery");e.forEach(((e,n)=>{const s=(0,i.getUniqueName)(this.getMediaQueryVariableName(n));t.concat(s,a.TokenClass.COLON,a.TokenClass.SPACE,a.TokenClass.BOOLEAN,a.TokenClass.SPACE,a.TokenClass.ASSIGN,a.TokenClass.SPACE,a.TokenClass.FALSE,a.TokenClass.NEW_LINE),r.concat(`listener_${s}`,a.TokenClass.SPACE,a.TokenClass.ASSIGN,a.TokenClass.SPACE,o,a.TokenClass.PROPERTY_START,"matchMediaSync",a.TokenClass.TAG_START,`'${n}'`,a.TokenClass.TAG_END,a.TokenClass.NEW_LINE)}))}genInitFuc(e,t,r){r.concat(e,a.TokenClass.TAG_START,a.TokenClass.TAG_END,a.TokenClass.SPACE,a.TokenClass.LBRA,a.TokenClass.NEW_LINE),r.indentOn(),r.incIndent(),t.forEach(((e,t)=>{r.concat(t,a.TokenClass.SPACE,a.TokenClass.ASSIGN,a.TokenClass.SPACE,e[0],a.TokenClass.NEW_LINE)})),r.decIndent(),r.concat(a.TokenClass.RBRA,a.TokenClass.NEW_LINE)}genMediaQueryCbFnc(e,t,r,o){const n=Array.from(r.entries()),s="mediaQueryResult";o.concat(e,a.TokenClass.TAG_START,s,a.TokenClass.TAG_END,a.TokenClass.SPACE,a.TokenClass.LBRA,a.TokenClass.NEW_LINE),o.incIndent(),o.concat(a.TokenClass.SWITCH,a.TokenClass.SPACE,a.TokenClass.TAG_START,`${s}.media`,a.TokenClass.TAG_END,a.TokenClass.SPACE,a.TokenClass.LBRA,a.TokenClass.NEW_LINE),o.incIndent();for(let e=0;e{const r=(0,i.getUniqueName)(this.getMediaQueryVariableName(t));o.concat(a.TokenClass.IF,a.TokenClass.SPACE,a.TokenClass.TAG_START,a.TokenClass.THIS,a.TokenClass.PROPERTY_START,r,a.TokenClass.TAG_END,a.TokenClass.SPACE,a.TokenClass.LBRA,a.TokenClass.NEW_LINE),o.incIndent(),e.forEach(((e,t)=>{o.concat(t,a.TokenClass.SPACE,a.TokenClass.ASSIGN,a.TokenClass.SPACE,e,a.TokenClass.NEW_LINE)})),o.decIndent(),o.concat(a.TokenClass.RBRA,a.TokenClass.NEW_LINE)})),o.decIndent(),o.concat(a.TokenClass.RBRA,a.TokenClass.NEW_LINE)}genAboutToAppear(e,t,r,o){let n=1;o.concat(a.TokenClass.THIS,a.TokenClass.PROPERTY_START,e,a.TokenClass.SPACE,a.TokenClass.ASSIGN,a.TokenClass.SPACE,a.TokenClass.THIS,a.TokenClass.PROPERTY_START,`${t}.bind(this)`,a.TokenClass.NEW_LINE),r.forEach(((t,s)=>{const p=`listener_${(0,i.getUniqueName)(this.getMediaQueryVariableName(s))}`;o.indentOn(),o.concat(a.TokenClass.THIS,a.TokenClass.PROPERTY_START,p,a.TokenClass.PROPERTY_START,`on('change', this.${e})`),n0&&e.mediaParams.forEach(((e,r)=>{t.set(r,e)})),t}getProperties(e){const t=new Map;return e.properties.forEach(((e,r)=>{t.set(r,e)})),e.mediaProperties.forEach(((e,r)=>{t.set(r,e)})),t}collectDefaultValueMap(e,t){void 0!==e.defaultValue&&e.defaultValue.forEach(((e,r)=>{t.set(r,e)})),null!==e.content&&0!==e.content.length&&e.content.forEach((e=>{this.collectDefaultValueMap(e,t)}))}collectMediaQueryMap(e,t){void 0!==e.mediaKeyProperty&&e.mediaKeyProperty.forEach(((e,r)=>{var o;const n=null!==(o=t.get(r))&&void 0!==o?o:new Map;e.forEach(((e,t)=>{n.set(t,e)})),t.set(r,n)})),null!==e.content&&0!==e.content.length&&e.content.forEach((e=>{this.collectMediaQueryMap(e,t)}))}getMediaQueryVariableName(e){const t="device-type: ",r="orientation: ",o=e.substring(e.indexOf(t),e.length),n=o.substring(t.length,o.indexOf(")")),a=e.substring(e.indexOf(r),e.length),i=a.substring(r.length,a.indexOf(")"));return`${n}${i.slice(0,1).toUpperCase()+i.slice(1).toLowerCase()}`}}t.ASTNodeGenerator=l,l.instance=void 0},8413:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ETSBridge=void 0;const o=r(9519),n=r(1912),a=r(3729),i=r(6125),s=r(366),p=r(7893);t.ETSBridge=class{constructor(){this.errors=0}error(e){console.error("Code generating error: "+e),this.errors+=1}getErrorCount(){return this.errors}visit(e){const t=new Map;let r=null;const l=new Map,c=new o.Tag(e.type,t,r,l,null);if((0,n.parseVisualModel)(e,c),(0,a.parseMediaVisualModel)(e,c),(0,i.parseCustomVisualModel)(e,c),(0,s.parseCustomMediaVisualModel)(e,c),(0,p.parseBuildersVisualModel)(e,c,this),e.children.length>0){r=[];for(const t of e.children)r.push(t.accept(this))}return c.content=r,c}}},9459:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.genBuilderEts=t.genCustomEts=t.genETS=t.EMPTY=void 0;const o=r(5623),n=r(1862);t.EMPTY={build:"",etsImport:"",etsVariable:"",etsFunction:"",aboutToAppear:""},t.genETS=function(e){const t=o.ASTNodeGenerator.getMethodGen(new n.Cache(" ",2));return e.accept(t),{build:t.cache.toString(),etsImport:t.etsImport.toString(),etsVariable:t.etsVariable.toString(),etsFunction:t.etsFunction.toString().concat(t.etsBuilder.toString()),aboutToAppear:t.aboutToAppear.toString()}},t.genCustomEts=function(e){const t=o.ASTNodeGenerator.getMethodGen(new n.Cache(" ",1));return e.accept(t),t.cache.toString()},t.genBuilderEts=function(e){const t=new o.ASTNodeGenerator(new n.Cache(" ",1));return e.accept(t),t}},4435:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringWriter=void 0;const o=r(9459);t.StringWriter=class{genETS(e){return(0,o.genETS)(e)}}},5051:(e,t)=>{"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),t.TokenClass=void 0,(r=t.TokenClass||(t.TokenClass={}))[r.IDENTIFIER=0]="IDENTIFIER",r[r.STRING_LITERAL=1]="STRING_LITERAL",r[r.NUMBER=2]="NUMBER",r[r.CHARACTER=3]="CHARACTER",r[r.EOF=4]="EOF",r[r.INVALID=5]="INVALID",r.EMPTY_DATA="empty",r.ASSIGN="=",r.INDENT=" ",r.NEW_LINE="\n",r.CARRIAGE_RETURN="\r",r.SPACE=" ",r.LQUOTE="'",r.RQUOTE="'",r.TAG_START="(",r.TAG_END=")",r.EMPTY_TAG_END="/>",r.END_TAG_START="{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getDynamicValueByDecorator=t.getMediaVariableDecorator=t.getCustomAttrType=t.getCustomAttributeMap=t.setCustomAttribute=void 0;const o=r(2891),n=new Map;function a(){return n}function i(e){var t,r;return null!==(r=null===(t=a().get(e))||void 0===t?void 0:t.decorator)&&void 0!==r?r:"normal"}t.setCustomAttribute=function(e){var t,r;const a=e.type;(null!==(r=null===(t=(0,o.getInstance)().customData)||void 0===t?void 0:t.property.get(a))&&void 0!==r?r:new Map).forEach(((e,t)=>{const r=`${t}-${a.replace(/\//g,"-")}`;n.set(r,e)}))},t.getCustomAttributeMap=a,t.getCustomAttrType=function(e){var t,r;return null!==(r=null===(t=a().get(e))||void 0===t?void 0:t.type)&&void 0!==r?r:""},t.getMediaVariableDecorator=function(e){const t=i(e);let r="";return"@Link"!==t&&"@Prop"!==t||(r="@State"),r},t.getDynamicValueByDecorator=function(e,t){let r=t;return"@Link"===i(e)&&(r=t.replace("this.","$")),r}},6125:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.enumParserMap=t.genCustomEvent=t.parseCustomVisualModel=void 0;const o=r(2891),n=r(3135),a=r(1195),i=r(8122),s=r(1790);function p(e,t){if(!(t.params instanceof Map))return;const r=function(e){var t,r;const n=e.type;return[...null!==(r=null===(t=(0,o.getInstance)().customData)||void 0===t?void 0:t.event.get(n))&&void 0!==r?r:[]]}(e);for(const o of r){const r=e.property.get(o);void 0!==r&&""!==r&&("this"===r.split(".")[0]?t.params.set(o,r+".bind(this)"):t.params.set(o,r))}}t.parseCustomVisualModel=function(e,r){(0,a.setCustomAttribute)(e),(0,a.getCustomAttributeMap)().forEach(((o,n)=>{if(function(e,t){return e.property.has(t)||e.dynamicProperty.has(t)}(e,n)){const a=c.get(o.type);"function"==typeof a&&a(n,e,r);const s=t.enumParserMap.get(o.type);"function"==typeof s&&function(e,t,r,o){if((0,i.dynamicParamParser)(e,t,r))return;const n=t.property.get(e);!(0,i.isEmptyOrUndefined)(n)&&r.params instanceof Map&&r.params.set((0,i.getEtsPropName)(e),o(n))}(n,e,r,s)}})),p(e,r)},t.genCustomEvent=p;const l=(0,i.curry)(i.getEtsEnumValue),c=new Map([["string",i.stringParamParser],["boolean",i.rawDataParamParser],["number",i.rawDataParamParser],["any[]",i.rawDataParamParser],["object",i.rawDataParamParser],["Date",function(e,t,r){(0,i.dateParamParser)(e,(0,i.getEtsPropName)(e),t,r)}]]);t.enumParserMap=new Map([["Alignment",function(e){const t=(0,i.getBackgroundImagePositionEnumValue)(e);return""!==t?t:(0,i.getEtsEnumValue)("Alignment.",e)}],["Direction",l("Direction.")],["ItemAlign",i.dealWithAlignSelf],["BorderStyle",l("BorderStyle.")],["ImageRepeat",i.dealWithBackgroundRepeat],["ImageSize",l("ImageSize.")],["Visibility",l("Visibility.")],["FontStyle",l("FontStyle.")],["FontWeight",i.dealWithFontWeight],["ButtonType",l("ButtonType.")],["Color",l("Color.")],["LineCapStyle",l("LineCapStyle.")],["ImageFit",l("ImageFit.")],["ImageInterpolation",l("ImageInterpolation.")],["ImageRenderMode",l("ImageRenderMode.")],["ProgressStyle",l("ProgressStyle.")],["SliderStyle",l("SliderStyle.")],["TextAlign",l("TextAlign.")],["TextOverflow",l("TextOverflow.")],["TextDecorationType",l("TextDecorationType.")],["TextCase",l("TextCase.")],["HorizontalAlign",s.dealWithColumnAlignItems],["FlexAlign",n.dealWithJustifyAlignContent],["VerticalAlign",s.dealWithRowAlignItems],["FlexDirection",l("FlexDirection.")],["FlexWrap",i.dealWithWrap],["Axis",l("Axis.")],["EdgeEffect",l("EdgeEffect.")],["Sticky",l("Sticky.")],["EnterKeyType",l("EnterKeyType.")],["ToggleType",l("ToggleType.")],["InputType",l("InputType.")],["ScrollDirection",l("ScrollDirection.")],["EdgeEffect",l("EdgeEffect.")],["GridDirection",l("GridDirection.")],["BarState",l("BarState.")],["NavigationTitleMode",l("NavigationTitleMode.")],["CopyOption",l("CopyOption.")],["BarPosition",l("BarPosition.")],["BarMode",l("BarMode.")]])},9223:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.commonMediaParserArray=t.ifParser=t.forEachParser=void 0;const o=r(6282),n=r(8122),a=r(9248),i=(0,n.curry)(((e,t)=>t.hasMediaProperty(e)));function s(e,t,r){var o,a,i,s;const p=null!==(o=e.property.get("left"))&&void 0!==o?o:e.dynamicProperty.get("left"),l=null!==(a=e.property.get("top"))&&void 0!==a?a:e.dynamicProperty.get("top"),c=t.get("left"),u=t.get("top"),y=r.get("left"),d=r.get("top");let f="undefined",m="undefined";return(0,n.isEmptyOrUndefined)(c)&&(0,n.isEmptyOrUndefined)(u)||(f=(0,n.quoteString)(null!==(i=null!=c?c:p)&&void 0!==i?i:"0"),m=(0,n.quoteString)(null!==(s=null!=u?u:l)&&void 0!==s?s:"0")),(0,n.isEmptyOrUndefined)(y)&&(0,n.isEmptyOrUndefined)(d)||(f=null!=y?y:f,m=null!=d?d:m),{leftValue:f,topValue:m}}function p(e,t){e.forEach(((e,r)=>{"undefined"!==e&&t.set(r,"undefined")}))}function l(e,t){var r,o;const a=new Map,i=t.split("-")[0];return(null!==(r=e.mediaProperty)&&void 0!==r?r:new Map).forEach(((r,o)=>{var s,p,l,c;const u=r.get(i),y=null===(p=null===(s=e.dynamicMediaProperty)||void 0===s?void 0:s.get(o))||void 0===p?void 0:p.get(i),d=null!==(c=null!==(l=r.get(t))&&void 0!==l?l:y)&&void 0!==c?c:u;void 0!==d&&a.set(o,(0,n.quoteString)(d))})),(null!==(o=e.dynamicMediaProperty)&&void 0!==o?o:new Map).forEach(((e,r)=>{var o;const n=e.get(i),s=null!==(o=e.get(t))&&void 0!==o?o:n;void 0!==s&&a.set(r,s)})),a}const c=(0,n.curry)(((e,t,r)=>{const a=(0,o.getMediaProperty)(t,e,n.quoteString);if(0===a.size)return;const i=(0,o.getMediaDefaultValue)(t,e,n.quoteString),s=(0,o.getVariableName)(t.id,e);r.setDefaultValue(s,(0,o.getType)(e),i),r.setMediaProperty(s,a),r.mediaProperties.set((0,n.getEtsPropName)(e),s)})),u=(0,n.curry)(((e,t,r)=>{const a=(0,o.getMediaProperty)(t,e);if(0===a.size)return;const i=(0,o.getMediaDefaultValue)(t,e),s=(0,o.getVariableName)(t.id,e);r.setDefaultValue(s,(0,o.getType)(e),i),r.setMediaProperty(s,a),r.mediaProperties.set((0,n.getEtsPropName)(e),s)})),y=(0,n.curry)(((e,t,r)=>{const a=(0,o.getMediaProperty)(t,e);if(0===a.size)return;const i=(0,o.getMediaDefaultValue)(t,e),s=(0,o.getVariableName)(t.id,e);r.setDefaultValue(s,(0,o.getType)(e),i),r.setMediaProperty(s,a),r.mediaProperties.set((0,n.getEtsPropName)(e),s)})),d=(0,n.curry)(((e,t,r,a)=>{const i=(0,o.getMediaProperty)(r,e,(0,n.curry)(n.getEtsEnumValue)(t));if(0===i.size)return;const s=(0,o.getMediaDefaultValue)(r,e,(0,n.curry)(n.getEtsEnumValue)(t)),p=(0,o.getVariableName)(r.id,e);a.setDefaultValue(p,(0,o.getType)(e),s),a.setMediaProperty(p,i),a.mediaProperties.set((0,n.getEtsPropName)(e),p)})),f=(0,n.curry)(((e,t,r)=>{const a=(0,o.getMediaProperty)(t,e,n.dealWithColor);if(0===a.size)return;const i=(0,o.getMediaDefaultValue)(t,e,n.dealWithColor),s=(0,o.getVariableName)(t.id,e);r.setDefaultValue(s,(0,o.getType)(e),i),r.setMediaProperty(s,a),r.mediaProperties.set((0,n.getEtsPropName)(e),s)}));function m(e,t,r,o=!1){(0,n.isEmptyOrUndefined)(t)||r.set(e,o?t:(0,n.quoteString)(t))}t.forEachParser=function(e,t){var r,n,a;const i=null!==(r=e.dynamicProperty.get("for"))&&void 0!==r?r:"[1]",s=null!==(n=e.property.get("item"))&&void 0!==n?n:"item",p=null!==(a=e.property.get("idx"))&&void 0!==a?a:"idx",l=e.dynamicProperty.get("keyGenerator"),c=(0,o.getMediaProperty)(e,"for");if(0===c.size)return;const u=(0,o.getVariableName)(e.id,"for"),y={for:u,key:l,item:s,idx:p};t.setDefaultValue(u,(0,o.getType)("for"),i),t.setMediaProperty(u,c),t.setForEachObj(y)},t.ifParser=function(e,t){const r=(0,o.getMediaProperty)(e,"if");if(0===r.size)return;const n=(0,o.getMediaDefaultValue)(e,"if"),a=(0,o.getVariableName)(e.id,"if");t.setDefaultValue(a,(0,o.getType)("if"),n),t.setMediaProperty(a,r),t.setIfBoolean(a)};const g=(0,n.curry)(((e,t,r)=>{const a=new Map,i=t.property.get(e),s=t.dynamicProperty.get(e),p=null!=s?s:i,c=["top","bottom","left","right"];let u=0;for(const i of c){const s=`${e}-${i}`,c=t.property.get(s),y=t.dynamicProperty.get(s),d=l(t,s);let f=(0,n.isEmptyOrUndefined)(p)?"undefined":(0,n.quoteString)(p);if((0,n.isEmptyOrUndefined)(c)||(f=(0,n.quoteString)(c)),(0,n.isEmptyOrUndefined)(y)||(f=y),d.size>0){const e=(0,o.getVariableName)(t.id,s);r.setDefaultValue(e,(0,o.getType)(s),f),r.setMediaProperty(e,d),m(i,e,a,!0),u++}else m(i,f,a,!0)}u>0&&r.mediaProperties.set(e,a)}));function h(e){const t=e.match(/^ *((0|[1-9][0-9]*)(px|vp|lpx|%))( *$| +((0|[1-9][0-9]*)(px|vp|lpx|%)) *$)/);return null===t?"undefined":void 0!==t[5]?`{ width: ${(0,n.quoteString)(t[1])}, height: ${(0,n.quoteString)(t[5])} }`:`{ width: ${(0,n.quoteString)(t[1])} }`}function E(e,t){var r,o;const a=new Map,i=new Map,s=S(t),p=P(t);return(null!==(r=e.mediaProperty)&&void 0!==r?r:new Map).forEach(((e,r)=>{const o=e.get(t);if(!(0,n.isEmptyOrUndefined)(o)){let e=s(o);e=""!==e?e:"undefined",a.set(r,e),i.set(r,p(o))}})),(null!==(o=e.dynamicMediaProperty)&&void 0!==o?o:new Map).forEach(((e,r)=>{const o=e.get(t);(0,n.isEmptyOrUndefined)(o)||(a.set(r,o),i.set(r,"undefined"))})),{enumValueMap:a,objValueMap:i}}function T(e,t){const r=e.property.get(t),o=e.dynamicProperty.get(t),a=S(t),i=P(t);let s="undefined",p="undefined";if(!(0,n.isEmptyOrUndefined)(r)){const e=a(r);s=""!==e?e:s,p=i(r)}return(0,n.isEmptyOrUndefined)(o)||(s=o,p="undefined"),{enumDefault:s,objDefault:p}}function S(e){return new Map([["background-image-size",n.getBackgroundImageSizeEnumValue],["background-image-position",n.getBackgroundImagePositionEnumValue]]).get(e)}function P(e){return new Map([["background-image-size",h],["background-image-position",v]]).get(e)}function v(e){const t=e.match(/^ *((0|[1-9][0-9]*)(px|vp|lpx|%)) +((0|[1-9][0-9]*)(px|vp|lpx|%)) *$/);return null===t?"undefined":`{ x: ${(0,n.quoteString)(t[1])}, y: ${(0,n.quoteString)(t[4])} }`}const b=(0,n.curry)(((e,t,r,a)=>{const i=(0,n.getBorderDirections)(e),s=new Map;let p=r.property.get(e);(0,n.isEmptyOrUndefined)(p)||(p=t(p));const l=r.dynamicProperty.get(e),c=null!=l?l:p,u=(0,o.getMediaProperty)(r,e,t);let y=0;for(const e of i){const i=(0,n.getEdgeBorderDirection)(e),p=r.property.get(e),l=r.dynamicProperty.get(e),d=(0,o.getMediaProperty)(r,e,t);let f=(0,n.isEmptyOrUndefined)(c)?"undefined":c;if((0,n.isEmptyOrUndefined)(p)||(f=t(p)),(0,n.isEmptyOrUndefined)(l)||(f=l),d.size>0){const t=(0,o.getVariableName)(r.id,e);a.setDefaultValue(t,(0,o.getType)(e),f),a.setMediaProperty(t,d),s.set(i,t),y++}else{const t=(0,o.getVariableName)(r.id,e);a.setDefaultValue(t,(0,o.getType)(e),f),a.setMediaProperty(t,u),s.set(i,t)}}y>0&&a.mediaProperties.set((0,n.getEtsPropName)(e),s)}));t.commonMediaParserArray=[[i("width"),c("width")],[i("height"),c("height")],[function(e){return e.hasMediaProperty("constraint-size-min-width")||e.hasMediaProperty("constraint-size-max-width")||e.hasMediaProperty("constraint-size-min-height")||e.hasMediaProperty("constraint-size-min-height")},function(e,t){const r=new Map,a=["min-width","max-width","min-height","max-height"];for(const i of a){const a=`constraint-size-${i}`,s=(0,o.getMediaProperty)(e,a,n.quoteString),p=(0,o.getMediaDefaultValue)(e,a,n.quoteString);if(s.size>0){const l=(0,o.getVariableName)(e.id,a);t.setDefaultValue(l,(0,o.getType)(a),p),t.setMediaProperty(l,s),m((0,n.getEtsPropName)(i),l,r,!0)}}r.size>0&&t.mediaProperties.set("constraintSize",r)}],[i("align"),d("align","Alignment.")],[i("direction"),d("direction","Direction.")],[function(e){return e.hasMediaProperty("left")||e.hasMediaProperty("top")},function(e,t){var r;const n=null!==(r=e.property.get("position"))&&void 0!==r?r:"relative",{leftValue:a,topValue:i}=s(e,e.property,e.dynamicProperty),{mediaPositionLeft:l,mediaPositionTop:c,mediaOffsetLeft:u,mediaOffsetTop:y}=function(e){var t,r;const o=new Map,n=new Map,a=new Map,i=new Map,p=null!==(t=e.mediaProperty)&&void 0!==t?t:new Map,l=null!==(r=e.dynamicMediaProperty)&&void 0!==r?r:new Map,c=new Set;for(const[e]of p)c.add(e);for(const[e]of l)c.add(e);return c.forEach((t=>{var r,p,l,c;const u=null!==(p=null===(r=e.mediaProperty)||void 0===r?void 0:r.get(t))&&void 0!==p?p:new Map,y=null!==(c=null===(l=e.dynamicMediaProperty)||void 0===l?void 0:l.get(t))&&void 0!==c?c:new Map,d=u.get("position"),{leftValue:f,topValue:m}=s(e,u,y);"absolute"===d?("undefined"!==f&&o.set(t,f),"undefined"!==m&&n.set(t,m)):("undefined"!==f&&a.set(t,f),"undefined"!==m&&i.set(t,m))})),{mediaPositionLeft:o,mediaPositionTop:n,mediaOffsetLeft:a,mediaOffsetTop:i}}(e),d=l.size>0||c.size>0||"absolute"===n,f=u.size>0||y.size>0||"relative"===n,m=(0,o.getVariableName)(e.id,"positionLeft"),g=(0,o.getVariableName)(e.id,"positionTop"),h=(0,o.getVariableName)(e.id,"offsetLeft"),E=(0,o.getVariableName)(e.id,"offsetTop");if(0!==l.size||0!==c.size||0!==y.size||0!==u.size){if(d&&f&&(p(l,u),p(u,l),p(c,y),p(y,c)),d){const e="absolute"===n?a:"undefined",r="absolute"===n?i:"undefined";t.setDefaultValue(m,(0,o.getType)("left"),e),t.setDefaultValue(g,(0,o.getType)("top"),r),t.setMediaProperty(m,l),t.setMediaProperty(g,c),t.mediaProperties.set("position",new Map([["x",m],["y",g]]))}if(f){const e="relative"===n?a:"undefined",r="relative"===n?i:"undefined";t.setDefaultValue(h,(0,o.getType)("left"),e),t.setDefaultValue(E,(0,o.getType)("top"),r),t.setMediaProperty(h,u),t.setMediaProperty(E,y),t.mediaProperties.set("offset",new Map([["x",h],["y",E]]))}}}],[i("aspect-ratio"),u("aspect-ratio")],[i("display-priority"),u("display-priority")],[i("flex-basis"),c("flex-basis")],[i("flex-grow"),u("flex-grow")],[i("flex-shrink"),u("flex-shrink")],[i("align-self"),function(e,t){const r=(0,o.getMediaProperty)(e,"align-self",n.dealWithAlignSelf);if(0===r.size)return;const a=(0,o.getMediaDefaultValue)(e,"align-self",n.dealWithAlignSelf),i=(0,o.getVariableName)(e.id,"align-self");t.setDefaultValue(i,(0,o.getType)("align-self"),a),t.setMediaProperty(i,r),t.mediaProperties.set("alignSelf",i)}],[i("border-style"),d("border-style","BorderStyle.")],[function(e){return e.hasMediaProperty("border-top-style")||e.hasMediaProperty("border-bottom-style")||e.hasMediaProperty("border-left-style")||e.hasMediaProperty("border-right-style")},b("border-style",(0,n.curry)(n.getEtsEnumValue)("BorderStyle."))],[i("border-width"),c("border-width")],[function(e){return e.hasMediaProperty("border-top-width")||e.hasMediaProperty("border-bottom-width")||e.hasMediaProperty("border-left-width")||e.hasMediaProperty("border-right-width")},b("border-width",n.quoteString)],[i("border-color"),f("border-color")],[function(e){return e.hasMediaProperty("border-top-color")||e.hasMediaProperty("border-bottom-color")||e.hasMediaProperty("border-left-color")||e.hasMediaProperty("border-right-color")},b("border-color",n.dealWithColor)],[i("border-radius"),c("border-radius")],[function(e){return e.hasMediaProperty("border-top-left-radius")||e.hasMediaProperty("border-bottom-right-radius")||e.hasMediaProperty("border-bottom-left-radius")||e.hasMediaProperty("border-top-right-radius")},b("border-radius",n.quoteString)],[i("background-color"),f("background-color")],[function(e){return e.hasMediaProperty("background-image-src")||e.hasMediaProperty("background-image-repeat")},function(e,t){const r=e.property.get("background-image-src"),i=e.property.get("background-image-repeat"),s=e.dynamicProperty.get("background-image-src"),p=e.dynamicProperty.get("background-image-repeat"),l=(0,o.getMediaProperty)(e,"background-image-src",a.dealWithSrc),c=(0,o.getMediaProperty)(e,"background-image-repeat",n.dealWithBackgroundRepeat);if(0===l.size&&0===c.size)return;let u=(0,a.dealWithSrc)(null!=r?r:"");if((0,n.isEmptyOrUndefined)(s)||(u=s),l.size>0){const r=(0,o.getVariableName)(e.id,"background-image-src");t.setDefaultValue(r,(0,o.getType)("background-image-src"),u),t.setMediaProperty(r,l),u=r}let y="undefined";if(!(0,n.isEmptyOrUndefined)(i)){const e=(0,n.dealWithBackgroundRepeat)(i);null!=e&&""!==e&&(y=e)}if((0,n.isEmptyOrUndefined)(p)||(y=p),c.size>0){const r=(0,o.getVariableName)(e.id,"background-image-repeat");t.setDefaultValue(r,(0,o.getType)("background-image-repeat"),y),t.setMediaProperty(r,c),y=r}t.mediaProperties.set("backgroundImage",u+", "+y)}],[i("background-image-size"),function(e,t){const{enumValueMap:r,objValueMap:n}=E(e,"background-image-size");if(0===r.size&&0===n.size)return;const{enumDefault:a,objDefault:i}=T(e,"background-image-size"),s=(0,o.getVariableName)(e.id,"background-image-size-enum"),p=(0,o.getVariableName)(e.id,"background-image-size-obj");t.setDefaultValue(s,"ImageSize",a),t.setDefaultValue(p,"SizeOptions",i),t.setMediaProperty(s,r),t.setMediaProperty(p,n),t.mediaProperties.set("backgroundImageSize",`${s} !== undefined ? ${s} : ${p}`)}],[i("background-image-position"),function(e,t){const{enumValueMap:r,objValueMap:n}=E(e,"background-image-position");if(0===r.size&&0===n.size)return;const{enumDefault:a,objDefault:i}=T(e,"background-image-position"),s=(0,o.getVariableName)(e.id,"background-image-position-enum"),p=(0,o.getVariableName)(e.id,"background-image-position-obj");t.setDefaultValue(s,"Alignment",a),t.setDefaultValue(p,"Position",i),t.setMediaProperty(s,r),t.setMediaProperty(p,n),t.mediaProperties.set("backgroundImagePosition",`${s} !== undefined ? ${s} : ${p}`)}],[i("opacity"),u("opacity")],[i("visibility"),d("visibility","Visibility.")],[i("enabled"),y("enabled")],[i("font-color"),f("font-color")],[function(e){return e.hasMediaProperty("margin")||e.hasMediaProperty("margin-left")||e.hasMediaProperty("margin-top")||e.hasMediaProperty("margin-right")||e.hasMediaProperty("margin-bottom")},g("margin")],[function(e){return e.hasMediaProperty("padding")||e.hasMediaProperty("padding-left")||e.hasMediaProperty("padding-top")||e.hasMediaProperty("padding-right")||e.hasMediaProperty("padding-bottom")},g("padding")]]},3135:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.componentsMediaParserArray=t.dateMediaParamParser=t.rawDataMediaParamParser=t.stringMediaParamParser=t.dealWithJustifyAlignContent=void 0;const o=r(6282),n=r(1195),a=r(8122),i=r(9248),s=r(1790),p=r(5264),l=(0,a.curry)(((e,t,r)=>r.type===e&&r.hasMediaProperty(t)));function c(e){return isNaN(Number(e))?(0,a.getEtsEnumValue)("FontWeight.",e):e}function u(e){let t=(0,a.getEtsEnumValue)("FlexAlign.",e);return"flex-start"===e?t="FlexAlign.Start":"flex-end"===e&&(t="FlexAlign.End"),t}function y(e){return"TextOverflow."+(0,a.firstUpperCase)(e)}function d(e,t,r){var o,n;const i=new Map,s=null!==(o=e.mediaProperty)&&void 0!==o?o:new Map,p=null!==(n=e.dynamicMediaProperty)&&void 0!==n?n:new Map;return s.forEach(((e,o)=>{let n=e.get(t);const s=e.get(r);(0,a.isEmptyOrUndefined)(n)&&(0,a.isEmptyOrUndefined)(s)||(n="0"===n||(0,a.isEmptyOrUndefined)(n)?"0":n.substring(0,n.length-2),i.set(o,n))})),p.forEach(((e,r)=>{const o=e.get(t);(0,a.isEmptyOrUndefined)(o)||i.set(r,o)})),i}t.dealWithJustifyAlignContent=u;const f=(0,a.curry)(((e,t,r)=>{const n=(0,o.getMediaProperty)(t,e,a.quoteString);if(0===n.size)return;const i=(0,o.getMediaDefaultValue)(t,e,a.quoteString),s=(0,o.getVariableName)(t.id,e);r.setDefaultValue(s,(0,o.getType)(e),i),r.setMediaProperty(s,n),r.mediaProperties.set((0,a.getEtsPropName)(e),s)})),m=(0,a.curry)(((e,t,r)=>{const n=(0,o.getMediaProperty)(t,e);if(0===n.size)return;const i=(0,o.getMediaDefaultValue)(t,e),s=(0,o.getVariableName)(t.id,e);r.setDefaultValue(s,(0,o.getType)(e),i),r.setMediaProperty(s,n),r.mediaProperties.set((0,a.getEtsPropName)(e),s)})),g=(0,a.curry)(((e,t,r)=>{m(e,t,r)})),h=(0,a.curry)(((e,t,r,n)=>{const i=(0,o.getMediaProperty)(r,e,(0,a.curry)(a.getEtsEnumValue)(t));if(0===i.size)return;const s=(0,o.getMediaDefaultValue)(r,e,(0,a.curry)(a.getEtsEnumValue)(t)),p=(0,o.getVariableName)(r.id,e);n.setDefaultValue(p,(0,o.getType)(e),s),n.setMediaProperty(p,i),n.mediaProperties.set((0,a.getEtsPropName)(e),p)}));t.stringMediaParamParser=(0,a.curry)(((e,t,r)=>{const i=(0,o.getMediaProperty)(t,e,a.quoteString);if(!(r.mediaParams instanceof Map)||0===i.size)return;const s=(0,o.getMediaDefaultValue)(t,e,a.quoteString),p=(0,o.getVariableName)(t.id,e),l=(0,n.getMediaVariableDecorator)(e);r.setDefaultValue(p,(0,o.getType)(e),s,l),r.setMediaProperty(p,i),r.mediaParams.set((0,a.getEtsPropName)(e),(0,n.getDynamicValueByDecorator)(e,p))})),t.rawDataMediaParamParser=(0,a.curry)(((e,t,r)=>{const i=(0,o.getMediaProperty)(t,e);if(!(r.mediaParams instanceof Map)||0===i.size)return;const s=(0,o.getMediaDefaultValue)(t,e),p=(0,o.getVariableName)(t.id,e);r.setDefaultValue(p,(0,o.getType)(e),s),r.setMediaProperty(p,i),r.mediaParams.set((0,a.getEtsPropName)(e),(0,n.getDynamicValueByDecorator)(e,p))})),t.dateMediaParamParser=(0,a.curry)(((e,t,r,n,i)=>{const s=e=>void 0===e||""===e?"new Date()":"new Date ("+(0,a.quoteString)(e)+")",p=(0,o.getMediaProperty)(n,e,s);if(!(i.mediaParams instanceof Map)||0===p.size)return;const l=(0,o.getMediaDefaultValue)(n,e,s),c=(0,o.getVariableName)(n.id,e);i.setDefaultValue(c,(0,o.getType)(e),l,r),i.setMediaProperty(c,p),i.mediaParams.set(t,c)}));const E=(0,a.curry)(((e,t,r,n,a)=>{const i=(0,o.getMediaProperty)(n,e);if(!(a.mediaParams instanceof Map)||0===i.size)return;const s=(0,o.getMediaDefaultValue)(n,e),p=(0,o.getVariableName)(n.id,e);a.setDefaultValue(p,(0,o.getType)(e),s,r),a.setMediaProperty(p,i),a.mediaParams.set(t,p)})),T=(0,a.curry)(((e,t,r,n)=>{const i=(0,o.getMediaProperty)(r,e,(0,a.curry)(a.getEtsEnumValue)(t));if(!(n.mediaParams instanceof Map)||0===i.size)return;const s=(0,o.getMediaDefaultValue)(r,e,(0,a.curry)(a.getEtsEnumValue)(t)),p=(0,o.getVariableName)(r.id,e);n.setDefaultValue(p,(0,o.getType)(e),s),n.setMediaProperty(p,i),n.mediaParams.set((0,a.getEtsPropName)(e),p)})),S=(0,a.curry)(((e,t,r)=>{const n=(0,o.getMediaProperty)(t,e,a.dealWithColor);if(0===n.size)return;const i=(0,o.getMediaDefaultValue)(t,e,a.dealWithColor),s=(0,o.getVariableName)(t.id,e);r.setDefaultValue(s,(0,o.getType)(e),i),r.setMediaProperty(s,n),r.mediaProperties.set((0,a.getEtsPropName)(e),s)})),P=(0,a.curry)(((e,t,r)=>{const n=(0,o.getMediaProperty)(t,e);if(0===n.size)return;const i=(0,o.getMediaDefaultValue)(t,e),s=(0,o.getVariableName)(t.id,e);r.setDefaultValue(s,(0,o.getType)(e),i),r.setMediaProperty(s,n),r.mediaProperties.set((0,a.getEtsPropName)(e),s)})),v=(0,a.curry)(((e,t,r,n)=>{const i=(0,o.getMediaProperty)(r,e,a.quoteString);if(0===i.size)return;const s=(0,o.getMediaDefaultValue)(r,e,a.quoteString),p=(0,o.getVariableName)(r.id,e);n.setDefaultValue(p,(0,o.getType)(e),s),n.setMediaProperty(p,i),n.mediaProperties.set((0,a.getEtsPropName)(t),p)})),b=(0,a.curry)(((e,t,r,n)=>{const i=(0,o.getMediaProperty)(r,e);if(0===i.size)return;const s=(0,o.getMediaDefaultValue)(r,e),p=(0,o.getVariableName)(r.id,e);n.setDefaultValue(p,(0,o.getType)(e),s),n.setMediaProperty(p,i),n.mediaProperties.set((0,a.getEtsPropName)(t),p)})),_=(0,a.curry)(((e,t,r,n)=>{const i=(0,o.getMediaProperty)(r,e,u);if(!(n.mediaParams instanceof Map)||0===i.size)return;const s=(0,o.getMediaDefaultValue)(r,e,u),p=(0,o.getVariableName)(r.id,e);n.setDefaultValue(p,(0,o.getType)(e),s),n.setMediaProperty(p,i),n.mediaParams.set((0,a.getEtsPropName)(e),p)})),N=(0,a.curry)(((e,t,r,n)=>{const a=(0,o.getMediaProperty)(r,e,u);if(!(n.mediaProperties instanceof Map)||0===a.size)return;const i=(0,o.getMediaDefaultValue)(r,e,u),s=(0,o.getVariableName)(r.id,e);n.setDefaultValue(s,(0,o.getType)(e),i),n.setMediaProperty(s,a),n.mediaProperties.set("justifyContent",s)})),C=(0,a.curry)(((e,t)=>t.type===e));function O(e,t,r){const n=e.property.get(r),i=e.dynamicProperty.get(r),s=(0,o.getMediaProperty)(e,r,a.quoteString);if(0===s.size)return;let p="''";(0,a.isEmptyOrUndefined)(n)||(p=(0,a.quoteString)(n)),(0,a.isEmptyOrUndefined)(i)||(p=(0,a.getContentName)(i));const l=(0,o.getVariableName)(e.id,r);t.setDefaultValue(l,(0,o.getType)(r),p),t.setMediaProperty(l,s),t.setMediaParams(l)}const A=(0,a.curry)(((e,t,r,n)=>{let i=n.mediaProperties.get((0,a.getEtsPropName)(e));void 0===i&&(i=new Map);const s=`${e}-${t}`,p=(0,o.getVariableName)(r.id,s);let l=(0,o.getMediaProperty)(r,s,a.quoteString),u=(0,o.getMediaDefaultValue)(r,s,a.quoteString);if("string"!=typeof i){if((0,a.isEmptyOrUndefined)(u))return;"style"===t&&(l=(0,o.getMediaProperty)(r,s,(0,a.curry)(a.getEtsEnumValue)("FontStyle.")),u=(0,o.getMediaDefaultValue)(r,s,(0,a.curry)(a.getEtsEnumValue)("FontStyle."))),"weight"===t&&(l=(0,o.getMediaProperty)(r,s,c),u=(0,o.getMediaDefaultValue)(r,s,c)),n.setDefaultValue(p,(0,o.getType)(s),u),n.setMediaProperty(p,l),i.set(t,p)}n.mediaProperties.set((0,a.getEtsPropName)(e),i)}));function M(e,t){const r=(0,o.getMediaProperty)(e,"font-weight",a.dealWithFontWeight);if(0===r.size)return;const n=(0,o.getMediaDefaultValue)(e,"font-weight",a.dealWithFontWeight),i=(0,o.getVariableName)(e.id,"font-weight");t.setDefaultValue(i,(0,o.getType)("font-weight"),n),t.setMediaProperty(i,r),t.mediaProperties.set("fontWeight",i)}function w(e,t,r,n){const i=new Map([["value","search-value"],["placeholder","search-placeholder"],["icon","icon"],["controller","search-controller"]]).get(e);if(void 0===i)return;const s=r.getProperty(i),p=r.dynamicProperty.get(i),l=(0,o.getMediaProperty)(r,i,a.quoteString),c=(0,o.getVariableName)(r.id,i);let u="''";0!==l.size&&((0,a.isEmptyOrUndefined)(s)||(u=(0,a.quoteString)(s)),(0,a.isEmptyOrUndefined)(p)||(u="controller"===e?p:(0,a.getContentName)(p)),n.setDefaultValue(c,(0,o.getType)(i),u),n.setMediaProperty(c,l),t.push(`${e}: ${(0,a.getContentName)(c)}`))}const R=[[l("button","label"),function(e,t){O(e,t,"label")}],[l("button","type"),h("type","ButtonType.")],[l("button","state-effect"),g("state-effect")],[l("button","font-size"),f("font-size")],[l("button","font-style"),h("font-style","FontStyle.")],[l("button","font-weight"),M],[l("button","font-family"),f("font-family")]],x=[[l("divider","vertical"),g("vertical")],[l("divider","color"),S("color")],[l("divider","stroke-width"),f("stroke-width")],[l("divider","line-cap"),h("line-cap","LineCapStyle.")]],L=[[C("image"),function(e,t){var r;const n=null!==(r=e.property.get("src"))&&void 0!==r?r:"",s=e.dynamicProperty.get("src"),p=(0,o.getMediaProperty)(e,"src",i.dealWithSrc);if(0===p.size)return;let l=(0,i.dealWithSrc)(n);(0,a.isEmptyOrUndefined)(s)||(l=s);const c=(0,o.getVariableName)(e.id,"src");t.setDefaultValue(c,(0,o.getType)("src"),l),t.setMediaProperty(c,p),t.setMediaParams(c)}],[l("image","alt"),f("alt")],[l("image","object-fit"),h("object-fit","ImageFit.")],[l("image","object-repeat"),h("object-repeat","ImageRepeat.")],[l("image","interpolation"),h("interpolation","ImageInterpolation.")],[l("image","render-mode"),h("render-mode","ImageRenderMode.")],[function(e){return e.hasMediaProperty("source-size-width")||e.hasMediaProperty("source-size-height")},function(e,t){let r=e.property.get("source-size-width"),n=e.property.get("source-size-height");const i=e.dynamicProperty.get("source-size-width"),s=e.dynamicProperty.get("source-size-height"),p=d(e,"source-size-width","source-size-height"),l=d(e,"source-size-height","source-size-width");if(0===p.size)return;r="0"===r||(0,a.isEmptyOrUndefined)(r)?"0":r.substring(0,r.length-2),n="0"===n||(0,a.isEmptyOrUndefined)(n)?"0":n.substring(0,n.length-2),(0,a.isEmptyOrUndefined)(i)||(r=i),(0,a.isEmptyOrUndefined)(s)||(n=s);const c=(0,o.getVariableName)(e.id,"source-size-width"),u=(0,o.getVariableName)(e.id,"source-size-height");t.setDefaultValue(c,(0,o.getType)("source-size-width"),r),t.setDefaultValue(u,(0,o.getType)("source-size-height"),n),t.setMediaProperty(c,p),t.setMediaProperty(u,l);const y=new Map([["width",c],["height",u]]);t.mediaProperties.set("sourceSize",y)}]],I=[[function(e){return"progress"===e.type&&(e.hasMediaProperty("value")||e.hasMediaProperty("total")||e.hasMediaProperty("style"))},function(e,t){const r=e.property.get("value"),n=e.dynamicProperty.get("value"),i=(0,o.getMediaProperty)(e,"value");if(!(t.mediaParams instanceof Map)||0===i.size)return;let s=null!=r?r:"0";(0,a.isEmptyOrUndefined)(n)||(s=n);const p=(0,o.getVariableName)(e.id,"value");t.setDefaultValue(p,(0,o.getType)("value"),s),t.setMediaProperty(p,i),t.mediaParams.set("value",p)}],[l("progress","total"),(0,t.rawDataMediaParamParser)("total")],[l("progress","style"),T("style","ProgressStyle.")],[l("progress","color"),S("color")]],F=[[l("slider","value"),(0,t.rawDataMediaParamParser)("value")],[l("slider","min"),(0,t.rawDataMediaParamParser)("min")],[l("slider","max"),(0,t.rawDataMediaParamParser)("max")],[l("slider","step"),(0,t.rawDataMediaParamParser)("step")],[l("slider","style"),T("style","SliderStyle.")],[l("slider","block-color"),S("block-color")],[l("slider","track-color"),S("track-color")],[l("slider","selected-color"),S("selected-color")],[l("slider","show-steps"),g("show-steps")],[l("slider","show-tips"),g("show-tips")]],k=[[l("text","content"),function(e,t){O(e,t,"content")}],[l("text","text-align"),h("text-align","TextAlign.")],[l("text","text-overflow"),function(e,t){const r=(0,o.getMediaProperty)(e,"text-overflow",y);if(0===r.size)return;const n=(0,o.getMediaDefaultValue)(e,"text-overflow",y),a=(0,o.getVariableName)(e.id,"text-overflow");t.setDefaultValue(a,(0,o.getType)("text-overflow"),n),t.setMediaProperty(a,r),t.mediaProperties.set("textOverflow",new Map([["overflow",a]]))}],[l("text","max-lines"),m("max-lines")],[l("text","line-height"),f("line-height")],[function(e){return"text"===e.type&&(e.hasMediaProperty("decoration-type")||e.hasMediaProperty("decoration-color"))},function(e,t){const r=(0,o.getMediaProperty)(e,"decoration-type",(0,a.curry)(a.getEtsEnumValue)("TextDecorationType.")),n=(0,o.getMediaProperty)(e,"decoration-color",a.dealWithColor);if(0===r.size&&0===n.size)return;let i=(0,o.getMediaDefaultValue)(e,"decoration-type",(0,a.curry)(a.getEtsEnumValue)("TextDecorationType.")),s=(0,o.getMediaDefaultValue)(e,"decoration-color",a.dealWithColor);if(r.size>0){const n=(0,o.getVariableName)(e.id,"decoration-type");t.setDefaultValue(n,(0,o.getType)("decoration-type"),i),t.setMediaProperty(n,r),i=n}if(n.size>0){const r=(0,o.getVariableName)(e.id,"decoration-color");t.setDefaultValue(r,(0,o.getType)("decoration-color"),s),t.setMediaProperty(r,n),s=r}const p=new Map([["type",i]]);t.mediaProperties.set("decoration",p),"undefined"!==s&&p.set("color",s)}],[l("text","baseline-offset"),f("baseline-offset")],[l("text","text-case"),h("text-case","TextCase.")],[l("text","font-size"),f("font-size")],[l("text","font-style"),h("font-style","FontStyle.")],[l("text","font-weight"),M],[l("text","font-family"),f("font-family")]],B=[[l("column","space"),(0,t.stringMediaParamParser)("space")],[l("column","align-items-column"),function(e,t){const r=(0,o.getMediaProperty)(e,"align-items-column",s.dealWithColumnAlignItems);if(0===r.size)return;const n=(0,o.getMediaDefaultValue)(e,"align-items-column",s.dealWithColumnAlignItems),a=(0,o.getVariableName)(e.id,"align-items-column");t.setDefaultValue(a,(0,o.getType)("align-items-column"),n),t.setMediaProperty(a,r),t.mediaProperties.set("alignItems",a)}],[l("column","justify-content-rc"),N("justify-content-rc","FlexAlign.")]],D=[[l("row","space"),(0,t.stringMediaParamParser)("space")],[l("row","align-items-row"),function(e,t){const r=(0,o.getMediaProperty)(e,"align-items-row",s.dealWithRowAlignItems);if(0===r.size)return;const n=(0,o.getMediaDefaultValue)(e,"align-items-row",s.dealWithRowAlignItems),a=(0,o.getVariableName)(e.id,"align-items-row");t.setDefaultValue(a,(0,o.getType)("align-items-row"),n),t.setMediaProperty(a,r),t.mediaProperties.set("alignItems",a)}],[l("row","justify-content-rc"),N("justify-content-rc","FlexAlign.")]],U=[[l("flex","flex-direction"),function(e,t){const r=(0,o.getMediaProperty)(e,"flex-direction",(0,a.curry)(a.getEtsEnumValue)("FlexDirection."));if(!(t.mediaParams instanceof Map)||0===r.size)return;const n=(0,o.getMediaDefaultValue)(e,"flex-direction",(0,a.curry)(a.getEtsEnumValue)("FlexDirection.")),i=(0,o.getVariableName)(e.id,"flex-direction");t.setDefaultValue(i,(0,o.getType)("flex-direction"),n),t.setMediaProperty(i,r),t.mediaParams.set("direction",i)}],[l("flex","wrap"),function(e,t){const r=(0,o.getMediaProperty)(e,"wrap",a.dealWithWrap);if(!(t.mediaParams instanceof Map)||0===r.size)return;const n=(0,o.getMediaDefaultValue)(e,"wrap",a.dealWithWrap),i=(0,o.getVariableName)(e.id,"wrap");t.setDefaultValue(i,(0,o.getType)("wrap"),n),t.setMediaProperty(i,r),t.mediaParams.set("wrap",i)}],[l("flex","justify-content"),_("justify-content","FlexAlign.")],[l("flex","align-items-flex"),function(e,t){const r=(0,o.getMediaProperty)(e,"align-items-flex",p.dealWithFlexAlignItems);if(!(t.mediaParams instanceof Map)||0===r.size)return;const n=(0,o.getMediaDefaultValue)(e,"align-items-flex",p.dealWithFlexAlignItems),a=(0,o.getVariableName)(e.id,"align-items-flex");t.setDefaultValue(a,(0,o.getType)("align-items-flex"),n),t.setMediaProperty(a,r),t.mediaParams.set("alignItems",a)}],[l("flex","align-content"),_("align-content","FlexAlign.")]],V=[[l("list","space"),(0,t.stringMediaParamParser)("space")],[l("list","initial-index"),(0,t.rawDataMediaParamParser)("initial-index")],[l("list","list-direction"),h("list-direction","Axis.")],[function(e){return"list"===e.type&&(e.hasMediaProperty("divider-stroke-width")||e.hasMediaProperty("divider-color")||e.hasMediaProperty("divider-start-margin")||e.hasMediaProperty("divider-end-margin"))},function(e,t){const r=[["divider-stroke-width",a.quoteString],["divider-color",a.dealWithColor],["divider-start-margin",a.quoteString],["divider-end-margin",a.quoteString]];let n=0;const i=new Map;for(const[s,p]of r){const r=(0,o.getMediaProperty)(e,s,p),l=(0,a.getEtsPropName)(s.replace("divider-",""));let c=(0,o.getMediaDefaultValue)(e,s,p);if("undefined"===c&&"divider-stroke-width"===s&&(c="0"),r.size>0){const a=(0,o.getVariableName)(e.id,s);t.setDefaultValue(a,(0,o.getType)(s),c),t.setMediaProperty(a,r),c=a,n++}i.set(l,c)}n>0&&t.mediaProperties.set("divider",i)}],[l("list","edit-mode"),g("edit-mode")],[l("list","edge-effect"),h("edge-effect","EdgeEffect.")],[l("list","chain-animation"),g("chain-animation")]],z=[[l("list-item","sticky"),h("sticky","Sticky.")],[l("list-item","editable"),g("editable")]],G=[[l("swiper","index"),m("index")],[l("swiper","auto-play"),g("auto-play")],[l("swiper","interval"),m("interval")],[l("swiper","indicator"),g("indicator")],[l("swiper","loop"),g("loop")],[l("swiper","duration"),m("duration")],[l("swiper","vertical"),g("vertical")],[l("swiper","item-space"),f("item-space")],[l("swiper","cached-count"),m("cached-count")],[l("swiper","disable-swipe"),g("disable-swipe")]],j=[[l("text-input","placeholder"),(0,t.stringMediaParamParser)("placeholder")],[l("text-input","textInput-type"),function(e,t){const r=(0,o.getMediaProperty)(e,"textInput-type",(0,a.curry)(a.getEtsEnumValue)("InputType."));if(0===r.size)return;const n=(0,o.getMediaDefaultValue)(e,"textInput-type",(0,a.curry)(a.getEtsEnumValue)("InputType.")),i=(0,o.getVariableName)(e.id,"textInput-type");t.setDefaultValue(i,(0,o.getType)("textInput-type"),n),t.setMediaProperty(i,r),t.mediaProperties.set("type",i)}],[l("text-input","placeholderColor"),S("placeholderColor")],[function(e){return"text-input"===e.type&&(e.hasMediaProperty("placeholderFont-size")||e.hasMediaProperty("placeholderFont-weight")||e.hasMediaProperty("placeholderFont-family")||e.hasMediaProperty("placeholderFont-style"))},function(e,t){const r=[["size",a.quoteString],["weight",c],["family",a.quoteString],["style",(0,a.curry)(a.getEtsEnumValue)("FontStyle.")]];let n=0;const i=new Map;for(const[a,s]of r){const r=`placeholderFont-${a}`,p=(0,o.getMediaProperty)(e,r,s);let l=(0,o.getMediaDefaultValue)(e,r,s);if(p.size>0){const a=(0,o.getVariableName)(e.id,r);t.setDefaultValue(a,(0,o.getType)(r),l),t.setMediaProperty(a,p),l=a,n++}i.set(a,l)}n>0&&t.mediaProperties.set("placeholderFont",i)}],[l("text-input","enterKeyType"),h("enterKeyType","EnterKeyType.")],[l("text-input","caretColor"),S("caretColor")],[l("text-input","maxLength"),m("maxLength")]],W=[[l("refresh","friction"),(0,t.rawDataMediaParamParser)("friction")],[l("refresh","offset"),(0,t.stringMediaParamParser)("offset")],[l("refresh","refreshing"),(0,t.rawDataMediaParamParser)("refreshing")]],$=[[l("timePicker","datetime-selected"),(0,t.dateMediaParamParser)("datetime-selected","selected","private")],[l("timePicker","useMilitaryTime"),g("useMilitaryTime")]],q=[[l("datePicker","datetime-selected"),(0,t.dateMediaParamParser)("datetime-selected","selected","private")],[l("datePicker","start"),(0,t.dateMediaParamParser)("start","start","private")],[l("datePicker","end"),(0,t.dateMediaParamParser)("end","end","private")],[l("datePicker","lunar"),g("lunar")]],H=[[l("textPicker","range"),(0,t.rawDataMediaParamParser)("range")],[l("textPicker","textPicker-selected"),E("textPicker-selected","selected","@State")],[l("textPicker","defaultPickerItemHeight"),f("defaultPickerItemHeight")]],Y=[[l("select","select-option"),function(e,t){!function(e,t,r){const n=e.dynamicProperty.get(r),i=(0,o.getMediaProperty)(e,r,a.quoteString);if(0===i.size)return;const s=null!=n?n:'[{value: ""}]',p=(0,o.getVariableName)(e.id,r);t.setDefaultValue(p,(0,o.getType)(r),s),t.setMediaProperty(p,i),t.setMediaParams(p)}(e,t,"select-option")}],[l("select","select-value"),function(e,t){const r="select-value",n=(0,o.getMediaProperty)(e,r,a.quoteString);if(0===n.size)return;const i=(0,o.getMediaDefaultValue)(e,r,a.quoteString),s=(0,o.getVariableName)(e.id,r);t.setDefaultValue(s,(0,o.getType)(r),i),t.setMediaProperty(s,n),t.mediaProperties.set("value",s)}],[l("select","selected"),m("selected")],[l("select","font-size"),A("font","size")],[l("select","font-style"),A("font","style")],[l("select","font-family"),A("font","family")],[l("select","font-weight"),A("font","weight")],[l("select","selected-option-font-size"),A("selected-option-font","size")],[l("select","selected-option-font-style"),A("selected-option-font","style")],[l("select","selected-option-font-family"),A("selected-option-font","family")],[l("select","selected-option-font-weight"),A("selected-option-font","weight")],[l("select","selected-option-font-color"),S("selected-option-font-color")],[l("select","selected-option-bg-color"),S("selected-option-bg-color")],[l("select","option-font-size"),A("option-font","size")],[l("select","option-font-style"),A("option-font","style")],[l("select","option-font-family"),A("option-font","family")],[l("select","option-font-weight"),A("option-font","weight")],[l("select","option-font-color"),S("option-font-color")],[l("select","option-bg-color"),S("option-bg-color")]],X=[[l("toggle","toggle-type"),function(e,t){const r="ToggleType.",n="toggle-type",i=(0,o.getMediaProperty)(e,n,(0,a.curry)(a.getEtsEnumValue)(r));if(!(t.mediaParams instanceof Map)||0===i.size)return;const s=(0,o.getMediaDefaultValue)(e,n,(0,a.curry)(a.getEtsEnumValue)(r)),p=(0,o.getVariableName)(e.id,n);t.setDefaultValue(p,(0,o.getType)(n),s),t.setMediaProperty(p,i),t.mediaParams.set("type",p)}],[l("toggle","isOn"),(0,t.rawDataMediaParamParser)("isOn")],[l("toggle","selectedColor"),S("selectedColor")],[l("toggle","switchPointColor"),S("switchPointColor")]],J=[[l("checkbox","select"),g("select")],[l("checkbox","selectedColor"),S("selectedColor")],[l("checkbox","name"),(0,t.stringMediaParamParser)("name")],[l("checkbox","group"),(0,t.stringMediaParamParser)("group")]],K=[[l("checkboxGroup","selectAll"),g("selectAll")],[l("checkboxGroup","selectedColor"),S("selectedColor")],[l("checkboxGroup","group"),(0,t.stringMediaParamParser)("group")]],Q=[[l("scroll","scrollable"),h("scrollable","ScrollDirection.")],[l("scroll","scroll-bar"),h("scroll-bar","BarState.")],[l("scroll","scroll-bar-color"),S("scroll-bar-color")],[l("scroll","scroll-bar-width"),f("scroll-bar-width")],[l("scroll","edge-effect-scroll"),function(e,t){const r="edge-effect-scroll",n=(0,o.getMediaProperty)(e,r,a.dealWithScrollEdgeEffect);if(0===n.size)return;const i=(0,o.getMediaDefaultValue)(e,r,a.dealWithScrollEdgeEffect),s=(0,o.getVariableName)(e.id,r);t.setDefaultValue(s,(0,o.getType)(r),i),t.setMediaProperty(s,n),t.mediaProperties.set("edgeEffect",s)}]],Z=[[l("grid","columns-template"),f("columns-template")],[l("grid","rows-template"),f("rows-template")],[l("grid","columns-gap"),f("columns-gap")],[l("grid","rows-gap"),f("rows-gap")],[l("grid","scroll-bar"),h("scroll-bar","BarState.")],[l("grid","scroll-bar-color"),S("scroll-bar-color")],[l("grid","scroll-bar-width"),f("scroll-bar-width")],[l("grid","cached-count"),m("cached-count")],[l("grid","edit-mode"),g("edit-mode")],[l("grid","layout-direction"),h("layout-direction","GridDirection.")],[l("grid","max-count"),m("max-count")],[l("grid","min-count"),m("min-count")],[l("grid","cell-length"),m("cell-length")],[l("grid","multi-selectable"),g("multi-selectable")],[l("grid","support-animation"),g("support-animation")]],ee=[[l("grid-item","row-start"),m("row-start")],[l("grid-item","row-end"),m("row-end")],[l("grid-item","column-start"),m("column-start")],[l("grid-item","column-end"),m("column-end")],[l("grid-item","force-rebuild"),g("force-rebuild")],[l("grid-item","selectable"),g("selectable")]],te=[[l("stack","align-content-stack"),function(e,t){const r="align-content-stack",n=(0,o.getMediaProperty)(e,r,(0,a.curry)(a.getEtsEnumValue)("Alignment."));if(!(t.mediaParams instanceof Map)||0===n.size)return;const i=(0,o.getMediaDefaultValue)(e,r,(0,a.curry)(a.getEtsEnumValue)("Alignment.")),s=(0,o.getVariableName)(e.id,r);t.setDefaultValue(s,(0,o.getType)(r),i),t.setMediaProperty(s,n),t.mediaParams.set("alignContent",s)}]],re=[[l("navigation","navigation-title"),v("navigation-title","title")],[l("navigation","subTitle"),f("subTitle")],[l("navigation","menus"),P("menus")],[l("navigation","titleMode"),h("titleMode","NavigationTitleMode.")],[l("navigation","toolBar"),P("toolBar")],[l("navigation","hideToolBar"),g("hideToolBar")],[l("navigation","hideTitleBar"),g("hideTitleBar")],[l("navigation","hideBackButton"),g("hideBackButton")]],oe=[[function(e){return"search"===e.type},function(e,t){const r=[];w("value",r,e,t),w("placeholder",r,e,t),w("icon",r,e,t),w("controller",r,e,t),0!==r.length&&t.setParams(`{${r.join(", ")}}`)}],[l("search","text-font-size"),A("text-font","size")],[l("search","text-font-style"),A("text-font","style")],[l("search","text-font-weight"),A("text-font","weight")],[l("search","text-font-family"),A("text-font","family")],[l("search","placeholder-font-size"),A("placeholder-font","size")],[l("search","placeholder-font-style"),A("placeholder-font","style")],[l("search","placeholder-font-weight"),A("placeholder-font","weight")],[l("search","placeholder-font-family"),A("placeholder-font","family")],[l("search","placeholderColor"),S("placeholderColor")],[l("search","search-text-align"),function(e,t){const r=(0,o.getMediaProperty)(e,"search-text-align",(0,a.curry)(a.getEtsEnumValue)("TextAlign."));if(0===r.size)return;const n=(0,o.getMediaDefaultValue)(e,"search-text-align",(0,a.curry)(a.getEtsEnumValue)("TextAlign.")),i=(0,o.getVariableName)(e.id,"search-text-align");t.setDefaultValue(i,(0,o.getType)("search-text-align"),n),t.setMediaProperty(i,r),t.mediaProperties.set("textAlign",i)}],[l("search","search-button"),f("search-button")],[l("search","copy-option"),h("copy-option","CopyOptions.")]],ne=[[l("tabs","bar-position"),T("bar-position","BarPosition.")],[l("tabs","index"),(0,t.rawDataMediaParamParser)("index")],[l("tabs","controller"),(0,t.rawDataMediaParamParser)("controller")],[l("tabs","vertical"),g("vertical")],[l("tabs","tabs-scrollable"),b("tabs-scrollable","scrollable")],[l("tabs","bar-mode"),h("bar-mode","BarMode.")],[l("tabs","bar-width"),f("bar-width")],[l("tabs","bar-height"),f("bar-height")],[l("tabs","animation-duration"),m("animation-duration")]],ae=[[function(e){return"tab-content"===e.type&&(e.hasMediaProperty("tabBar-icon")||e.hasMediaProperty("tabBar-text"))},function(e,t){const r=(0,o.getMediaProperty)(e,"tabBar-text",a.quoteString),n=(0,o.getMediaProperty)(e,"tabBar-icon",i.dealWithSrc),s=(0,o.getMediaDefaultValue)(e,"tabBar-text",a.quoteString),p=(0,o.getMediaDefaultValue)(e,"tabBar-icon",i.dealWithSrc),l=(0,o.getVariableName)(e.id,"tabBar-text"),c=(0,o.getVariableName)(e.id,"tabBar-icon"),u=new Map([["text",s],["icon",p]]);r.size>0&&(t.setDefaultValue(l,(0,o.getType)("tabBar-text"),s),t.setMediaProperty(l,r),u.set("text",l)),n.size>0&&(t.setDefaultValue(c,(0,o.getType)("tabBar-icon"),p),t.setMediaProperty(c,n),u.set("icon",c)),t.mediaProperties.set("tabBar",u)}]];t.componentsMediaParserArray=[...R,...x,...L,...I,...F,...k,...B,...D,...U,...V,...z,...G,...j,...X,...W,...$,...H,...Y,...q,...te,...Q,...Z,...ee,...re,...oe,...ne,...ae,...J,...K]},366:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseCustomMediaVisualModel=void 0;const o=r(6125),n=r(3135),a=r(6282),i=r(1195),s=r(8122);t.parseCustomMediaVisualModel=function(e,t){(0,i.getCustomAttributeMap)().forEach(((r,n)=>{if(function(e,t){return e.hasMediaProperty(t)}(e,n)){const l=p.get(r.type);"function"==typeof l&&l(n,e,t);const c=o.enumParserMap.get(r.type);"function"==typeof c&&function(e,t,r,o){const n=(0,a.getMediaProperty)(t,e,o);if(!(r.mediaParams instanceof Map)||0===n.size)return;const p=(0,a.getMediaDefaultValue)(t,e,o),l=(0,a.getVariableName)(t.id,e);r.setDefaultValue(l,(0,a.getType)(e),p),r.setMediaProperty(l,n),r.mediaParams.set((0,s.getEtsPropName)(e),(0,i.getDynamicValueByDecorator)(e,l))}(n,e,t,c)}}))};const p=new Map([["string",n.stringMediaParamParser],["boolean",n.rawDataMediaParamParser],["number",n.rawDataMediaParamParser],["any[]",n.rawDataMediaParamParser],["object",n.rawDataMediaParamParser],["Date",function(e,t,r){(0,n.dateMediaParamParser)(e,(0,s.getEtsPropName)(e),"private",t,r)}]])},3729:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isMediaProperty=t.parseMediaVisualModel=void 0;const o=r(1912),n=r(9223),a=r(3135);function i(e,t,r){const o=t.get(r);return void 0!==o&&o.has(e)}t.parseMediaVisualModel=function(e,t){(0,n.forEachParser)(e,t),(0,n.ifParser)(e,t);for(const r of p)("boolean"==typeof r[0]||r[0](e))&&r[1](e,t)},t.isMediaProperty=function(e,t){return!i(e,s,"common")&&!i(e,s,t)&&!i(e,s,"events")};const s=new Map([["common",new Set(["keyGenerator","item","idx"])],["events",new Set([...o.events])]]),p=[...n.commonMediaParserArray,...a.componentsMediaParserArray]},6282:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getMediaDefaultValue=t.getVariableName=t.getMediaProperty=t.getType=void 0;const o=r(4294),n=r(1290),a=r(1195),i=r(8122);function s(e,t){for(const r of t)if(r.property===e)return r.etsType;return""}t.getType=function(e){const t=e+"-visual",r=n.etsPropertyList;let o="";for(const e of r)if(void 0!==e.propertySet.properties&&(o=s(t,e.propertySet.properties)),e.propertySet.property===t&&(o=e.propertySet.etsType),""!==o)break;return""!==o?function(e=""){const t=new Map([["Rfloat","Resource"],["Rstring","Resource"],["Rcolor","Resource"],["Rmedia","Resource"],["Rrawfile","Resource"],["Rplural","Resource"],["ETSArray","any[]"]]),r=new Array;return e.split("|").forEach((e=>{const o=t.get(e),n=null!=o?o:e;r.includes(n)||r.push(null!=o?o:e)})),r.join(" | ")}(o):(0,a.getCustomAttrType)(e)},t.getMediaProperty=function(e,t,r){var o,n;const a=new Map;return(null!==(o=e.mediaProperty)&&void 0!==o?o:new Map).forEach(((e,o)=>{let n=e.get(t);(0,i.isEmptyOrUndefined)(n)||("function"==typeof r&&(n=r(n)),(0,i.isEmptyOrUndefined)(n)||a.set(o,n))})),(null!==(n=e.dynamicMediaProperty)&&void 0!==n?n:new Map).forEach(((e,r)=>{let o=e.get(t);void 0===o||"content"!==t&&"label"!==t||(o=(0,i.getContentName)(o)),(0,i.isEmptyOrUndefined)(o)||a.set(r,o)})),a},t.getVariableName=function(e,t){const r=(0,o.getTagName)(e),n=`this.${(0,i.getEtsPropName)(r)}${(0,i.firstUpperCase)((0,i.getEtsPropName)(t))}`;return`${n}_${(0,o.getUniqueId)(n)}`},t.getMediaDefaultValue=function(e,t,r){var o;const n=e.property.get(t),a=e.dynamicProperty.get(t);let s=null!==(o=new Map([["if","true"],["auto-play","false"],["interval","3000"],["select-value","''"],["columns-template","''"],["rows-template","''"],["tabBar-icon","''"],["tabBar-text","'TabBar'"]]).get(t))&&void 0!==o?o:"undefined";return(0,i.isEmptyOrUndefined)(n)||(s="function"==typeof r?r(n):n,s=(0,i.isEmptyOrUndefined)(s)?"undefined":s),(0,i.isEmptyOrUndefined)(a)||(s=a),s}},7893:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseBuildersVisualModel=void 0;const o=r(8122);t.parseBuildersVisualModel=function(e,t,r){const n=e.slots;void 0!==n&&0!==n.size&&n.forEach(((n,a)=>{const i=(0,o.getBuilderUniqueName)(e.id,a);t.properties.set(a,`this.${i}`),t.builders.set(i,r.visit(n))}))}},8916:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.buttonParserArray=void 0;const o=r(8122);t.buttonParserArray=[[(0,o.hasFeatureProperty)("button","label"),o.labelParamParser],[(0,o.hasFeatureProperty)("button","type"),(0,o.enumPropertyParser)("type","ButtonType.")],[(0,o.hasFeatureProperty)("button","state-effect"),(0,o.booleanPropertyParser)("state-effect")],[(0,o.hasFeatureProperty)("button","font-size"),(0,o.stringPropertyParser)("font-size")],[(0,o.hasFeatureProperty)("button","font-style"),(0,o.enumPropertyParser)("font-style","FontStyle.")],[(0,o.hasFeatureProperty)("button","font-weight"),o.fontWeightPropertyParser],[(0,o.hasFeatureProperty)("button","font-family"),(0,o.stringPropertyParser)("font-family")]]},1147:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.checkboxGroupParseArray=void 0;const o=r(8122);t.checkboxGroupParseArray=[[(0,o.hasFeatureProperty)("checkboxGroup","selectAll"),(0,o.booleanPropertyParser)("selectAll")],[(0,o.hasFeatureProperty)("checkboxGroup","selectedColor"),(0,o.colorPropertyParser)("selectedColor")],[(0,o.hasFeatureProperty)("checkboxGroup","group"),(0,o.stringParamParser)("group")]]},2218:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.checkboxParseArray=void 0;const o=r(8122);t.checkboxParseArray=[[(0,o.hasFeatureProperty)("checkbox","select"),(0,o.booleanPropertyParser)("select")],[(0,o.hasFeatureProperty)("checkbox","selectedColor"),(0,o.colorPropertyParser)("selectedColor")],[(0,o.hasFeatureProperty)("checkbox","name"),(0,o.stringParamParser)("name")],[(0,o.hasFeatureProperty)("checkbox","group"),(0,o.stringParamParser)("group")]]},7150:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.commonParserArray=void 0;const o=r(8122),n=r(9248);function a(e,t,r,n=!1){(0,o.isEmptyOrUndefined)(t)||r.set(e,n?t:(0,o.quoteString)(t))}function i(e,t,r,n,a){const i=e.getProperty(t),s=e.getProperty(r),p=e.dynamicProperty.has(t),l=e.dynamicProperty.has(r),c=(0,o.getEdgeBorderDirection)(r);(0,o.isEmptyOrUndefined)(s)?(0,o.isEmptyOrUndefined)(i)||n.set(c,p?i:a(i)):n.set(c,l?s:a(s))}t.commonParserArray=[[(0,o.hasCommonProperty)("width"),(0,o.stringPropertyParser)("width")],[(0,o.hasCommonProperty)("height"),(0,o.stringPropertyParser)("height")],[function(e){return e.hasProperty("constraint-size-min-width")||e.hasProperty("constraint-size-max-width")||e.hasProperty("constraint-size-min-height")||e.hasProperty("constraint-size-max-height")},function(e,t){const r=new Map,o=e.getProperty("constraint-size-min-width"),n=e.getProperty("constraint-size-max-width"),i=e.getProperty("constraint-size-min-height"),s=e.getProperty("constraint-size-max-height");a("minWidth",o,r,e.dynamicProperty.has("constraint-size-min-width")),a("maxWidth",n,r,e.dynamicProperty.has("constraint-size-max-width")),a("minHeight",i,r,e.dynamicProperty.has("constraint-size-min-height")),a("maxHeight",s,r,e.dynamicProperty.has("constraint-size-max-height")),r.size>0&&t.properties.set("constraintSize",r)}],[(0,o.hasCommonProperty)("align"),(0,o.enumPropertyParser)("align","Alignment.")],[(0,o.hasCommonProperty)("direction"),(0,o.enumPropertyParser)("direction","Direction.")],[function(e){return e.hasProperty("left")||e.hasProperty("top")},function(e,t){const r="absolute"===e.property.get("position")?"position":"offset",n=e.property.get("left"),a=e.property.get("top"),i=e.dynamicProperty.get("left"),s=e.dynamicProperty.get("top");if((0,o.isEmptyOrUndefined)(i)&&(0,o.isEmptyOrUndefined)(s)&&(0,o.isEmptyOrUndefined)(n)&&(0,o.isEmptyOrUndefined)(a))return;const p=new Map([["x",`${(0,o.quoteString)(null!=n?n:"0")}`],["y",`${(0,o.quoteString)(null!=a?a:"0")}`]]);(0,o.isEmptyOrUndefined)(i)||p.set("x",i),(0,o.isEmptyOrUndefined)(s)||p.set("y",s),t.properties.set(r,p)}],[(0,o.hasCommonProperty)("aspect-ratio"),(0,o.numberPropertyParser)("aspect-ratio")],[(0,o.hasCommonProperty)("display-priority"),(0,o.numberPropertyParser)("display-priority")],[(0,o.hasCommonProperty)("flex-basis"),(0,o.stringPropertyParser)("flex-basis")],[(0,o.hasCommonProperty)("flex-grow"),(0,o.numberPropertyParser)("flex-grow")],[(0,o.hasCommonProperty)("flex-shrink"),(0,o.numberPropertyParser)("flex-shrink")],[(0,o.hasCommonProperty)("align-self"),function(e,t){const r=e.dynamicProperty.get("align-self");if(!(0,o.isEmptyOrUndefined)(r))return void t.properties.set("alignSelf",r);const n=e.property.get("align-self");if((0,o.isEmptyOrUndefined)(n))return;const a=(0,o.dealWithAlignSelf)(n);t.properties.set("alignSelf",a)}],[function(e){return e.hasProperty("border-style")||e.hasProperty("border-top-style")||e.hasProperty("border-right-style")||e.hasProperty("border-bottom-style")||e.hasProperty("border-left-style")},function(e,t){const r=new Map,n=e.getProperty("border-style"),a=e.getProperty("border-top-style"),s=e.getProperty("border-bottom-style"),p=e.getProperty("border-left-style"),l=e.getProperty("border-right-style"),c=e.dynamicProperty.has("border-style"),u=(0,o.getBorderDirections)("border-style");for(const t of u)i(e,"border-style",t,r,(0,o.curry)(o.getEtsEnumValue)("BorderStyle."));(0,o.isEmptyOrUndefined)(a)&&(0,o.isEmptyOrUndefined)(s)&&(0,o.isEmptyOrUndefined)(p)&&(0,o.isEmptyOrUndefined)(l)?(0,o.isEmptyOrUndefined)(n)||t.properties.set((0,o.getEtsPropName)("border-style"),c?n:(0,o.getEtsEnumValue)("BorderStyle.",n)):r.size>0&&t.properties.set((0,o.getEtsPropName)("border-style"),r)}],[function(e){return e.hasProperty("border-width")||e.hasProperty("border-top-width")||e.hasProperty("border-right-width")||e.hasProperty("border-bottom-width")||e.hasProperty("border-left-width")},function(e,t){const r=new Map,n=e.getProperty("border-width"),i=e.getProperty("border-top-width"),s=e.getProperty("border-bottom-width"),p=e.getProperty("border-left-width"),l=e.getProperty("border-right-width"),c=e.property.has("border-top-width"),u=e.property.has("border-bottom-width"),y=e.property.has("border-left-width"),d=e.property.has("border-right-width"),f=e.dynamicProperty.has("border-width"),m=e.dynamicProperty.has("border-top-width"),g=e.dynamicProperty.has("border-bottom-width"),h=e.dynamicProperty.has("border-left-width"),E=e.dynamicProperty.has("border-right-width");(0,o.isEmptyOrUndefined)(i)&&(0,o.isEmptyOrUndefined)(s)&&(0,o.isEmptyOrUndefined)(p)&&(0,o.isEmptyOrUndefined)(l)?(0,o.isEmptyOrUndefined)(n)||t.properties.set((0,o.getEtsPropName)("border-width"),f?n:(0,o.quoteString)(n)):(a("top",null!=i?i:n,r,m||!c&&f),a("bottom",null!=s?s:n,r,g||!u&&f),a("left",null!=p?p:n,r,h||!y&&f),a("right",null!=l?l:n,r,E||!d&&f),r.size>0&&t.properties.set((0,o.getEtsPropName)("border-width"),r))}],[function(e){return e.hasProperty("border-color")||e.hasProperty("border-top-color")||e.hasProperty("border-right-color")||e.hasProperty("border-bottom-color")||e.hasProperty("border-left-color")},function(e,t){const r=new Map,n=e.getProperty("border-color"),a=e.getProperty("border-top-color"),s=e.getProperty("border-bottom-color"),p=e.getProperty("border-left-color"),l=e.getProperty("border-right-color"),c=e.dynamicProperty.has("border-color"),u=(0,o.getBorderDirections)("border-color");for(const t of u)i(e,"border-color",t,r,o.dealWithColor);(0,o.isEmptyOrUndefined)(a)&&(0,o.isEmptyOrUndefined)(s)&&(0,o.isEmptyOrUndefined)(p)&&(0,o.isEmptyOrUndefined)(l)?(0,o.isEmptyOrUndefined)(n)||t.properties.set((0,o.getEtsPropName)("border-color"),c?n:(0,o.dealWithColor)(n)):r.size>0&&t.properties.set((0,o.getEtsPropName)("border-color"),r)}],[function(e){return e.hasProperty("border-radius")||e.hasProperty("border-top-left-radius")||e.hasProperty("border-top-right-radius")||e.hasProperty("border-bottom-right-radius")||e.hasProperty("border-bottom-left-radius")},function(e,t){const r=new Map,n=e.getProperty("border-radius"),a=e.getProperty("border-top-left-radius"),s=e.getProperty("border-top-right-radius"),p=e.getProperty("border-bottom-left-radius"),l=e.getProperty("border-bottom-right-radius"),c=e.dynamicProperty.has("border-radius"),u=(0,o.getBorderDirections)("border-radius");for(const t of u)i(e,"border-radius",t,r,o.quoteString);(0,o.isEmptyOrUndefined)(a)&&(0,o.isEmptyOrUndefined)(s)&&(0,o.isEmptyOrUndefined)(p)&&(0,o.isEmptyOrUndefined)(l)?(0,o.isEmptyOrUndefined)(n)||t.properties.set((0,o.getEtsPropName)("border-radius"),c?n:(0,o.quoteString)(n)):r.size>0&&t.properties.set((0,o.getEtsPropName)("border-radius"),r)}],[(0,o.hasCommonProperty)("background-color"),(0,o.colorPropertyParser)("background-color")],[function(e){return e.hasProperty("background-image-src")||e.hasProperty("background-image-repeat")},function(e,t){const r=e.property.get("background-image-src"),a=e.property.get("background-image-repeat"),i=e.dynamicProperty.get("background-image-src"),s=e.dynamicProperty.get("background-image-repeat");if((0,o.isEmptyOrUndefined)(r)&&(0,o.isEmptyOrUndefined)(a)&&(0,o.isEmptyOrUndefined)(i)&&(0,o.isEmptyOrUndefined)(s))return;let p=(0,n.dealWithSrc)(null!=r?r:"");if((0,o.isEmptyOrUndefined)(i)||(p=i),(0,o.isEmptyOrUndefined)(s)){if(!(0,o.isEmptyOrUndefined)(a)){const e=(0,o.dealWithBackgroundRepeat)(a);null!=e&&""!==e&&(p=p+", "+e)}}else p=p+", "+s;t.properties.set("backgroundImage",p)}],[(0,o.hasCommonProperty)("background-image-size"),function(e,t){const r=e.dynamicProperty.get("background-image-size");if(!(0,o.isEmptyOrUndefined)(r))return void t.properties.set("backgroundImageSize",r);const n=e.property.get("background-image-size");if((0,o.isEmptyOrUndefined)(n))return;if(""!==(0,o.getBackgroundImageSizeEnumValue)(n))return void t.properties.set("backgroundImageSize",(0,o.getEtsEnumValue)("ImageSize.",n));const a=n.match(/^ *((0|[1-9][0-9]*)(px|vp|lpx|%))( *$| +((0|[1-9][0-9]*)(px|vp|lpx|%)) *$)/);null!==a&&(void 0!==a[5]?t.properties.set("backgroundImageSize",new Map([["width",`${(0,o.quoteString)(a[1])}`],["height",`${(0,o.quoteString)(a[5])}`]])):t.properties.set("backgroundImageSize",new Map([["width",`${(0,o.quoteString)(a[1])}`]])))}],[(0,o.hasCommonProperty)("background-image-position"),function(e,t){const r=e.dynamicProperty.get("background-image-position");if(!(0,o.isEmptyOrUndefined)(r))return void t.properties.set("backgroundImagePosition",r);const n=e.property.get("background-image-position");if((0,o.isEmptyOrUndefined)(n))return;const a=(0,o.getBackgroundImagePositionEnumValue)(n);if(""!==a)return void t.properties.set("backgroundImagePosition",a);const i=n.match(/^ *((0|[1-9][0-9]*)(px|vp|lpx|%)) +((0|[1-9][0-9]*)(px|vp|lpx|%)) *$/);null!==i&&t.properties.set("backgroundImagePosition",new Map([["x",`${(0,o.quoteString)(i[1])}`],["y",`${(0,o.quoteString)(i[4])}`]]))}],[(0,o.hasCommonProperty)("opacity"),(0,o.numberPropertyParser)("opacity")],[(0,o.hasCommonProperty)("visibility"),(0,o.enumPropertyParser)("visibility","Visibility.")],[(0,o.hasCommonProperty)("enabled"),(0,o.booleanPropertyParser)("enabled")],[(0,o.hasCommonProperty)("font-color"),(0,o.colorPropertyParser)("font-color")],[function(e){return e.hasProperty("margin")||e.hasProperty("margin-left")||e.hasProperty("margin-top")||e.hasProperty("margin-right")||e.hasProperty("margin-bottom")},function(e,t){var r,o,n,i;const s=new Map,p=e.getProperty("margin"),l=null!==(r=e.getProperty("margin-top"))&&void 0!==r?r:p,c=null!==(o=e.getProperty("margin-bottom"))&&void 0!==o?o:p,u=null!==(n=e.getProperty("margin-left"))&&void 0!==n?n:p,y=null!==(i=e.getProperty("margin-right"))&&void 0!==i?i:p,d=e.property.has("margin-top"),f=e.property.has("margin-bottom"),m=e.property.has("margin-left"),g=e.property.has("margin-right"),h=e.dynamicProperty.has("margin"),E=e.dynamicProperty.has("margin-top"),T=e.dynamicProperty.has("margin-bottom"),S=e.dynamicProperty.has("margin-left"),P=e.dynamicProperty.has("margin-right");a("top",l,s,E||!d&&h),a("bottom",c,s,T||!f&&h),a("left",u,s,S||!m&&h),a("right",y,s,P||!g&&h),s.size>0&&t.properties.set("margin",s)}],[function(e){return e.hasProperty("padding")||e.hasProperty("padding-left")||e.hasProperty("padding-top")||e.hasProperty("padding-right")||e.hasProperty("padding-bottom")},function(e,t){var r,o,n,i;const s=new Map,p=e.getProperty("padding"),l=null!==(r=e.getProperty("padding-top"))&&void 0!==r?r:p,c=null!==(o=e.getProperty("padding-bottom"))&&void 0!==o?o:p,u=null!==(n=e.getProperty("padding-left"))&&void 0!==n?n:p,y=null!==(i=e.getProperty("padding-right"))&&void 0!==i?i:p,d=e.property.has("padding-top"),f=e.property.has("padding-bottom"),m=e.property.has("padding-left"),g=e.property.has("padding-right"),h=e.dynamicProperty.has("padding"),E=e.dynamicProperty.has("padding-top"),T=e.dynamicProperty.has("padding-bottom"),S=e.dynamicProperty.has("padding-left"),P=e.dynamicProperty.has("padding-right");a("top",l,s,E||!d&&h),a("bottom",c,s,T||!f&&h),a("left",u,s,S||!m&&h),a("right",y,s,P||!g&&h),s.size>0&&t.properties.set("padding",s)}]]},1778:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dividerParserArray=void 0;const o=r(8122);t.dividerParserArray=[[(0,o.hasFeatureProperty)("divider","vertical"),(0,o.booleanPropertyParser)("vertical")],[(0,o.hasFeatureProperty)("divider","color"),(0,o.colorPropertyParser)("color")],[(0,o.hasFeatureProperty)("divider","stroke-width"),(0,o.stringPropertyParser)("stroke-width")],[(0,o.hasFeatureProperty)("divider","line-cap"),(0,o.enumPropertyParser)("line-cap","LineCapStyle.")]]},5264:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dealWithFlexAlignItems=t.flexParserArray=void 0;const o=r(8122),n=(0,o.curry)(((e,t,r,n)=>{if(!(n.params instanceof Map))return;const a=r.dynamicProperty.get(e);if(!(0,o.isEmptyOrUndefined)(a))return void n.params.set((0,o.getEtsPropName)(e),a);const i=r.property.get(e);if((0,o.isEmptyOrUndefined)(i))return;let s=(0,o.getEtsEnumValue)(t,i);"flex-start"===i?s=t+"Start":"flex-end"===i&&(s=t+"End"),n.params.set((0,o.getEtsPropName)(e),s)}));function a(e){let t=(0,o.getEtsEnumValue)("ItemAlign.",e);return"flex-start"===e?t="ItemAlign.Start":"flex-end"===e&&(t="ItemAlign.End"),t}t.flexParserArray=[[(0,o.hasFeatureProperty)("flex","flex-direction"),function(e,t){if(!(t.params instanceof Map))return;const r=e.dynamicProperty.get("flex-direction");if(!(0,o.isEmptyOrUndefined)(r))return void t.params.set("direction",r);const n=e.property.get("flex-direction");(0,o.isEmptyOrUndefined)(n)||t.params.set("direction",(0,o.getEtsEnumValue)("FlexDirection.",n))}],[(0,o.hasFeatureProperty)("flex","wrap"),function(e,t){if(!(t.params instanceof Map))return;const r=e.dynamicProperty.get("wrap");if(!(0,o.isEmptyOrUndefined)(r))return void t.params.set("wrap",r);const n=e.property.get("wrap");if((0,o.isEmptyOrUndefined)(n))return;const a=(0,o.dealWithWrap)(n);t.params.set("wrap",a)}],[(0,o.hasFeatureProperty)("flex","justify-content"),n("justify-content","FlexAlign.")],[(0,o.hasFeatureProperty)("flex","align-items-flex"),function(e,t){if(!(t.params instanceof Map))return;const r=e.dynamicProperty.get("align-items-flex");if(!(0,o.isEmptyOrUndefined)(r))return void t.params.set("alignItems",r);const n=e.property.get("align-items-flex");if((0,o.isEmptyOrUndefined)(n))return;const i=a(n);t.params.set("alignItems",i)}],[(0,o.hasFeatureProperty)("flex","align-content"),n("align-content","FlexAlign.")]],t.dealWithFlexAlignItems=a},2153:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gridItemParserArray=t.gridParserArray=void 0;const o=r(8122);t.gridParserArray=[[(0,o.hasFeatureProperty)("grid","scroller"),o.scrollerParamParser],[(0,o.hasFeatureProperty)("grid","columns-template"),(0,o.stringPropertyParser)("columns-template")],[(0,o.hasFeatureProperty)("grid","rows-template"),(0,o.stringPropertyParser)("rows-template")],[(0,o.hasFeatureProperty)("grid","columns-gap"),(0,o.stringPropertyParser)("columns-gap")],[(0,o.hasFeatureProperty)("grid","rows-gap"),(0,o.stringPropertyParser)("rows-gap")],[(0,o.hasFeatureProperty)("grid","scroll-bar"),(0,o.enumPropertyParser)("scroll-bar","BarState.")],[(0,o.hasFeatureProperty)("grid","scroll-bar-color"),(0,o.colorPropertyParser)("scroll-bar-color")],[(0,o.hasFeatureProperty)("grid","scroll-bar-width"),(0,o.stringPropertyParser)("scroll-bar-width")],[(0,o.hasFeatureProperty)("grid","cached-count"),(0,o.numberPropertyParser)("cached-count")],[(0,o.hasFeatureProperty)("grid","edit-mode"),(0,o.booleanPropertyParser)("edit-mode")],[(0,o.hasFeatureProperty)("grid","layout-direction"),(0,o.enumPropertyParser)("layout-direction","GridDirection.")],[(0,o.hasFeatureProperty)("grid","max-count"),(0,o.numberPropertyParser)("max-count")],[(0,o.hasFeatureProperty)("grid","min-count"),(0,o.numberPropertyParser)("min-count")],[(0,o.hasFeatureProperty)("grid","cell-length"),(0,o.numberPropertyParser)("cell-length")],[(0,o.hasFeatureProperty)("grid","multi-selectable"),(0,o.booleanPropertyParser)("multi-selectable")],[(0,o.hasFeatureProperty)("grid","support-animation"),(0,o.booleanPropertyParser)("support-animation")]],t.gridItemParserArray=[[(0,o.hasFeatureProperty)("grid-item","row-start"),(0,o.numberPropertyParser)("row-start")],[(0,o.hasFeatureProperty)("grid-item","row-end"),(0,o.numberPropertyParser)("row-end")],[(0,o.hasFeatureProperty)("grid-item","column-start"),(0,o.numberPropertyParser)("column-start")],[(0,o.hasFeatureProperty)("grid-item","column-end"),(0,o.numberPropertyParser)("column-end")],[(0,o.hasFeatureProperty)("grid-item","force-rebuild"),(0,o.booleanPropertyParser)("force-rebuild")],[(0,o.hasFeatureProperty)("grid-item","selectable"),(0,o.booleanPropertyParser)("selectable")]]},9248:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dealWithSrc=t.imageParserArray=t.isTargetComponent=void 0;const o=r(8122);function n(e){return null===e.match(/\$(r|rawfile)\('(.*)'\)$/)?(0,o.quoteString)(e):e}t.isTargetComponent=(0,o.curry)(((e,t)=>t.type===e)),t.imageParserArray=[[(0,t.isTargetComponent)("image"),function(e,t){var r;const a=e.dynamicProperty.get("src");if(!(0,o.isEmptyOrUndefined)(a))return void t.setParams(a);const i=null!==(r=e.property.get("src"))&&void 0!==r?r:"";t.setParams(n(i))}],[(0,o.hasFeatureProperty)("image","alt"),(0,o.stringPropertyParser)("alt")],[(0,o.hasFeatureProperty)("image","object-fit"),(0,o.enumPropertyParser)("object-fit","ImageFit.")],[(0,o.hasFeatureProperty)("image","object-repeat"),(0,o.enumPropertyParser)("object-repeat","ImageRepeat.")],[(0,o.hasFeatureProperty)("image","interpolation"),(0,o.enumPropertyParser)("interpolation","ImageInterpolation.")],[(0,o.hasFeatureProperty)("image","render-mode"),(0,o.enumPropertyParser)("render-mode","ImageRenderMode.")],[function(e){return e.hasProperty("source-size-width")||e.hasProperty("source-size-height")},function(e,t){let r=e.getProperty("source-size-width"),n=e.getProperty("source-size-height");if((0,o.isEmptyOrUndefined)(r)&&(0,o.isEmptyOrUndefined)(n))return;const a=e.dynamicProperty.has("source-size-width"),i=e.dynamicProperty.has("source-size-height");r="0"===r||(0,o.isEmptyOrUndefined)(r)?"0":a?r:r.substring(0,r.length-2),n="0"===n||(0,o.isEmptyOrUndefined)(n)?"0":i?n:n.substring(0,n.length-2);const s=new Map([["width",r],["height",n]]);t.properties.set("sourceSize",s)}]],t.dealWithSrc=n},7907:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.listItemParserArray=t.listParserArray=void 0;const o=r(8122);t.listParserArray=[[(0,o.hasFeatureProperty)("list","space"),(0,o.stringParamParser)("space")],[(0,o.hasFeatureProperty)("list","initial-index"),(0,o.rawDataParamParser)("initial-index")],[(0,o.hasFeatureProperty)("list","list-direction"),(0,o.enumPropertyParser)("list-direction","Axis.")],[function(e){return"list"===e.type&&(e.hasProperty("divider-stroke-width")||e.hasProperty("divider-color")||e.hasProperty("divider-start-margin")||e.hasProperty("divider-end-margin"))},function(e,t){const r=e.property.get("divider-stroke-width"),n=e.dynamicProperty.get("divider-stroke-width"),a=new Map([["strokeWidth",`${(0,o.quoteString)(null!=r?r:"0")}`]]);(0,o.isEmptyOrUndefined)(n)||a.set("strokeWidth",n);const i=e.property.get("divider-color"),s=e.dynamicProperty.get("divider-color"),p=e.property.get("divider-start-margin"),l=e.dynamicProperty.get("divider-start-margin"),c=e.property.get("divider-end-margin"),u=e.dynamicProperty.get("divider-end-margin");(0,o.isEmptyOrUndefined)(s)?(0,o.isEmptyOrUndefined)(i)||a.set("color",(0,o.dealWithColor)(i)):a.set("color",s),(0,o.isEmptyOrUndefined)(l)?(0,o.isEmptyOrUndefined)(p)||a.set("startMargin",(0,o.quoteString)(p)):a.set("startMargin",l),(0,o.isEmptyOrUndefined)(u)?(0,o.isEmptyOrUndefined)(c)||a.set("endMargin",(0,o.quoteString)(c)):a.set("endMargin",u),t.properties.set("divider",a)}],[(0,o.hasFeatureProperty)("list","edit-mode"),(0,o.booleanPropertyParser)("edit-mode")],[(0,o.hasFeatureProperty)("list","edge-effect"),(0,o.enumPropertyParser)("edge-effect","EdgeEffect.")],[(0,o.hasFeatureProperty)("list","chain-animation"),(0,o.booleanPropertyParser)("chain-animation")]],t.listItemParserArray=[[(0,o.hasFeatureProperty)("list-item","sticky"),(0,o.enumPropertyParser)("sticky","Sticky.")],[(0,o.hasFeatureProperty)("list-item","editable"),(0,o.booleanPropertyParser)("editable")]]},8191:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.navigationParserArray=void 0;const o=r(8122);t.navigationParserArray=[[(0,o.hasFeatureProperty)("navigation","navigation-title"),function(e,t){const r=e.getProperty("navigation-title"),n=e.dynamicProperty.get("navigation-title");(0,o.isEmptyOrUndefined)(n)?(0,o.isEmptyOrUndefined)(r)||t.properties.set("title",(0,o.quoteString)(r)):t.properties.set("title",n)}],[(0,o.hasFeatureProperty)("navigation","subTitle"),(0,o.stringPropertyParser)("subTitle")],[(0,o.hasFeatureProperty)("navigation","menus"),(0,o.objectPropertyParser)("menus")],[(0,o.hasFeatureProperty)("navigation","titleMode"),(0,o.enumPropertyParser)("titleMode","NavigationTitleMode.")],[(0,o.hasFeatureProperty)("navigation","toolBar"),(0,o.objectPropertyParser)("toolBar")],[(0,o.hasFeatureProperty)("navigation","hideToolBar"),(0,o.booleanPropertyParser)("hideToolBar")],[(0,o.hasFeatureProperty)("navigation","hideTitleBar"),(0,o.booleanPropertyParser)("hideTitleBar")],[(0,o.hasFeatureProperty)("navigation","hideBackButton"),(0,o.booleanPropertyParser)("hideBackButton")]]},2565:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.textPickerParserArray=t.datePickerParserArray=t.timePickerParserArray=void 0;const o=r(8122);t.timePickerParserArray=[[(0,o.hasFeatureProperty)("timePicker","datetime-selected"),(0,o.dateParamParser)("datetime-selected","selected")],[(0,o.hasFeatureProperty)("timePicker","useMilitaryTime"),(0,o.booleanPropertyParser)("useMilitaryTime")]],t.datePickerParserArray=[[(0,o.hasFeatureProperty)("datePicker","datetime-selected"),(0,o.dateParamParser)("datetime-selected","selected")],[(0,o.hasFeatureProperty)("datePicker","start"),(0,o.dateParamParser)("start","start")],[(0,o.hasFeatureProperty)("datePicker","end"),(0,o.dateParamParser)("end","end")],[(0,o.hasFeatureProperty)("datePicker","lunar"),(0,o.booleanPropertyParser)("lunar")]],t.textPickerParserArray=[[(0,o.hasFeatureProperty)("textPicker","range"),(0,o.arrayParamParser)("range")],[(0,o.hasFeatureProperty)("textPicker","textPicker-selected"),(0,o.customRawDataParamParser)("textPicker-selected","selected")],[(0,o.hasFeatureProperty)("textPicker","defaultPickerItemHeight"),(0,o.stringPropertyParser)("defaultPickerItemHeight")]]},8483:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.progressParserArray=void 0;const o=r(8122);t.progressParserArray=[[function(e){return"progress"===e.type&&(e.hasProperty("value")||e.hasProperty("total")||e.hasProperty("style"))},function(e,t){var r;(0,o.dynamicParamParser)("value",e,t)||t.params instanceof Map&&t.params.set("value",null!==(r=e.getProperty("value"))&&void 0!==r?r:"0")}],[(0,o.hasFeatureProperty)("progress","total"),(0,o.rawDataParamParser)("total")],[(0,o.hasFeatureProperty)("progress","style"),(0,o.enumParamParser)("style","ProgressStyle.")],[(0,o.hasFeatureProperty)("progress","color"),(0,o.colorPropertyParser)("color")]]},4925:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.refreshParserArray=void 0;const o=r(8122);t.refreshParserArray=[[(0,o.hasFeatureProperty)("refresh","friction"),(0,o.rawDataParamParser)("friction")],[(0,o.hasFeatureProperty)("refresh","offset"),(0,o.stringParamParser)("offset")],[(0,o.hasFeatureProperty)("refresh","refreshing"),(0,o.booleanParamParser)("refreshing")]]},1790:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dealWithRowAlignItems=t.dealWithColumnAlignItems=t.rowParserArray=t.columnParserArray=void 0;const o=r(8122),n=(0,o.curry)(((e,t,r,n)=>{if(!(n.properties instanceof Map))return;const a=r.dynamicProperty.get(e);if(!(0,o.isEmptyOrUndefined)(a))return void n.properties.set("justifyContent",a);const i=r.property.get(e);if((0,o.isEmptyOrUndefined)(i))return;let s=(0,o.getEtsEnumValue)(t,i);"flex-start"===i?s=t+"Start":"flex-end"===i&&(s=t+"End"),n.properties.set("justifyContent",s)}));function a(e){let t=(0,o.getEtsEnumValue)("HorizontalAlign.",e);return"flex-start"===e?t="HorizontalAlign.Start":"flex-end"===e&&(t="HorizontalAlign.End"),t}function i(e){let t=(0,o.getEtsEnumValue)("VerticalAlign.",e);return"flex-start"===e?t="VerticalAlign.Top":"flex-end"===e&&(t="VerticalAlign.Bottom"),t}t.columnParserArray=[[(0,o.hasFeatureProperty)("column","space"),(0,o.stringParamParser)("space")],[(0,o.hasFeatureProperty)("column","align-items-column"),function(e,t){const r=e.dynamicProperty.get("align-items-column");if(!(0,o.isEmptyOrUndefined)(r))return void t.properties.set("alignItems",r);const n=e.property.get("align-items-column");if((0,o.isEmptyOrUndefined)(n))return;const i=a(n);t.properties.set("alignItems",i)}],[(0,o.hasFeatureProperty)("column","justify-content-rc"),n("justify-content-rc","FlexAlign.")]],t.rowParserArray=[[(0,o.hasFeatureProperty)("row","space"),(0,o.stringParamParser)("space")],[(0,o.hasFeatureProperty)("row","align-items-row"),function(e,t){const r=e.dynamicProperty.get("align-items-row");if(!(0,o.isEmptyOrUndefined)(r))return void t.properties.set("alignItems",r);const n=e.property.get("align-items-row");if((0,o.isEmptyOrUndefined)(n))return;const a=i(n);t.properties.set("alignItems",a)}],[(0,o.hasFeatureProperty)("row","justify-content-rc"),n("justify-content-rc","FlexAlign.")]],t.dealWithColumnAlignItems=a,t.dealWithRowAlignItems=i},7375:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.scrollParserArray=void 0;const o=r(8122);t.scrollParserArray=[[(0,o.hasFeatureProperty)("scroll","scrollable"),(0,o.enumPropertyParser)("scrollable","ScrollDirection.")],[(0,o.hasFeatureProperty)("scroll","scroll-bar"),(0,o.enumPropertyParser)("scroll-bar","BarState.")],[(0,o.hasFeatureProperty)("scroll","scroll-bar-color"),(0,o.colorPropertyParser)("scroll-bar-color")],[(0,o.hasFeatureProperty)("scroll","scroll-bar-width"),(0,o.stringPropertyParser)("scroll-bar-width")],[(0,o.hasFeatureProperty)("scroll","edge-effect-scroll"),function(e,t){const r="edge-effect-scroll";if((0,o.dynamicPropertyParser)(r,e,t))return;const n=e.property.get(r);(0,o.isEmptyOrUndefined)(n)||t.properties.set("edgeEffect",(0,o.getEtsEnumValue)("EdgeEffect.",n))}],[(0,o.hasFeatureProperty)("scroll","scroller"),o.scrollerParamParser]]},9284:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.searchParserArray=void 0;const o=r(8122),n=r(8014);function a(e,t,r,n){const a=new Map([["value","search-value"],["placeholder","search-placeholder"],["icon","icon"],["controller","search-controller"]]).get(e);if(void 0===a)return;const i=r.getProperty(a),s=r.dynamicProperty.get(a);"controller"!==e||(0,o.isEmptyOrUndefined)(s)?(0,o.isEmptyOrUndefined)(s)?(0,o.isEmptyOrUndefined)(i)||t.push(`${e}: ${(0,o.quoteString)(i)}`):t.push(`${e}: ${(0,o.getContentName)(s)}`):t.push(`${e}: ${s}`)}t.searchParserArray=[[(0,o.hasFeatureProperty)("search","text-font-size"),(0,n.selectFontParser)("text-font","size")],[(0,o.hasFeatureProperty)("search","text-font-style"),(0,n.selectFontParser)("text-font","style")],[(0,o.hasFeatureProperty)("search","text-font-weight"),(0,n.selectFontParser)("text-font","weight")],[(0,o.hasFeatureProperty)("search","text-font-family"),(0,n.selectFontParser)("text-font","family")],[(0,o.hasFeatureProperty)("search","placeholder-font-size"),(0,n.selectFontParser)("placeholder-font","size")],[(0,o.hasFeatureProperty)("search","placeholder-font-style"),(0,n.selectFontParser)("placeholder-font","style")],[(0,o.hasFeatureProperty)("search","placeholder-font-weight"),(0,n.selectFontParser)("placeholder-font","weight")],[(0,o.hasFeatureProperty)("search","placeholder-font-family"),(0,n.selectFontParser)("placeholder-font","family")],[(0,o.hasFeatureProperty)("search","placeholderColor"),(0,o.colorPropertyParser)("placeholderColor")],[(0,o.hasFeatureProperty)("search","search-text-align"),o.searchTextAlign],[function(e){return"search"===e.type},function(e,t){const r=[];a("value",r,e),a("placeholder",r,e),a("icon",r,e),a("controller",r,e),t.setParams(`{${r.join(", ")}}`)}],[(0,o.hasFeatureProperty)("search","search-button"),(0,o.stringPropertyParser)("search-button")],[(0,o.hasFeatureProperty)("search","copy-option"),(0,o.enumPropertyParser)("copy-option","CopyOptions.")]]},8014:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.selectParserArray=t.selectFontParser=void 0;const o=r(8122);t.selectFontParser=(0,o.curry)(((e,t,r,n)=>{let a=n.properties.get((0,o.getEtsPropName)(e));void 0===a&&(a=new Map);const i=`${e}-${t}`,s=r.property.get(i),p=r.dynamicProperty.get(i);"string"!=typeof a&&((0,o.isEmptyOrUndefined)(p)?(0,o.isEmptyOrUndefined)(s)||("size"!==t&&"family"!==t||a.set(t,(0,o.quoteString)(s)),"style"===t&&a.set(t,(0,o.getEtsEnumValue)("FontStyle.",s)),"weight"===t&&a.set(t,(0,o.dealWithFontWeight)(s))):a.set(t,p)),n.properties.set((0,o.getEtsPropName)(e),a)})),t.selectParserArray=[[(0,o.hasSelectOption)("select","select-option"),function(e,t){const r=e.dynamicProperty.get("select-option");t.setParams(null!=r?r:'[{value: ""}]')}],[(0,o.hasFeatureProperty)("select","select-value"),function(e,t){const r=e.getProperty("select-value"),n=e.dynamicProperty.get("select-value");(0,o.isEmptyOrUndefined)(n)?(0,o.isEmptyOrUndefined)(r)||t.properties.set("value",(0,o.quoteString)(r)):t.properties.set("value",(0,o.getContentName)(n))}],[(0,o.hasFeatureProperty)("select","selected"),(0,o.numberPropertyParser)("selected")],[(0,o.hasFeatureProperty)("select","font-size"),(0,t.selectFontParser)("font","size")],[(0,o.hasFeatureProperty)("select","font-style"),(0,t.selectFontParser)("font","style")],[(0,o.hasFeatureProperty)("select","font-weight"),(0,t.selectFontParser)("font","weight")],[(0,o.hasFeatureProperty)("select","font-family"),(0,t.selectFontParser)("font","family")],[(0,o.hasFeatureProperty)("select","selected-option-font-size"),(0,t.selectFontParser)("selected-option-font","size")],[(0,o.hasFeatureProperty)("select","selected-option-font-style"),(0,t.selectFontParser)("selected-option-font","style")],[(0,o.hasFeatureProperty)("select","selected-option-font-weight"),(0,t.selectFontParser)("selected-option-font","weight")],[(0,o.hasFeatureProperty)("select","selected-option-font-family"),(0,t.selectFontParser)("selected-option-font","family")],[(0,o.hasFeatureProperty)("select","selected-option-font-color"),(0,o.colorPropertyParser)("selected-option-font-color")],[(0,o.hasFeatureProperty)("select","selected-option-bg-color"),(0,o.colorPropertyParser)("selected-option-bg-color")],[(0,o.hasFeatureProperty)("select","option-font-size"),(0,t.selectFontParser)("option-font","size")],[(0,o.hasFeatureProperty)("select","option-font-style"),(0,t.selectFontParser)("option-font","style")],[(0,o.hasFeatureProperty)("select","option-font-weight"),(0,t.selectFontParser)("option-font","weight")],[(0,o.hasFeatureProperty)("select","option-font-family"),(0,t.selectFontParser)("option-font","family")],[(0,o.hasFeatureProperty)("select","option-font-color"),(0,o.colorPropertyParser)("option-font-color")],[(0,o.hasFeatureProperty)("select","option-bg-color"),(0,o.colorPropertyParser)("option-bg-color")]]},2563:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sliderParserArray=void 0;const o=r(8122);t.sliderParserArray=[[(0,o.hasFeatureProperty)("slider","value"),(0,o.rawDataParamParser)("value")],[(0,o.hasFeatureProperty)("slider","min"),(0,o.rawDataParamParser)("min")],[(0,o.hasFeatureProperty)("slider","max"),(0,o.rawDataParamParser)("max")],[(0,o.hasFeatureProperty)("slider","step"),(0,o.rawDataParamParser)("step")],[(0,o.hasFeatureProperty)("slider","style"),(0,o.enumParamParser)("style","SliderStyle.")],[(0,o.hasFeatureProperty)("slider","block-color"),(0,o.colorPropertyParser)("block-color")],[(0,o.hasFeatureProperty)("slider","track-color"),(0,o.colorPropertyParser)("track-color")],[(0,o.hasFeatureProperty)("slider","selected-color"),(0,o.colorPropertyParser)("selected-color")],[(0,o.hasFeatureProperty)("slider","show-steps"),(0,o.booleanPropertyParser)("show-steps")],[(0,o.hasFeatureProperty)("slider","show-tips"),(0,o.booleanPropertyParser)("show-tips")]]},8936:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stackParserArray=void 0;const o=r(8122);t.stackParserArray=[[(0,o.hasFeatureProperty)("stack","align-content-stack"),function(e,t){if(!(t.params instanceof Map))return;const r=e.dynamicProperty.get("align-content-stack");if(!(0,o.isEmptyOrUndefined)(r))return void t.params.set("alignContent",r);const n=e.property.get("align-content-stack");if((0,o.isEmptyOrUndefined)(n))return;const a=(0,o.getEtsEnumValue)("Alignment.",n);t.params.set((0,o.getEtsPropName)("alignContent"),a)}]]},780:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.swiperParserArray=void 0;const o=r(8122);t.swiperParserArray=[[(0,o.hasFeatureProperty)("swiper","index"),(0,o.numberPropertyParser)("index")],[(0,o.hasFeatureProperty)("swiper","auto-play"),(0,o.booleanPropertyParser)("auto-play")],[(0,o.hasFeatureProperty)("swiper","interval"),(0,o.numberPropertyParser)("interval")],[(0,o.hasFeatureProperty)("swiper","indicator"),(0,o.booleanPropertyParser)("indicator")],[(0,o.hasFeatureProperty)("swiper","loop"),(0,o.booleanPropertyParser)("loop")],[(0,o.hasFeatureProperty)("swiper","duration"),(0,o.numberPropertyParser)("duration")],[(0,o.hasFeatureProperty)("swiper","vertical"),(0,o.booleanPropertyParser)("vertical")],[(0,o.hasFeatureProperty)("swiper","item-space"),(0,o.stringPropertyParser)("item-space")],[(0,o.hasFeatureProperty)("swiper","cached-count"),(0,o.numberPropertyParser)("cached-count")],[(0,o.hasFeatureProperty)("swiper","disable-swipe"),(0,o.booleanPropertyParser)("disable-swipe")]]},7036:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tabContentParserArray=void 0;const o=r(8122),n=r(9248);t.tabContentParserArray=[[function(e){return"tab-content"===e.type&&(e.hasProperty("tabBar-icon")||e.hasProperty("tabBar-text"))},function(e,t){var r,a;const i=new Map,s=null!==(r=e.getProperty("tabBar-icon"))&&void 0!==r?r:"",p=null!==(a=e.getProperty("tabBar-text"))&&void 0!==a?a:"TabBar",l=e.dynamicProperty.has("tabBar-text"),c=e.dynamicProperty.has("tabBar-icon");(0,o.isEmptyOrUndefined)(s)||i.set("icon",c?s:(0,n.dealWithSrc)(s)),void 0!==p&&i.set("text",l?p:(0,o.quoteString)(p)),i.size>0&&t.properties.set("tabBar",i)}]]},2973:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tabsParserArray=void 0;const o=r(8122),n=(0,o.curry)(((e,t)=>{const r=e.dynamicProperty.get("tabs-scrollable");if(void 0!==r&&""!==r.trim())return void t.properties.set("scrollable",r);const n=e.property.get("tabs-scrollable");(0,o.isEmptyOrUndefined)(n)||t.properties.set("scrollable",n)}));t.tabsParserArray=[[(0,o.hasFeatureProperty)("tabs","bar-position"),(0,o.enumParamParser)("bar-position","BarPosition.")],[(0,o.hasFeatureProperty)("tabs","index"),(0,o.rawDataParamParser)("index")],[(0,o.hasFeatureProperty)("tabs","controller"),(0,o.rawDataParamParser)("controller")],[(0,o.hasFeatureProperty)("tabs","vertical"),(0,o.booleanPropertyParser)("vertical")],[(0,o.hasFeatureProperty)("tabs","tabs-scrollable"),n],[(0,o.hasFeatureProperty)("tabs","bar-mode"),(0,o.enumPropertyParser)("bar-mode","BarMode.")],[(0,o.hasFeatureProperty)("tabs","bar-width"),(0,o.stringPropertyParser)("bar-width")],[(0,o.hasFeatureProperty)("tabs","bar-height"),(0,o.stringPropertyParser)("bar-height")],[(0,o.hasFeatureProperty)("tabs","animation-duration"),(0,o.numberPropertyParser)("animation-duration")]]},1162:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.textInputParserArray=void 0;const o=r(8122);t.textInputParserArray=[[(0,o.hasFeatureProperty)("text-input","placeholder"),(0,o.stringParamParser)("placeholder")],[(0,o.hasFeatureProperty)("text-input","textInput-type"),function(e,t){const r=e.dynamicProperty.get("textInput-type");if(!(0,o.isEmptyOrUndefined)(r))return void t.properties.set("type",r);const n=e.property.get("textInput-type");(0,o.isEmptyOrUndefined)(n)||t.properties.set("type","InputType."+n)}],[(0,o.hasFeatureProperty)("text-input","placeholderColor"),(0,o.colorPropertyParser)("placeholderColor")],[function(e){return"text-input"===e.type&&(e.hasProperty("placeholderFont-size")||e.hasProperty("placeholderFont-weight")||e.hasProperty("placeholderFont-family")||e.hasProperty("placeholderFont-style"))},function(e,t){const r=e.property.get("placeholderFont-size"),n=e.dynamicProperty.get("placeholderFont-size"),a=e.property.get("placeholderFont-weight"),i=e.dynamicProperty.get("placeholderFont-weight"),s=e.property.get("placeholderFont-family"),p=e.dynamicProperty.get("placeholderFont-family"),l=e.property.get("placeholderFont-style"),c=e.dynamicProperty.get("placeholderFont-style"),u=new Map;(0,o.isEmptyOrUndefined)(n)?(0,o.isEmptyOrUndefined)(r)||u.set("size",parseInt(r)):u.set("size",n),(0,o.isEmptyOrUndefined)(i)?(0,o.isEmptyOrUndefined)(a)||u.set("weight",isNaN(Number(a))?(0,o.getEtsEnumValue)("FontWeight.",a):a):u.set("weight",i),(0,o.isEmptyOrUndefined)(p)?(0,o.isEmptyOrUndefined)(s)||u.set("family",(0,o.quoteString)(s)):u.set("family",p),(0,o.isEmptyOrUndefined)(c)?(0,o.isEmptyOrUndefined)(l)||u.set("style",(0,o.getEtsEnumValue)("FontStyle.",l)):u.set("style",c),t.properties.set("placeholderFont",u)}],[(0,o.hasFeatureProperty)("text-input","enterKeyType"),(0,o.enumPropertyParser)("enterKeyType","EnterKeyType.")],[(0,o.hasFeatureProperty)("text-input","caretColor"),(0,o.colorPropertyParser)("caretColor")],[(0,o.hasFeatureProperty)("text-input","maxLength"),(0,o.numberPropertyParser)("maxLength")]]},8681:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.textParserArray=void 0;const o=r(8122);t.textParserArray=[[(0,o.hasFeatureProperty)("text","content"),o.contentParamParser],[(0,o.hasFeatureProperty)("text","text-align"),(0,o.enumPropertyParser)("text-align","TextAlign.")],[(0,o.hasFeatureProperty)("text","text-overflow"),function(e,t){const r=e.dynamicProperty.get("text-overflow");if(!(0,o.isEmptyOrUndefined)(r))return void t.properties.set("textOverflow",new Map([["overflow",r]]));const n=e.property.get("text-overflow");(0,o.isEmptyOrUndefined)(n)||t.properties.set("textOverflow",new Map([["overflow","TextOverflow."+(0,o.firstUpperCase)(n)]]))}],[(0,o.hasFeatureProperty)("text","max-lines"),(0,o.numberPropertyParser)("max-lines")],[(0,o.hasFeatureProperty)("text","line-height"),(0,o.stringPropertyParser)("line-height")],[function(e){return"text"===e.type&&(e.hasProperty("decoration-type")||e.hasProperty("decoration-color"))},function(e,t){const r=e.property.get("decoration-type"),n=e.dynamicProperty.get("decoration-type"),a=e.property.get("decoration-color"),i=e.dynamicProperty.get("decoration-color");if((0,o.isEmptyOrUndefined)(r)&&(0,o.isEmptyOrUndefined)(a)&&(0,o.isEmptyOrUndefined)(n)&&(0,o.isEmptyOrUndefined)(i))return;const s=new Map;(0,o.isEmptyOrUndefined)(n)?s.set("type",(0,o.isEmptyOrUndefined)(r)?"TextDecorationType.None":(0,o.getEtsEnumValue)("TextDecorationType.",r)):s.set("type",n),t.properties.set("decoration",s),(0,o.isEmptyOrUndefined)(i)?(0,o.isEmptyOrUndefined)(a)||s.set("color",(0,o.dealWithColor)(a)):s.set("color",i)}],[(0,o.hasFeatureProperty)("text","baseline-offset"),(0,o.stringPropertyParser)("baseline-offset")],[(0,o.hasFeatureProperty)("text","text-case"),(0,o.enumPropertyParser)("text-case","TextCase.")],[(0,o.hasFeatureProperty)("text","font-size"),(0,o.stringPropertyParser)("font-size")],[(0,o.hasFeatureProperty)("text","font-style"),(0,o.enumPropertyParser)("font-style","FontStyle.")],[(0,o.hasFeatureProperty)("text","font-weight"),o.fontWeightPropertyParser],[(0,o.hasFeatureProperty)("text","font-family"),(0,o.stringPropertyParser)("font-family")]]},4313:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toggleParseArray=void 0;const o=r(8122);t.toggleParseArray=[[(0,o.hasFeatureProperty)("toggle","toggle-type"),function(e,t){const r="toggle-type";if((0,o.customDynamicParamParser)(r,"type",e,t))return;const n=e.property.get(r);!(0,o.isEmptyOrUndefined)(n)&&t.params instanceof Map&&t.params.set("type",(0,o.getEtsEnumValue)("ToggleType.",n))}],[(0,o.hasFeatureProperty)("toggle","isOn"),(0,o.booleanParamParser)("isOn")],[(0,o.hasFeatureProperty)("toggle","selectedColor"),(0,o.colorPropertyParser)("selectedColor")],[(0,o.hasFeatureProperty)("toggle","switchPointColor"),(0,o.colorPropertyParser)("switchPointColor")]]},8122:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getBuilderUniqueName=t.getEdgeBorderDirection=t.getBorderDirections=t.dealWithAlignSelf=t.dealWithScrollEdgeEffect=t.dealWithBackgroundRepeat=t.dealWithBackgroundImageSize=t.dealWithBackgroundImagePosition=t.dealWithFontWeight=t.getContentName=t.scrollerParamParser=t.dealWithWrap=t.getBackgroundImageSizeEnumValue=t.getBackgroundImagePositionEnumValue=t.contentParamParser=t.labelParamParser=t.fontWeightPropertyParser=t.dealWithColor=t.getEtsEnumValue=t.getEtsPropName=t.parseTagName=t.firstUpperCase=t.getForEachObj=t.colorPropertyParser=t.enumParamParser=t.arrayParamParser=t.booleanParamParser=t.customRawDataParamParser=t.rawDataParamParser=t.dateParamParser=t.stringParamParser=t.dynamicParamParser=t.searchTextAlign=t.enumPropertyParser=t.booleanPropertyParser=t.numberPropertyParser=t.isEmptyOrUndefined=t.objectPropertyParser=t.stringPropertyParser=t.customDynamicParamParser=t.dynamicPropertyParser=t.quoteString=t.hasSelectOption=t.hasFeatureProperty=t.hasCommonProperty=t.curry=void 0;const o=r(1195),n=r(4294);function a(e){return(...t)=>t.lengtht.property.has(e)||t.dynamicProperty.has(e))),t.hasFeatureProperty=a(((e,t,r)=>r.type===e&&(r.property.has(t)||r.dynamicProperty.has(t)))),t.hasSelectOption=a(((e,t,r)=>r.type===e)),t.quoteString=i,t.dynamicPropertyParser=s,t.customDynamicParamParser=p,t.stringPropertyParser=a(((e,t,r)=>{if(s(e,t,r))return;const o=t.property.get(e);void 0!==o&&r.properties.set(y(e),i(o))})),t.objectPropertyParser=a(((e,t,r)=>{if(s(e,t,r))return;const o=t.property.get(e);void 0!==o&&r.properties.set(y(e),o)})),t.isEmptyOrUndefined=l,t.numberPropertyParser=a(((e,t,r)=>{if(s(e,t,r))return;const o=t.property.get(e);l(o)||r.properties.set(y(e),o)})),t.booleanPropertyParser=a(((e,t,r)=>{if(s(e,t,r))return;const o=t.property.get(e);l(o)||r.properties.set(y(e),o)})),t.enumPropertyParser=a(((e,t,r,o)=>{if(s(e,r,o))return;const n=r.property.get(e);l(n)||o.properties.set(y(e),d(t,n))})),t.searchTextAlign=function(e,t){const r=e.dynamicProperty.get("search-text-align");if(void 0!==r&&""!==r.trim())return void t.properties.set("textAlign",r);const o=e.property.get("search-text-align");l(o)||t.properties.set("textAlign",d("TextAlign.",o))},t.dynamicParamParser=c,t.stringParamParser=a(((e,t,r)=>{if(c(e,t,r))return;const o=t.property.get(e);void 0!==o&&r.params instanceof Map&&r.params.set(y(e),i(o))})),t.dateParamParser=a(((e,t,r,o)=>{const n=r.dynamicProperty.get(e);if(void 0!==n&&""!==n.trim()&&o.params instanceof Map)return void o.params.set(t,n);const a=r.property.get(e);void 0!==a&&o.params instanceof Map&&o.params.set(t,(e=>void 0===e||""===e?"new Date()":"new Date ("+i(e)+")")(a))})),t.rawDataParamParser=a(((e,t,r)=>{if(c(e,t,r))return;const o=t.property.get(e);!l(o)&&r.params instanceof Map&&r.params.set(y(e),o)})),t.customRawDataParamParser=a(((e,t,r,o)=>{if(p(e,t,r,o))return;const n=r.property.get(e);!l(n)&&o.params instanceof Map&&o.params.set(t,n)})),t.booleanParamParser=a(((e,r,o)=>{(0,t.rawDataParamParser)(e,r,o)})),t.arrayParamParser=a(((e,r,o)=>{(0,t.rawDataParamParser)(e,r,o)})),t.enumParamParser=a(((e,t,r,o)=>{if(c(e,r,o))return;const n=r.property.get(e);!l(n)&&o.params instanceof Map&&o.params.set(y(e),d(t,n))})),t.colorPropertyParser=a(((e,t,r)=>{if(s(e,t,r))return;let o=t.property.get(e);l(o)||(o=f(o),r.properties.set(y(e),o))})),t.getForEachObj=function(e){var t,r;const o=e.dynamicProperty.get("for"),n=e.dynamicProperty.get("keyGenerator"),a=null!==(t=e.property.get("item"))&&void 0!==t?t:"item",i=null!==(r=e.property.get("idx"))&&void 0!==r?r:"idx";return void 0!==e.dynamicProperty.get("for")?{for:o,key:n,item:a,idx:i}:null},t.firstUpperCase=u,t.parseTagName=function(e){return(0,n.getTagName)(e).split("-").map((e=>e[0].toUpperCase()+e.slice(1))).join("")},t.getEtsPropName=y,t.getEtsEnumValue=d,t.dealWithColor=f,t.fontWeightPropertyParser=function(e,t){const r=e.getProperty("font-weight");if(l(r))return;const o=g(r);t.properties.set("fontWeight",o)},t.labelParamParser=function(e,t){const r=e.dynamicProperty.get("label");if(!l(r))return void t.setParams(m(r));const o=e.property.get("label");"string"==typeof o&&t.setParams(i(o))},t.contentParamParser=function(e,t){const r=e.property.get("content"),o=e.dynamicProperty.get("content");l(o)?"string"==typeof r&&t.setParams(i(r)):t.setParams(m(o))},t.getBackgroundImagePositionEnumValue=function(e){const t=new Map([["top left","TopStart"],["top center","Top"],["top right","TopEnd"],["center left","Start"],["center center","Center"],["center right","End"],["bottom left","BottomStart"],["bottom center","Bottom"],["bottom right","BottomEnd"]]);return t.has(e)?`Alignment.${String(t.get(e))}`:""},t.getBackgroundImageSizeEnumValue=function(e){return new Set(["cover","contain","auto"]).has(e)?d("ImageSize.",e):""},t.dealWithWrap=function(e){let t=d("FlexWrap.",e);return"nowrap"===e&&(t="FlexWrap.NoWrap"),t},t.scrollerParamParser=function(e,t){const r=e.dynamicProperty.get("scroller");l(r)||t.setParams(r)},t.getContentName=m,t.dealWithFontWeight=g,t.dealWithBackgroundImagePosition=function(e){if(new Set(["TopStart","Top","TopEnd","Start","Center","End","BottomStart","Bottom","BottomEnd"]).has(e))return"Alignment."+e;const t=e.match(/^ *((0|[1-9][0-9]*)(px|vp|lpx|%)) +((0|[1-9][0-9]*)(px|vp|lpx|%)) *$/);return null!==t?`{ x: ${i(t[1])}, y: ${i(t[4])} }`:void 0},t.dealWithBackgroundImageSize=function(e){if(new Set(["Cover","Contain","Auto"]).has(e))return d("ImageSize.",e);const t=e.match(/^ *((0|[1-9][0-9]*)(px|vp|lpx|%))( *$| +((0|[1-9][0-9]*)(px|vp|lpx|%)) *$)/);return null!==t?void 0!==t[5]?`{ width: ${i(t[1])}, height: ${i(t[5])} }`:`{ width: ${i(t[1])} }`:void 0},t.dealWithBackgroundRepeat=function(e){const t=new Map([["repeat-x","X"],["repeat-y","Y"],["repeat","XY"],["no-repeat","NoRepeat"]]).get(e);if(null!=t&&""!==t)return d("ImageRepeat.",t)},t.dealWithScrollEdgeEffect=function(e){var t;const r=d("EdgeEffect.",e);return null!==(t=new Map([["Spring","EdgeEffect.Spring"],["Fade","EdgeEffect.Fade"],["None","EdgeEffect.None"]]).get(r))&&void 0!==t?t:r},t.dealWithAlignSelf=function(e){let t=d("ItemAlign.",e);return"flex-start"===e?t="ItemAlign.Start":"flex-end"===e&&(t="ItemAlign.End"),t},t.getBorderDirections=function(e){return"border-width"===e?["border-top-width","border-bottom-width","border-left-width","border-right-width"]:"border-color"===e?["border-top-color","border-bottom-color","border-left-color","border-right-color"]:"border-style"===e?["border-top-style","border-bottom-style","border-left-style","border-right-style"]:["border-top-left-radius","border-bottom-right-radius","border-bottom-left-radius","border-top-right-radius"]},t.getEdgeBorderDirection=function(e){var t;return e.includes("radius")?null!==(t=new Map([["border-top-left-radius","topLeft"],["border-top-right-radius","topRight"],["border-bottom-left-radius","bottomLeft"],["border-bottom-right-radius","bottomRight"]]).get(e))&&void 0!==t?t:e:e.split("-")[1]},t.getBuilderUniqueName=function(e,t){const r=`${y((0,n.getTagName)(e))}${u(y(t))}`;return`${r}_${(0,n.getUniqueId)(r)}`}},1912:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.events=t.parseVisualModel=void 0;const o=r(8122),n=r(7150),a=r(1778),i=r(8916),s=r(9248),p=r(8483),l=r(2563),c=r(8681),u=r(1790),y=r(8191),d=r(2153),f=r(780),m=r(2565),g=r(4313),h=r(5264),E=r(7907),T=r(7375),S=r(8014),P=r(4925),v=r(1162),b=r(9284),_=r(8936),N=r(2973),C=r(7036),O=r(2218),A=r(1147);t.parseVisualModel=function(e,r){r.setTagName((0,o.parseTagName)(e.type));const n=(0,o.getForEachObj)(e);r.setForEachObj(n);const a=void 0!==e.dynamicProperty.get("if")?e.dynamicProperty.get("if"):e.property.get("if");void 0===a?r.setIfBoolean(null):r.setIfBoolean(a);for(const t of M)("boolean"==typeof t[0]||t[0](e))&&t[1](e,r);!function(e,r){var o;const n="onDisappear",a="onDisAppear";for(let o of t.events){const t=e.property.get(o);o===n&&(o=a),void 0!==t&&""!==t&&("this"===t.split(".")[0]?r.properties.set(o,t+".bind(this)"):r.properties.set(o,t))}if(void 0!==e.property.get("newFunction")){const t=null!==(o=e.property.get("newFunction"))&&void 0!==o?o:"{}",i=JSON.parse(t);Object.keys(i).forEach((e=>{var t;const o=null!==(t=i[e].eventCodeGen)&&void 0!==t?t:"";e===n&&(e=a),r.properties.set(e,o)}))}}(e,r)},t.events=["onClick","onTouch","onAppear","onDisappear","onKeyEvent","onAreaChange","onItemDelete","onScrollIndex","onItemDragEnter","onItemDragMove","onItemDragLeave","onItemDragStart","onItemDrop","onComplete","onError","onFinish","onChange","onSubmit","onEditChanged","onStateChange","onRefreshing","onSelect","onScroll","onScrollEdge","onScrollEnd","onScrollBegin","onTitleModeChange","onCopy","onCut","onPaste"];const M=[...n.commonParserArray,...i.buttonParserArray,...a.dividerParserArray,...s.imageParserArray,...p.progressParserArray,...l.sliderParserArray,...c.textParserArray,...u.columnParserArray,...u.rowParserArray,...h.flexParserArray,...E.listParserArray,...E.listItemParserArray,...f.swiperParserArray,...v.textInputParserArray,...y.navigationParserArray,...m.timePickerParserArray,...m.textPickerParserArray,...P.refreshParserArray,...g.toggleParseArray,...S.selectParserArray,...m.datePickerParserArray,...T.scrollParserArray,...d.gridParserArray,...d.gridItemParserArray,...b.searchParserArray,..._.stackParserArray,...N.tabsParserArray,...C.tabContentParserArray,...O.checkboxParseArray,...A.checkboxGroupParseArray]},7571:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isEvent=t.isData=t.isUnknown=t.isContent=t.isAttribute=t.isStyle=t.styleMap=void 0;const o=r(904),n=["width","height","min-width","min-height","max-width","max-height","padding","padding-start","padding-end","padding-top","padding-right","padding-bottom","padding-left","margin","margin-start","margin-end","margin-top","margin-right","margin-bottom","margin-left","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","border-bottom-color","border-bottom-right-radius","border-left-width","border-left-style","border-left-color","border-bottom-left-radius","background-color","background","background-image","background-size","background-position","background-repeat","display","opacity","visibility","flex","flex-grow","flex-shrink","flex-basis","position","display","top","right","bottom","left","display-index","flex-weight","aspect-ratio"],a=["font-size","font-family","font-style","font-weight"],i=["text-align","line-height","text-decoration","letter-spacing","max-lines","text-overflow","allow-scale","min-font-size","max-font-size","font-size-step","prefer-font-sizes","color",...a],s=["allow-scale","text-decoration","color",...a],p=["text-color","allow-scale","icon-width","icon-height","radius",...a],l=["texton-color","textoff-color","text-padding","allow-scale",...a],c=["column-height","text-color","allow-scale","letter-spacing","text-decoration","line-height","opacity",...a],u=["text-color","allow-scale","letter-spacing",...a];t.styleMap=new Map([["common",new Set([...n])],["div",new Set(["flex-direction","overflow","flex-wrap","justify-content","align-items","align-content","grid-template-columns","grid-template-rows","grid-row-start","grid-row-end","grid-column-start","grid-column-end","grid-gap","grid-columns-gap","grid-rows-gap"])],["text",new Set([...i])],["image",new Set(["object-fit","match-text-direction","fit-original-size"])],["span",new Set([...s])],["input",new Set(["font-size","font-family","font-weight","color","placeholder-color","allow-scale"])],["button",new Set([...p])],["switch",new Set([...l])],["refresh",new Set(["progress-color"])],["divider",new Set(["stroke-width","line-cap","color"])],["chart",new Set(["stroke-width","radius","start-angle","total-angle","center-x","center-y","colors","weights"])],["picker",new Set([...c])],["picker-view",new Set(["color","font-size","selected-color","selected-font-size","focus-color","focus-font-size","disappear-color","disappear-font-size","font-family"])],["slider",new Set(["color","selected-color","block-color"])],["swiper",new Set(["indicator-color","indicator-selected-color","indicator-size","indicator-top","indicator-right","indicator-bottom","indicator-left"])],["list",new Set(["flex-direction","columns","item-extent","fade-color"])],["list-item",new Set(["column-span"])],["progress",new Set(["color","stroke-width","background-color","secondary-color","scale-width","scale-number","start-angle","total-angle","center-x","center-y","radius"])],["select",new Set(["font-family"])],["menu",new Set([...u])],["option",new Set(["color","font-family","allow-scale","font-size","font-weight","text-decoration"])],["video",new Set(["object-fit"])],["clock",new Set(["font-family"])]]);const y=new Map([["common",new Set(["id","ref","disabled","focusable","data","if","for"])],["image",new Set(["src","alt"])],["button",new Set(["type","value","icon","waiting"])],["refresh",new Set(["offset","refreshing","type","lasttime","friction"])],["input",new Set(["type","checked","name","value","placeholder","maxlength","enterkeytype","headericon"])],["switch",new Set(["checked","showtext","texton","textoff"])],["option",new Set(["value","selected","icon"])],["chart",new Set(["type","percent","datasets","options"])],["picker",new Set(["type","range","selected","start","end","lunar","lunarSwitch","columns","hours","containSecond","value","vibrate"])],["picker-view",new Set(["type","range","selected","start","end","lunar","lunarSwitch","columns","hours","containSecond","indicatorprefix","indicatorsuffix","vibrate"])],["slider",new Set(["min","max","step","showtips","showsteps","mode","value"])],["divider",new Set(["vertical"])],["list",new Set(["scrollpage","cachedcount","scrollbar","scrolleffect","shapemode","indexer","itemscale","itemcenter","updateeffect","scrollvibrate","initialindex","initialoffset"])],["list-item",new Set(["type","primary","section","sticky","stickyradius","clickeffect"])],["swiper",new Set(["index","autoplay","interval","indicator","digital","indicatordisabled","loop","duration","vertical"])],["progress",new Set(["type","percent","secondarypercent","clockwise"])],["menu",new Set(["target","title","type"])],["clock",new Set(["clockconfig","showdigit","hourswest"])],["badge",new Set(["placement","count","visible","maxcount","config","label"])],["video",new Set(["muted","src","autoplay","poster","controls","loop","starttime","direction","speed"])],["tabs",new Set(["index","vertical"])],["tab-bar",new Set(["mode"])],["tab-content",new Set(["scrollable"])]]),d=new Map([["common",new Set(["ontouchstart","ontouchmove","ontouchcancel","ontouchend","onclick","onlongpress","onfocus","onblur","onkey","onswipe"])],["image",new Set(["oncomplete","onerror"])],["input",new Set(["onchange","onenterkeyclick"])],["select",new Set(["onchange"])],["refresh",new Set(["onrefresh","onpulldown"])],["swiper",new Set(["onchange","onrotation"])],["list",new Set(["onindexerchange","onscroll","onscrollbottom","onscrolltop","onscrollend","onscrolltouchup","onrequestitem"])],["list-item",new Set(["onsticky"])],["menu",new Set(["onselected","oncancel"])],["picker",new Set(["oncolumnchange","onchange","oncancel"])],["picker-view",new Set(["oncolumnchange","onchange"])],["video",new Set(["onprepared","onstart","onpause","onfinish","onerror","onseeking","onseeked","ontimeupdate","onfullscreenchange","onstop"])],["tabs",new Set(["onchange"])],["switch",new Set(["onchange"])],["dialog",new Set(["oncancel"])],["slider",new Set(["onchange"])]]),f=new Map([["common",new Set(["onClick","onTouch","onAppear","onDisappear","onKeyEvent","onAreaChange"])],["image",new Set(["onComplete","onError","onFinish"])],["swiper",new Set(["onChange"])],["list",new Set(["onItemDelete","onScrollIndex","onItemDragEnter","onItemDragMove","onItemDragLeave","onItemDragStart","onItemDrop"])],["text-input",new Set(["onChange","onSubmit","onEditChanged"])],["refresh",new Set(["onStateChange","onRefreshing"])],["toggle",new Set(["onChange"])],["timePicker",new Set(["onChange"])],["textPicker",new Set(["onChange"])],["select",new Set(["onSelect"])],["datePicker",new Set(["onChange"])],["search",new Set(["onSubmit","onChange","onCopy","onCut","onPaste"])],["grid",new Set(["onScrollIndex","onItemDragStart","onItemDragEnter","onItemDragMove","onItemDragLeave","onItemDrop"])],["grid-item",new Set(["onSelect"])],["scroll",new Set(["onScroll","onScrollEdge","onScrollEnd","onScrollBegin"])],["navigation",new Set(["onTitleModeChange"])],["tabs",new Set(["onChange"])],["checkbox",new Set(["onChange"])],["checkboxGroup",new Set(["onChange"])]]);function m(e,t,r){const o=t.get(r);return void 0!==o&&o.has(e)}function g(e,r){return m(e,t.styleMap,"common")||m(e,t.styleMap,r)}function h(e,t){return(0,o.getDomain)()===o.Domain.ETS?m(e,f,"common")||m(e,f,t):E(e,t)||T(e,t)}function E(e,t){return m(e,y,"common")||m(e,y,t)}function T(e,t){return m(e,d,"common")||m(e,d,t)}t.isStyle=g,t.isAttribute=h,t.isContent=function(e){return"content"===e},t.isUnknown=function(e,t){return!g(e,t)&&!h(e,t)},t.isData=E,t.isEvent=T},8964:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.checkboxGroupProperties=t.checkboxProperties=void 0;const o=r(1513);t.checkboxProperties=[{propertySector:o.Sector.FEATURE_ETS,propertySet:Object.assign(Object.assign({name:"Select",property:"select-visual"},o.commonParamsForJudge),{defaults:!1})},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"Name",property:"name-visual",type:o.TypeName.BASE,etsType:o.EtsType.COMB_CONTENT,defaults:""}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"Group",property:"group-visual",type:o.TypeName.BASE,etsType:o.EtsType.COMB_CONTENT,defaults:""}}],t.checkboxGroupProperties=[{propertySector:o.Sector.FEATURE_ETS,propertySet:Object.assign(Object.assign({name:"SelectAll",property:"selectAll-visual"},o.commonParamsForJudge),{defaults:!1})}]},3311:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dividerProperties=void 0;const o=r(1513);t.dividerProperties=[{propertySector:o.Sector.FEATURE_ETS,propertySet:Object.assign({name:"Vertical",property:"vertical-visual"},o.commonParamsForJudge)},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"LineCap",property:"line-cap-visual",type:o.TypeName.SELECT,etsType:o.EtsType.LINE_CAP_STYLE,defaults:"butt",list:[o.CLEAN_VALUE_NODE,{name:"Butt",value:"butt"},{name:"Round",value:"round"},{name:"Square",value:"square"}]}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"StrokeWidth",property:"stroke-width-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.COMB_LENGTH,units:o.etsLength}}]},3687:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.flexProperties=void 0;const o=r(1513);t.flexProperties=[{propertySector:o.Sector.FLEXCHILD,propertySet:{name:"FlexBasis",property:"flex-basis-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.COMB_LENGTH,units:o.etsLength,defaults:"auto",fixedValues:["auto"],info:"The initial main size of a flex item. It sets the size of the content box otherwise set with box-sizing.",isLayout:!0}},{propertySector:o.Sector.FLEXCHILD,propertySet:{name:"AlignSelf",property:"align-self-visual",type:o.TypeName.SELECT,etsType:o.EtsType.ITEM_ALIGN,defaults:"auto",list:[o.CLEAN_VALUE_NODE,{name:"Auto",value:"auto"},{name:"Start",value:"flex-start"},{name:"Center",value:"center"},{name:"End",value:"flex-end"},{name:"Stretch",value:"stretch"},{name:"Baseline",value:"baseline"}],info:"The alignment of items on the Cross Axis.",isLayout:!0}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"Direction",property:"flex-direction-visual",type:o.TypeName.SELECT,etsType:o.EtsType.FLEX_DIRECTION,defaults:"row",list:[o.CLEAN_VALUE_NODE,{name:"Row",value:"row"},{name:"RowReverse",value:"row-reverse"},{name:"Column",value:"column"},{name:"ColumnReverse",value:"column-reverse"}],info:"The direction of flex.",isLayout:!0}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"Wrap",property:"wrap-visual",type:o.TypeName.SELECT,etsType:o.EtsType.FLEX_WRAP,defaults:"nowrap",list:[o.CLEAN_VALUE_NODE,{name:"NoWrap",value:"nowrap"},{name:"Wrap",value:"wrap"},{name:"WrapReverse",value:"wrap-reverse"}],info:"Whether flex items are forced onto one line or multiple lines.",isLayout:!0}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"JustifyContent",property:"justify-content-visual",type:o.TypeName.SELECT,etsType:o.EtsType.FLEX_ALIGN,defaults:"flex-start",list:[o.CLEAN_VALUE_NODE,{name:"Start",value:"flex-start"},{name:"Center",value:"center"},{name:"End",value:"flex-end"},{name:"SpaceBetween",value:"space-between"},{name:"SpaceAround",value:"space-around"},{name:"SpaceEvenly",value:"space-evenly"}],info:"Allocate the space between and around the elements along the main axis of the flexible container",isLayout:!0}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"JustifyContent",property:"justify-content-rc-visual",type:o.TypeName.SELECT,etsType:o.EtsType.FLEX_ALIGN,defaults:"flex-start",list:[o.CLEAN_VALUE_NODE,{name:"Start",value:"flex-start"},{name:"Center",value:"center"},{name:"End",value:"flex-end"},{name:"SpaceBetween",value:"space-between"},{name:"SpaceAround",value:"space-around"},{name:"SpaceEvenly",value:"space-evenly"}],info:"Allocate the space between and around the elements along the main axis of the flexible container",isLayout:!0}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"AlignItems",property:"align-items-flex-visual",type:o.TypeName.SELECT,etsType:o.EtsType.ITEM_ALIGN,defaults:"stretch",list:[o.CLEAN_VALUE_NODE,{name:"Auto",value:"auto"},{name:"Start",value:"flex-start"},{name:"Center",value:"center"},{name:"End",value:"flex-end"},{name:"Stretch",value:"stretch"},{name:"Baseline",value:"baseline"}],info:"The alignment of items on the Cross Axis.",isLayout:!0}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"AlignContent",property:"align-content-visual",type:o.TypeName.SELECT,etsType:o.EtsType.FLEX_ALIGN,defaults:"flex-start",list:[o.CLEAN_VALUE_NODE,{name:"Start",value:"flex-start"},{name:"Center",value:"center"},{name:"End",value:"flex-end"},{name:"SpaceBetween",value:"space-between"},{name:"SpaceAround",value:"space-around"},{name:"SpaceEvenly",value:"space-evenly"}],info:"Set the distribution of space between and around content items along a flexbox's cross-axis or a grid's block axis.",isLayout:!0}}]},4836:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gridItemProperties=void 0;const o=r(1513);t.gridItemProperties=[{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"RowStart",property:"row-start-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.NUMBER}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"RowEnd",property:"row-end-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.NUMBER}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"ColumnStart",property:"column-start-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.NUMBER}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"ColumnEnd",property:"column-end-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.NUMBER}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"ForceRebuild",property:"force-rebuild-visual",type:o.TypeName.SELECT,etsType:o.EtsType.BOOLEAN,list:o.booleanListWithClean,defaults:"false"}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"Selectable",property:"selectable-visual",type:o.TypeName.SELECT,etsType:o.EtsType.BOOLEAN,list:o.booleanListWithClean,defaults:"true"}}]},6181:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.gridProperties=void 0;const o=r(1513);t.gridProperties=[{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"ColumnsTemplate",property:"columns-template-visual",type:o.TypeName.BASE,etsType:o.EtsType.STRING}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"RowsTemplate",property:"rows-template-visual",type:o.TypeName.BASE,etsType:o.EtsType.STRING}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"ColumnsGap",property:"columns-gap-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.COMB_R_LENGTH,units:o.etsLength,defaults:0}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"RowsGap",property:"rows-gap-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.COMB_R_LENGTH,units:o.etsLength,defaults:0}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"LayoutDirection",property:"layout-direction-visual",type:o.TypeName.SELECT,etsType:o.EtsType.GRID_DIRECTION,list:[o.CLEAN_VALUE_NODE,{name:"Row",value:"row"},{name:"Column",value:"column"},{name:"RowReverse",value:"row-reverse"},{name:"ColumnReverse",value:"column-reverse"}],defaults:"row"}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"MaxCount",property:"max-count-visual",type:o.TypeName.BASE,etsType:o.EtsType.NUMBER,defaults:1/0}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"MinCount",property:"min-count-visual",type:o.TypeName.BASE,etsType:o.EtsType.NUMBER,defaults:1}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"CellLength",property:"cell-length-visual",type:o.TypeName.BASE,etsType:o.EtsType.NUMBER}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"MultiSelectable",property:"multi-selectable-visual",type:o.TypeName.SELECT,etsType:o.EtsType.BOOLEAN,list:o.booleanListWithClean,defaults:"false"}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"SupportAnimation",property:"support-animation-visual",type:o.TypeName.SELECT,etsType:o.EtsType.BOOLEAN,list:o.booleanListWithClean,defaults:"false"}}]},8840:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.listItemProperties=void 0;const o=r(1513);t.listItemProperties=[{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"Sticky",property:"sticky-visual",type:o.TypeName.SELECT,etsType:o.EtsType.STICKY,list:[o.CLEAN_VALUE_NODE,{name:"None",value:"none"},{name:"Normal",value:"normal"}],defaults:"none"}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"Editable",property:"editable-visual",type:o.TypeName.SELECT,etsType:o.EtsType.BOOLEAN,list:[o.CLEAN_VALUE_NODE,{name:"true",value:"true"},{name:"false",value:"false"}],defaults:"false"}}]},8124:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.listProperties=void 0;const o=r(1513);t.listProperties=[{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"InitialIndex",property:"initial-index-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.NUMBER}},{propertySector:o.Sector.MORE,propertySet:{name:"ListDirection",property:"list-direction-visual",type:o.TypeName.SELECT,etsType:o.EtsType.AXIS,list:[o.CLEAN_VALUE_NODE,{name:"Vertical",value:"vertical"},{name:"Horizontal",value:"horizontal"}],defaults:"vertical"}},{propertySector:o.Sector.MORE,propertySet:{name:"Color",property:"divider-color-visual",type:o.TypeName.COLOR,etsType:o.EtsType.COMB_COLOR}},{propertySector:o.Sector.MORE,propertySet:{name:"StrokeWidth",property:"divider-stroke-width-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.COMB_R_LENGTH,units:o.etsLength}},{propertySector:o.Sector.MORE,propertySet:{name:"StartMargin",property:"divider-start-margin-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.COMB_R_LENGTH,units:o.etsLength}},{propertySector:o.Sector.MORE,propertySet:{name:"EndMargin",property:"divider-end-margin-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.COMB_R_LENGTH,units:o.etsLength}},{propertySector:o.Sector.MORE,propertySet:{name:"EditMode",property:"edit-mode-visual",type:o.TypeName.SELECT,etsType:o.EtsType.BOOLEAN,list:[o.CLEAN_VALUE_NODE,{name:"true",value:"true"},{name:"false",value:"false"}],defaults:"false"}},{propertySector:o.Sector.MORE,propertySet:{name:"EdgeEffect",property:"edge-effect-visual",type:o.TypeName.SELECT,etsType:o.EtsType.EDGE_EFFECT,list:[o.CLEAN_VALUE_NODE,{name:"Spring",value:"spring"},{name:"None",value:"none"}],defaults:"spring"}},{propertySector:o.Sector.MORE,propertySet:{name:"ChainAnimation",property:"chain-animation-visual",type:o.TypeName.SELECT,etsType:o.EtsType.BOOLEAN,list:[o.CLEAN_VALUE_NODE,{name:"true",value:"true"},{name:"false",value:"false"}],defaults:"false"}}]},5452:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.navigationProperties=void 0;const o=r(1513);t.navigationProperties=[{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"Title",property:"navigation-title-visual",type:o.TypeName.BASE,etsType:o.EtsType.STRING,defaults:""}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"SubTitle",property:"subTitle-visual",type:o.TypeName.BASE,etsType:o.EtsType.STRING,defaults:""}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"Menus",property:"menus-visual",type:o.TypeName.BASE,etsType:o.EtsType.ARRAY,supportStaticProperty:!1,defaults:""}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"TitleMode",property:"titleMode-visual",type:o.TypeName.SELECT,etsType:o.EtsType.NAVIGATION_TITLEMODE,list:[o.CLEAN_VALUE_NODE,{value:"Free"},{value:"Mini"},{value:"Full"}],defaults:"Mini"}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"ToolBar",property:"toolBar-visual",type:o.TypeName.BASE,etsType:o.EtsType.OBJECT,supportStaticProperty:!1,defaults:{}}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"HideToolBar",property:"hideToolBar-visual",type:o.TypeName.SELECT,etsType:o.EtsType.BOOLEAN,list:o.booleanListWithClean,defaults:"false"}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"HideTitleBar",property:"hideTitleBar-visual",type:o.TypeName.SELECT,etsType:o.EtsType.BOOLEAN,list:o.booleanListWithClean,defaults:"false"}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"HideBackButton",property:"hideBackButton-visual",type:o.TypeName.SELECT,etsType:o.EtsType.BOOLEAN,list:o.booleanListWithClean,defaults:"false"}}]},4090:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pickerProperties=void 0;const o=r(1513);t.pickerProperties=[{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"Range",property:"range-visual",type:o.TypeName.BASE,etsType:o.EtsType.ARRAY,supportStaticProperty:!1,defaults:""}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"Selected",property:"datetime-selected-visual",type:o.TypeName.BASE,etsType:o.EtsType.DATE}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"Start",property:"start-visual",type:o.TypeName.BASE,etsType:o.EtsType.DATE}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"End",property:"end-visual",type:o.TypeName.BASE,etsType:o.EtsType.DATE}},{propertySector:o.Sector.FEATURE_ETS,propertySet:Object.assign(Object.assign({name:"UseMilitaryTime",property:"useMilitaryTime-visual"},o.commonParamsForJudge),{defaults:!1})},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"Selected",property:"textPicker-selected-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.NUMBER}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"DefaultPickerItemHeight",property:"defaultPickerItemHeight-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.COMB_LENGTH,units:["vp","px","lpx"]}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"Lunar",property:"lunar-visual",type:o.TypeName.SELECT,etsType:o.EtsType.BOOLEAN,list:[{name:"true",value:"true"},{name:"false",value:"false"}]}}]},5302:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.refreshProperties=void 0;const o=r(1513);t.refreshProperties=[{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"Friction",property:"friction-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.COMB_LENGTH,defaults:62}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"Offset",property:"offset-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.COMB_LENGTH,units:o.etsLength,defaults:16}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"Refreshing",property:"refreshing-visual",type:o.TypeName.SELECT,etsType:o.EtsType.BOOLEAN,defaults:"false",list:[{name:"true",value:"true"},{name:"false",value:"false"}]}}]},4488:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.scrollProperties=void 0;const o=r(1513);t.scrollProperties=[{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"Scrollable",property:"scrollable-visual",type:o.TypeName.SELECT,etsType:o.EtsType.SCROLL_DIRECTION,list:[o.CLEAN_VALUE_NODE,{value:"Horizontal"},{value:"Vertical"},{value:"None"}],defaults:"Vertical",startApi:"9"}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"Scrollable",property:"scrollable-visual",type:o.TypeName.SELECT,etsType:o.EtsType.SCROLL_DIRECTION,list:[o.CLEAN_VALUE_NODE,{value:"Horizontal"},{value:"Vertical"},{value:"None"},{value:"Free"}],defaults:"Vertical",endApi:"9"}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"ScrollBar",property:"scroll-bar-visual",type:o.TypeName.SELECT,etsType:o.EtsType.BAR_STATE,list:[o.CLEAN_VALUE_NODE,{value:"Off"},{value:"On"},{value:"Auto"}]}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"ScrollBarColor",property:"scroll-bar-color-visual",type:o.TypeName.COLOR,etsType:o.EtsType.NON_R_COLOR}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"ScrollBarWidth",property:"scroll-bar-width-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.COMB_LENGTH,units:o.etsLength}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"EdgeEffect",property:"edge-effect-scroll-visual",type:o.TypeName.SELECT,etsType:o.EtsType.EDGE_EFFECT,list:[o.CLEAN_VALUE_NODE,{value:"Spring"},{value:"Fade"},{value:"None"}],defaults:"None"}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"Scroller",property:"scroller-visual",type:o.TypeName.BASE,etsType:o.EtsType.SCROLLER,supportStaticProperty:!1}}]},128:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.searchProperties=void 0;const o=r(1513),n=[{propertySector:o.Sector.MORE,propertySet:{name:"PlaceholderFontSize",property:"placeholder-font-size-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.COMB_R_LENGTH,units:o.fontSizeUnit}},{propertySector:o.Sector.MORE,propertySet:{name:"PlaceholderFontStyle",property:"placeholder-font-style-visual",type:o.TypeName.SELECT,etsType:o.EtsType.FONT_STYLE,list:[o.CLEAN_VALUE_NODE,{name:"Normal",value:"normal"},{name:"Italic",value:"italic"}],defaults:"normal"}},{propertySector:o.Sector.MORE,propertySet:{name:"PlaceholderFontWeight",property:"placeholder-font-weight-visual",type:o.TypeName.SELECT,etsType:`${o.EtsType.FONT_WEIGHT}|${o.EtsType.NUMBER}`,list:o.fontWeightList,defaults:"normal"}},{propertySector:o.Sector.MORE,propertySet:{name:"PlaceholderFontFamily",property:"placeholder-font-family-visual",type:o.TypeName.BASE,etsType:o.EtsType.COMB_CONTENT,defaults:""}}],a=[{propertySector:o.Sector.MORE,propertySet:{name:"TextFontSize",property:"text-font-size-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.COMB_R_LENGTH,units:o.fontSizeUnit}},{propertySector:o.Sector.MORE,propertySet:{name:"TextFontStyle",property:"text-font-style-visual",type:o.TypeName.SELECT,etsType:o.EtsType.FONT_STYLE,list:[o.CLEAN_VALUE_NODE,{name:"Normal",value:"normal"},{name:"Italic",value:"italic"}],defaults:"normal"}},{propertySector:o.Sector.MORE,propertySet:{name:"TextFontWeight",property:"text-font-weight-visual",type:o.TypeName.SELECT,etsType:`${o.EtsType.FONT_WEIGHT}|${o.EtsType.NUMBER}`,list:o.fontWeightList,defaults:"normal"}},{propertySector:o.Sector.MORE,propertySet:{name:"TextFontFamily",property:"text-font-family-visual",type:o.TypeName.BASE,etsType:o.EtsType.COMB_CONTENT,defaults:""}},{propertySector:o.Sector.MORE,propertySet:{name:"TextAlign",property:"search-text-align-visual",type:o.TypeName.SELECT,etsType:o.EtsType.TEXT_ALIGN,list:[o.CLEAN_VALUE_NODE,{name:"Start",value:"start"},{name:"Center",value:"center"},{name:"End",value:"end"}],defaults:"start"}}];t.searchProperties=[...n,...a,{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"Controller",property:"search-controller-visual",type:o.TypeName.BASE,etsType:o.EtsType.SEARCH_CONTROLLER,supportStaticProperty:!1,defaults:""}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"Icon",property:"icon-visual",type:o.TypeName.BASE,etsType:o.EtsType.STRING}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"Placeholder",property:"search-placeholder-visual",type:o.TypeName.BASE,etsType:o.EtsType.STRING}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"Value",property:"search-value-visual",type:o.TypeName.BASE,etsType:o.EtsType.STRING}},{propertySector:o.Sector.MORE,propertySet:{name:"SearchButton",property:"search-button-visual",type:o.TypeName.BASE,etsType:o.EtsType.STRING}},{propertySector:o.Sector.MORE,propertySet:{name:"CopyOption",property:"copy-option-visual",type:o.TypeName.SELECT,etsType:o.EtsType.COPY_OPTION,list:[o.CLEAN_VALUE_NODE,{name:"None",value:"None"},{name:"InApp",value:"InApp"},{name:"LocalDevice",value:"LocalDevice"}],defaults:"None",startApi:"9"}}]},1021:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.selectProperties=void 0;const o=r(1513),n=[{propertySector:o.Sector.SELECT,propertySet:{name:"SelectedOptionFontSize",property:"selected-option-font-size-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.COMB_R_LENGTH,units:o.fontSizeUnit}},{propertySector:o.Sector.SELECT,propertySet:{name:"SelectedOptionFontStyle",property:"selected-option-font-style-visual",type:o.TypeName.SELECT,etsType:o.EtsType.FONT_STYLE,list:[o.CLEAN_VALUE_NODE,{name:"Normal",value:"normal"},{name:"Italic",value:"italic"}],defaults:"normal"}},{propertySector:o.Sector.SELECT,propertySet:{name:"SelectedOptionFontColor",property:"selected-option-font-color-visual",type:o.TypeName.COLOR,etsType:o.EtsType.COMB_COLOR}},{propertySector:o.Sector.SELECT,propertySet:{name:"SelectedOptionFontWeight",property:"selected-option-font-weight-visual",type:o.TypeName.SELECT,etsType:`${o.EtsType.FONT_WEIGHT}|${o.EtsType.NUMBER}`,list:o.fontWeightList,defaults:"normal"}},{propertySector:o.Sector.SELECT,propertySet:{name:"SelectedOptionFontFamily",property:"selected-option-font-family-visual",type:o.TypeName.BASE,etsType:o.EtsType.COMB_CONTENT,defaults:""}},{propertySector:o.Sector.SELECT,propertySet:{name:"SelectedOptionBackgroundColor",property:"selected-option-bg-color-visual",type:o.TypeName.COLOR,etsType:o.EtsType.COMB_COLOR}}],a=[{propertySector:o.Sector.OPTION,propertySet:{name:"OptionFontSize",property:"option-font-size-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.COMB_R_LENGTH,units:o.fontSizeUnit}},{propertySector:o.Sector.OPTION,propertySet:{name:"OptionFontStyle",property:"option-font-style-visual",type:o.TypeName.SELECT,etsType:o.EtsType.FONT_STYLE,list:[o.CLEAN_VALUE_NODE,{name:"Normal",value:"normal"},{name:"Italic",value:"italic"}],defaults:"normal"}},{propertySector:o.Sector.OPTION,propertySet:{name:"OptionFontColor",property:"option-font-color-visual",type:o.TypeName.COLOR,etsType:o.EtsType.COMB_COLOR}},{propertySector:o.Sector.OPTION,propertySet:{name:"OptionFontWeight",property:"option-font-weight-visual",type:o.TypeName.SELECT,etsType:`${o.EtsType.FONT_WEIGHT}|${o.EtsType.NUMBER}`,list:o.fontWeightList,defaults:"normal"}},{propertySector:o.Sector.OPTION,propertySet:{name:"OptionFontFamily",property:"option-font-family-visual",type:o.TypeName.BASE,etsType:o.EtsType.COMB_CONTENT,defaults:""}},{propertySector:o.Sector.OPTION,propertySet:{name:"OptionBackgroundColor",property:"option-bg-color-visual",type:o.TypeName.COLOR,etsType:o.EtsType.COMB_COLOR}}];t.selectProperties=[...n,...a,{propertySector:o.Sector.SELECT,propertySet:{name:"Value",property:"select-value-visual",type:o.TypeName.BASE,etsType:o.EtsType.STRING}},{propertySector:o.Sector.SELECT,propertySet:{name:"Selected",property:"selected-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.NUMBER}},{propertySector:o.Sector.SELECT,propertySet:{name:"Options",property:"select-option-visual",type:o.TypeName.BASE,etsType:o.EtsType.ARRAY,supportStaticProperty:!1,defaults:""}}]},8929:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sliderProperties=void 0;const o=r(1513);t.sliderProperties=[{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"TrackColor",property:"track-color-visual",type:o.TypeName.COLOR,defaults:"#ffffff"}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"ShowSteps",property:"show-steps-visual",type:o.TypeName.ADJUSTABLE}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"ShowTips",property:"show-tips-visual",type:o.TypeName.ADJUSTABLE}}]},1815:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stackProperties=void 0;const o=r(1513);t.stackProperties=[{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"AlignContent",property:"align-content-stack-visual",type:o.TypeName.SELECT,etsType:o.EtsType.ALIGNMENT,defaults:"center",list:o.alignProperties}}]},1492:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.swiperProperties=void 0;const o=r(1513);t.swiperProperties=[{propertySector:o.Sector.MORE,propertySet:Object.assign({name:"AutoPlay",property:"auto-play-visual"},o.commonParamsForJudge)},{propertySector:o.Sector.MORE,propertySet:{name:"Interval",property:"interval-visual",type:o.TypeName.BASE,etsType:o.EtsType.NUMBER}},{propertySector:o.Sector.MORE,propertySet:Object.assign(Object.assign({name:"Loop",property:"loop-visual"},o.commonParamsForJudge),{defaults:!0})},{propertySector:o.Sector.MORE,propertySet:{name:"Duration",property:"duration-visual",type:o.TypeName.BASE,etsType:o.EtsType.NUMBER}},{propertySector:o.Sector.MORE,propertySet:{name:"ItemSpace",property:"item-space-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.COMB_LENGTH}},{propertySector:o.Sector.MORE,propertySet:{name:"CachedCount",property:"cached-count-visual",type:o.TypeName.BASE,etsType:o.EtsType.NUMBER}},{propertySector:o.Sector.MORE,propertySet:Object.assign({name:"DisableSwipe",property:"disable-swipe-visual"},o.commonParamsForJudge)},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"Index",property:"index-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.NUMBER}},{propertySector:o.Sector.MORE,propertySet:Object.assign(Object.assign({name:"Indicator",property:"indicator-visual"},o.commonParamsForJudge),{defaults:!0})}]},6153:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tabContentProperties=void 0;const o=r(1513);t.tabContentProperties=[{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"TabBar Icon",property:"tabBar-icon-visual",type:o.TypeName.BASE,etsType:o.EtsType.COMB_SRC}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"TabBar Text",property:"tabBar-text-visual",type:o.TypeName.BASE,etsType:o.EtsType.COMB_CONTENT}}]},6686:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tabsProperties=void 0;const o=r(1513);t.tabsProperties=[{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"Controller",property:"controller-visual",type:o.TypeName.BASE,etsType:o.EtsType.TABS_CONTROLLER,supportStaticProperty:!1,defaults:""}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"Scrollable",property:"tabs-scrollable-visual",type:o.TypeName.SELECT,etsType:o.EtsType.BOOLEAN,list:o.booleanListWithClean,defaults:"true"}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"BarPosition",property:"bar-position-visual",type:o.TypeName.SELECT,etsType:o.EtsType.BAR_POSITION,list:[o.CLEAN_VALUE_NODE,{name:"Start",value:"start"},{name:"End",value:"end"}],defaults:"start"}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"BarMode",property:"bar-mode-visual",type:o.TypeName.SELECT,etsType:o.EtsType.BAR_MODE,list:[o.CLEAN_VALUE_NODE,{name:"Scrollable",value:"scrollable"},{name:"Fixed",value:"fixed"}],defaults:"fixed"}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"BarWidth",property:"bar-width-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.COMB_R_LENGTH,units:o.etsLength}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"BarHeight",property:"bar-height-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.COMB_R_LENGTH,units:o.etsLength}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"AnimationDuration",property:"animation-duration-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.NUMBER,defaults:200}}]},3890:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.textInputProperties=void 0;const o=r(1513);t.textInputProperties=[{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"Placeholder",property:"placeholder-visual",type:o.TypeName.BASE,etsType:o.EtsType.COMB_CONTENT,defaults:""}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"Type",property:"textInput-type-visual",type:o.TypeName.SELECT,etsType:o.EtsType.INPUT_TYPE,list:[o.CLEAN_VALUE_NODE,{value:"Normal"},{value:"Password"},{value:"Email"},{value:"Number"}],defaults:"Normal"}},{propertySector:o.Sector.MORE,propertySet:{name:"PlaceholderColor",property:"placeholderColor-visual",type:o.TypeName.COLOR,etsType:o.EtsType.COMB_COLOR}},{propertySector:o.Sector.MORE,propertySet:{name:"PlaceholderFontSize",property:"placeholderFont-size-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.COMB_R_LENGTH,units:["fp"]}},{propertySector:o.Sector.MORE,propertySet:{name:"PlaceholderFontWeight",property:"placeholderFont-weight-visual",type:o.TypeName.SELECT,etsType:`${o.EtsType.FONT_WEIGHT}|${o.EtsType.NUMBER}`,list:[o.CLEAN_VALUE_NODE,{value:"Normal"},{value:"Lighter"},{value:"Regular"},{value:"Medium"},{value:"Bold"},{value:"Bolder"},...o.commonFontWeight],defaults:"400"}},{propertySector:o.Sector.MORE,propertySet:{name:"PlaceholderFontFamily",property:"placeholderFont-family-visual",type:o.TypeName.BASE,etsType:o.EtsType.COMB_CONTENT,defaults:""}},{propertySector:o.Sector.MORE,propertySet:{name:"PlaceholderFontStyle",property:"placeholderFont-style-visual",type:o.TypeName.SELECT,etsType:o.EtsType.FONT_STYLE,list:[o.CLEAN_VALUE_NODE,{value:"Normal"},{value:"Italic"}],defaults:"Normal"}},{propertySector:o.Sector.MORE,propertySet:{name:"EnterKeyType",property:"enterKeyType-visual",type:o.TypeName.SELECT,etsType:o.EtsType.ENTER_KEY_TYPE,list:[o.CLEAN_VALUE_NODE,{value:"Go"},{value:"Search"},{value:"Send"},{value:"Next"},{value:"Done"}],defaults:"Done"}},{propertySector:o.Sector.MORE,propertySet:{name:"CaretColor",property:"caretColor-visual",type:o.TypeName.COLOR,etsType:o.EtsType.COMB_COLOR}},{propertySector:o.Sector.MORE,propertySet:{name:"MaxLength",property:"maxLength-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.NUMBER}}]},8271:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.textComponentProperties=void 0;const o=r(1513);t.textComponentProperties=[{propertySector:o.Sector.TEXTSTYLES,propertySet:{name:"TextAlign",property:"text-align-visual",type:o.TypeName.SELECT,etsType:o.EtsType.TEXT_ALIGN,list:[o.CLEAN_VALUE_NODE,{name:"Start",value:"start"},{name:"Center",value:"center"},{name:"End",value:"end"}],defaults:"start",isLayout:!0}},{propertySector:o.Sector.TEXTSTYLES,propertySet:{name:"LineHeight",property:"line-height-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.COMB_R_LENGTH,units:["fp","px","lpx"],isLayout:!0}},{propertySector:o.Sector.TEXTSTYLES,propertySet:{name:"TextOverflow",property:"text-overflow-visual",type:o.TypeName.SELECT,etsType:o.EtsType.TEXT_OVERFLOW,list:[o.CLEAN_VALUE_NODE,{name:"Clip",value:"clip"},{name:"Ellipsis",value:"ellipsis"},{name:"None",value:"none"}],defaults:"clip",isLayout:!0}},{propertySector:o.Sector.TEXTSTYLES,propertySet:{name:"BaselineOffset",property:"baseline-offset-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.COMB_LENGTH,units:["fp","px","lpx"],isLayout:!0}},{propertySector:o.Sector.TEXTSTYLES,propertySet:{name:"DecorationType",property:"decoration-type-visual",type:o.TypeName.SELECT,etsType:o.EtsType.TEXT_DECORATION_TYPE,list:[o.CLEAN_VALUE_NODE,{name:"Underline",value:"underline"},{name:"LineThrough",value:"line-through"},{name:"Overline",value:"overline"},{name:"None",value:"none"}],defaults:"none"}},{propertySector:o.Sector.TEXTSTYLES,propertySet:{name:"DecorationColor",property:"decoration-color-visual",type:o.TypeName.COLOR,etsType:o.EtsType.COMB_COLOR}},{propertySector:o.Sector.TEXTSTYLES,propertySet:{name:"TextCase",property:"text-case-visual",type:o.TypeName.SELECT,etsType:o.EtsType.TEXT_CASE,list:[o.CLEAN_VALUE_NODE,{value:"Normal"},{value:"LowerCase"},{value:"UpperCase"}],defaults:"Normal"}}]},3460:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toggleProperties=void 0;const o=r(1513);t.toggleProperties=[{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"Type",property:"toggle-type-visual",type:o.TypeName.SELECT,etsType:o.EtsType.TOGGLE_TYPE,list:[o.CLEAN_VALUE_NODE,{value:"Button"},{value:"Checkbox"},{value:"Switch"}],defaults:"Button",isLayout:!0}},{propertySector:o.Sector.FEATURE_ETS,propertySet:Object.assign(Object.assign({name:"IsOn",property:"isOn-visual"},o.commonParamsForJudge),{defaults:!1})},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"SelectedColor",property:"selectedColor-visual",type:o.TypeName.COLOR,etsType:o.EtsType.COMB_COLOR}},{propertySector:o.Sector.FEATURE_ETS,propertySet:{name:"SwitchPointColor",property:"switchPointColor-visual",type:o.TypeName.COLOR,etsType:o.EtsType.COMB_COLOR}}]},1290:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.etsPropertyList=t.sizeProperties=void 0;const o=r(5958),n=r(1513),a=r(5302),i=r(3460),s=r(8271),p=r(3890),l=r(3311),c=r(8124),u=r(8840),y=r(3687),d=r(1492),f=r(1021),m=r(8929),g=r(4090),h=r(128),E=r(1815),T=r(4836),S=r(6181),P=r(4488),v=r(5452),b=r(6686),_=r(8964),N=r(6153),C=r(6486),O=(()=>{const e=C.cloneDeep(o.commonPropertyList),t=new Map([["color-visual",n.Sector.FEATURE_ETS],["value-visual",n.Sector.FEATURE_ETS],["total-visual",n.Sector.FEATURE_ETS],["style-visual",n.Sector.FEATURE_ETS],["font-family-visual",n.Sector.TEXTSTYLES],["max-lines-visual",n.Sector.TEXTSTYLES],["flex-grow-visual",n.Sector.FLEXCHILD],["flex-shrink-visual",n.Sector.FLEXCHILD],["aspect-ratio-visual",n.Sector.LAYOUT],["opacity-visual",n.Sector.EFFECT],["background-color-visual",n.Sector.BACKGROUND]]);return e.forEach((e=>{const r=e.propertySet.property;t.has(r)&&(e.propertySector=t.get(r))})),e})(),A=[{propertySector:n.Sector.TEXTSTYLES,propertySet:{name:"FontSize",property:"font-size-visual",type:n.TypeName.INTEGER,etsType:n.EtsType.COMB_R_LENGTH,units:n.fontSizeUnit,min:0,isLayout:!0}},{propertySector:n.Sector.TEXTSTYLES,propertySet:{name:"FontStyle",property:"font-style-visual",type:n.TypeName.SELECT,etsType:n.EtsType.FONT_STYLE,list:[n.CLEAN_VALUE_NODE,{name:"Normal",value:"normal"},{name:"Italic",value:"italic"}],defaults:"normal",isLayout:!0}},{propertySector:n.Sector.TEXTSTYLES,propertySet:{name:"FontColor",property:"font-color-visual",type:n.TypeName.COLOR,etsType:n.EtsType.COMB_COLOR}},{propertySector:n.Sector.TEXTSTYLES,propertySet:{name:"FontWeight",property:"font-weight-visual",type:n.TypeName.SELECT,etsType:`${n.EtsType.FONT_WEIGHT}|${n.EtsType.NUMBER}`,list:n.fontWeightList,defaults:"400",isLayout:!0}}],M=[{propertySector:n.Sector.RENDER,propertySet:{name:"ForEach",property:"for-visual",type:n.TypeName.BASE,etsType:n.EtsType.ARRAY,supportStaticProperty:!1,defaults:""}},{propertySector:n.Sector.RENDER,propertySet:{name:"KeyGenerator",property:"keyGenerator-visual",type:n.TypeName.BASE,etsType:"Event",supportStaticProperty:!1,defaults:""}},{propertySector:n.Sector.RENDER,propertySet:{name:"Item",property:"item-visual",type:n.TypeName.BASE,supportDynamicProperty:!1,info:"Variable Name for Item of ForEach Array"}},{propertySector:n.Sector.RENDER,propertySet:{name:"Idx",property:"idx-visual",type:n.TypeName.BASE,supportDynamicProperty:!1,info:"Variable Name for Index of Corresponding Item In ForEach Array"}}],w={type:n.TypeName.INTEGER,etsType:n.EtsType.COMB_R_LENGTH,units:n.etsUnit,placeholder:"0",isLayout:!0};t.sizeProperties=[{propertySector:n.Sector.SIZE,propertySet:{name:"Width",property:"width-visual",type:n.TypeName.INTEGER,etsType:n.EtsType.COMB_R_LENGTH,units:n.etsUnit,min:0,isLayout:!0}},{propertySector:n.Sector.SIZE,propertySet:{name:"Height",property:"height-visual",type:n.TypeName.INTEGER,etsType:n.EtsType.COMB_R_LENGTH,units:n.etsUnit,min:0,isLayout:!0}},{propertySector:n.Sector.SIZE,propertySet:{name:"MinWidth",property:"constraint-size-min-width-visual",type:n.TypeName.INTEGER,etsType:n.EtsType.COMB_R_LENGTH,units:n.etsUnit,min:0,isLayout:!0}},{propertySector:n.Sector.SIZE,propertySet:{name:"MinHeight",property:"constraint-size-min-height-visual",type:n.TypeName.INTEGER,etsType:n.EtsType.COMB_R_LENGTH,units:n.etsUnit,min:0,isLayout:!0}},{propertySector:n.Sector.SIZE,propertySet:{name:"MaxWidth",property:"constraint-size-max-width-visual",type:n.TypeName.INTEGER,etsType:n.EtsType.COMB_R_LENGTH,units:n.etsUnit,min:0,isLayout:!0}},{propertySector:n.Sector.SIZE,propertySet:{name:"MaxHeight",property:"constraint-size-max-height-visual",type:n.TypeName.INTEGER,etsType:n.EtsType.COMB_R_LENGTH,units:n.etsUnit,min:0,isLayout:!0}},{propertySector:n.Sector.SPACING,propertySet:Object.assign({name:"Margin",property:"margin-visual"},w)},{propertySector:n.Sector.SPACING,propertySet:Object.assign({name:"Padding",property:"padding-visual"},w)},{propertySector:n.Sector.SPACING,propertySet:Object.assign({name:"MarginTop",property:"margin-top-visual"},w)},{propertySector:n.Sector.SPACING,propertySet:Object.assign({name:"MarginRight",property:"margin-right-visual"},w)},{propertySector:n.Sector.SPACING,propertySet:Object.assign({name:"MarginBottom",property:"margin-bottom-visual"},w)},{propertySector:n.Sector.SPACING,propertySet:Object.assign({name:"MarginLeft",property:"margin-left-visual"},w)},{propertySector:n.Sector.SPACING,propertySet:Object.assign({name:"PaddingTop",property:"padding-top-visual"},w)},{propertySector:n.Sector.SPACING,propertySet:Object.assign({name:"PaddingRight",property:"padding-right-visual"},w)},{propertySector:n.Sector.SPACING,propertySet:Object.assign({name:"PaddingBottom",property:"padding-bottom-visual"},w)},{propertySector:n.Sector.SPACING,propertySet:Object.assign({name:"PaddingLeft",property:"padding-left-visual"},w)}];const R={type:n.TypeName.INTEGER,etsType:n.EtsType.COMB_R_LENGTH,units:n.etsLength,isLayout:!0},x={type:n.TypeName.INTEGER,etsType:n.EtsType.COMB_R_LENGTH,units:n.etsLength},L={type:n.TypeName.COLOR,etsType:n.EtsType.COMB_COLOR},I=[{propertySector:n.Sector.CUSTOM,propertySet:{name:"CustomString",property:"custom-string-visual",type:n.TypeName.BASE,etsType:n.EtsType.STRING}},{propertySector:n.Sector.CUSTOM,propertySet:{name:"CustomNumber",property:"custom-number-visual",type:n.TypeName.INTEGER,etsType:n.EtsType.NUMBER}},{propertySector:n.Sector.CUSTOM,propertySet:{name:"CustomBoolean",property:"custom-boolean-visual",type:n.TypeName.SELECT,etsType:n.EtsType.BOOLEAN,list:n.booleanListWithClean,defaults:"false"}}],F=[{propertySector:n.Sector.BORDER,propertySet:Object.assign({name:"BorderWidth",property:"border-width-visual"},R)},{propertySector:n.Sector.BORDER,propertySet:Object.assign({name:"BorderStyle",property:"border-style-visual"},n.commonParamsForBorder)},{propertySector:n.Sector.BORDER,propertySet:Object.assign({name:"BorderColor",property:"border-color-visual"},L)},{propertySector:n.Sector.BORDER,propertySet:Object.assign({name:"BorderRadius",property:"border-radius-visual"},x)},{propertySector:n.Sector.BORDER,propertySet:Object.assign({name:"BorderTopWidth",property:"border-top-width-visual"},R),startApi:"9"},{propertySector:n.Sector.BORDER,propertySet:Object.assign({name:"BorderTopStyle",property:"border-top-style-visual"},n.commonParamsForBorder),startApi:"9"},{propertySector:n.Sector.BORDER,propertySet:Object.assign({name:"BorderTopColor",property:"border-top-color-visual"},L),startApi:"9"},{propertySector:n.Sector.BORDER,propertySet:Object.assign(Object.assign({name:"BorderTopLeftRadius",property:"border-top-left-radius-visual"},x),{startApi:"9"})},{propertySector:n.Sector.BORDER,propertySet:Object.assign({name:"BorderRightWidth",property:"border-right-width-visual"},R),startApi:"9"},{propertySector:n.Sector.BORDER,propertySet:Object.assign({name:"BorderRightStyle",property:"border-right-style-visual"},n.commonParamsForBorder),startApi:"9"},{propertySector:n.Sector.BORDER,propertySet:Object.assign({name:"BorderRightColor",property:"border-right-color-visual"},L),startApi:"9"},{propertySector:n.Sector.BORDER,propertySet:Object.assign(Object.assign({name:"BorderTopRightRadius",property:"border-top-right-radius-visual"},x),{startApi:"9"})},{propertySector:n.Sector.BORDER,propertySet:Object.assign({name:"BorderBottomWidth",property:"border-bottom-width-visual"},R),startApi:"9"},{propertySector:n.Sector.BORDER,propertySet:Object.assign({name:"BorderBottomStyle",property:"border-bottom-style-visual"},n.commonParamsForBorder),startApi:"9"},{propertySector:n.Sector.BORDER,propertySet:Object.assign({name:"BorderBottomColor",property:"border-bottom-color-visual"},L),startApi:"9"},{propertySector:n.Sector.BORDER,propertySet:Object.assign(Object.assign({name:"BorderBottomRightRadius",property:"border-bottom-right-radius-visual"},x),{startApi:"9"})},{propertySector:n.Sector.BORDER,propertySet:Object.assign({name:"BorderLeftWidth",property:"border-left-width-visual"},R),startApi:"9"},{propertySector:n.Sector.BORDER,propertySet:Object.assign({name:"BorderLeftStyle",property:"border-left-style-visual"},n.commonParamsForBorder),startApi:"9"},{propertySector:n.Sector.BORDER,propertySet:Object.assign({name:"BorderLeftColor",property:"border-left-color-visual"},L),startApi:"9"},{propertySector:n.Sector.BORDER,propertySet:Object.assign(Object.assign({name:"BorderBottomLeftRadius",property:"border-bottom-left-radius-visual"},x),{startApi:"9"})}],k=[{propertySector:n.Sector.BACKGROUND,propertySet:{name:"BackgroundImageSrc",property:"background-image-src-visual",type:n.TypeName.BASE,etsType:n.EtsType.COMB_SRC}},{propertySector:n.Sector.BACKGROUND,propertySet:{name:"BackgroundImageRepeat",property:"background-image-repeat-visual",type:n.TypeName.SELECT,etsType:n.EtsType.IMAGE_REPERT,list:[n.CLEAN_VALUE_NODE,{name:"X",value:"repeat-x"},{name:"Y",value:"repeat-y"},{name:"XY",value:"repeat"},{name:"NoRepeat",value:"no-repeat"}]}},{propertySector:n.Sector.BACKGROUND,propertySet:{name:"BackgroundImageSize",property:"background-image-size-visual",type:n.TypeName.DATA_SELECT_INPUT,etsType:`${n.EtsType.IMAGE_SIZE}|${n.EtsType.STRING}`,list:[n.CLEAN_VALUE_NODE,{name:"Cover",value:"cover"},{name:"Contain",value:"contain"},{name:"Auto",value:"auto"}],defaults:"Auto"}},{propertySector:n.Sector.BACKGROUND,propertySet:{name:"BackgroundImagePosition",property:"background-image-position-visual",type:n.TypeName.DATA_SELECT_INPUT,etsType:`${n.EtsType.ALIGNMENT}|${n.EtsType.STRING}`,list:[n.CLEAN_VALUE_NODE,{name:"TopStart",value:"top left"},{name:"Top",value:"top center"},{name:"TopEnd",value:"top right"},{name:"Start",value:"center left"},{name:"Center",value:"center center"},{name:"End",value:"center right"},{name:"BottomStart",value:"bottom left"},{name:"Bottom",value:"bottom center"},{name:"BottomEnd",value:"bottom right"}],defaults:"0 0"}}],B=[{propertySector:n.Sector.LAYOUT,propertySet:{name:"Location",property:"position-visual",type:n.TypeName.SELECT,defaults:"offset",supportDynamicProperty:!1,list:[n.CLEAN_VALUE_NODE,{name:"offset",value:"relative"},{name:"position",value:"absolute"}],isLayout:!0}},{propertySector:n.Sector.LAYOUT,propertySet:{name:"X",property:"left-visual",type:n.TypeName.INTEGER,etsType:n.EtsType.COMB_R_LENGTH,defaults:0,units:["vp","px","lpx"],isLayout:!0}},{propertySector:n.Sector.LAYOUT,propertySet:{name:"Y",property:"top-visual",type:n.TypeName.INTEGER,etsType:n.EtsType.COMB_R_LENGTH,defaults:0,units:["vp","px","lpx"],isLayout:!0}}],D=[{propertySector:n.Sector.LAYOUT,propertySet:{name:"DisplayPriority",property:"display-priority-visual",type:n.TypeName.INTEGER,etsType:n.EtsType.NUMBER,isLayout:!0}},{propertySector:n.Sector.EFFECT,propertySet:{name:"Visibility",property:"visibility-visual",type:n.TypeName.SELECT,etsType:n.EtsType.VISIBILITY,defaults:"visible",list:[n.CLEAN_VALUE_NODE,{name:"Visible",value:"visible"},{name:"Hidden",value:"hidden"},{name:"None",value:"none"}],isLayout:!0}},{propertySector:n.Sector.EFFECT,propertySet:{name:"Enabled",property:"enabled-visual",type:n.TypeName.SELECT,etsType:n.EtsType.BOOLEAN,defaults:"true",list:[{value:"true"},{value:"false"}]}},{propertySector:n.Sector.LAYOUT,propertySet:{name:"Align",property:"align-visual",type:n.TypeName.SELECT,etsType:n.EtsType.ALIGNMENT,defaults:"center",list:n.alignProperties}},{propertySector:n.Sector.RENDER,propertySet:{name:"If",property:"if-visual",type:n.TypeName.SELECT,etsType:n.EtsType.BOOLEAN,defaults:"",list:[{name:"true",value:"true"},{name:"false",value:"false"}],isLayout:!0}},{propertySector:n.Sector.FEATURE_ETS,propertySet:{name:"Space",property:"space-visual",type:n.TypeName.INTEGER,etsType:n.EtsType.COMB_LENGTH,units:["vp","px","lpx"],requires:{"display-visual":["flex","cleanValue"]},info:"Space between any two adjacent child components.",isLayout:!0}},{propertySector:n.Sector.FEATURE_ETS,propertySet:{name:"AlignItems",property:"align-items-row-visual",type:n.TypeName.SELECT,etsType:n.EtsType.VERTICAL_ALIGN,defaults:"center",requires:{"display-visual":["flex","cleanValue"]},list:[n.CLEAN_VALUE_NODE,{value:"flex-start",name:"top",etsEnumValue:"Top"},{value:"flex-end",name:"bottom",etsEnumValue:"Bottom"},{value:"center",name:"center",etsEnumValue:"Center"}],info:"Alignment mode of child components in the vertical direction.",isLayout:!0}},{propertySector:n.Sector.FEATURE_ETS,propertySet:{name:"AlignItems",property:"align-items-column-visual",type:n.TypeName.SELECT,etsType:n.EtsType.HORIZONTAL_ALIGN,defaults:"center",requires:{"display-visual":["flex","cleanValue"]},list:[n.CLEAN_VALUE_NODE,{value:"flex-start",name:"start",etsEnumValue:"Start"},{value:"flex-end",name:"end",etsEnumValue:"End"},{value:"center",name:"center",etsEnumValue:"Center"}],info:"Alignment mode of child components in the horizontal direction.",isLayout:!0}},{propertySector:n.Sector.FEATURE_ETS,propertySet:{name:"Src",property:"src-visual",type:n.TypeName.BASE,etsType:n.EtsType.COMB_SRC}},{propertySector:n.Sector.MORE,propertySet:{name:"Alt",property:"alt-visual",type:n.TypeName.BASE,etsType:n.EtsType.COMB_CONTENT}},{propertySector:n.Sector.MORE,propertySet:{name:"RenderMode",property:"render-mode-visual",type:n.TypeName.SELECT,etsType:n.EtsType.IMAGE_RENDER_MODE,defaults:"original",list:[n.CLEAN_VALUE_NODE,{name:"Original",value:"original"},{name:"Template",value:"template"}]}},{propertySector:n.Sector.MORE,propertySet:{name:"ObjectRepeat",property:"object-repeat-visual",type:n.TypeName.SELECT,etsType:n.EtsType.IMAGE_REPERT,defaults:"no-repeat",list:[n.CLEAN_VALUE_NODE,{name:"X",value:"X"},{name:"Y",value:"Y"},{name:"XY",value:"XY"},{name:"NoRepeat",value:"no-repeat"}]}},{propertySector:n.Sector.MORE,propertySet:{name:"ObjectFit",property:"object-fit-visual",type:n.TypeName.SELECT,etsType:n.EtsType.IMAGE_FIT,defaults:"cover",list:[n.CLEAN_VALUE_NODE,{name:"Cover",value:"cover"},{name:"Contain",value:"contain"},{name:"Fill",value:"fill"},{name:"None",value:"none"},{name:"ScaleDown",value:"scale-down"}]}},{propertySector:n.Sector.MORE,propertySet:{name:"InterPolation",property:"interpolation-visual",type:n.TypeName.SELECT,etsType:n.EtsType.IMAGE_INTERPOLATION,defaults:"none",list:[n.CLEAN_VALUE_NODE,{name:"None",value:"none"},{name:"High",value:"high"},{name:"Medium",value:"medium"},{name:"Low",value:"low"}]}},{propertySector:n.Sector.MORE,propertySet:{name:"SourceSizeWidth",property:"source-size-width-visual",type:n.TypeName.INTEGER,etsType:n.EtsType.NUMBER,units:["px"]}},{propertySector:n.Sector.MORE,propertySet:{name:"SourceSizeHeight",property:"source-size-height-visual",type:n.TypeName.INTEGER,etsType:n.EtsType.NUMBER,units:["px"]}},{propertySector:n.Sector.FEATURE_ETS,propertySet:{name:"Type",property:"type-visual",type:n.TypeName.SELECT,etsType:n.EtsType.BUTTON_TYPE,defaults:"capsule",list:[{name:"Normal",value:"normal"},{name:"Capsule",value:"capsule"},{name:"Circle",value:"circle"}]}},{propertySector:n.Sector.FEATURE_ETS,propertySet:{name:"StateEffect",property:"state-effect-visual",type:n.TypeName.SELECT,etsType:n.EtsType.BOOLEAN,defaults:"true",list:n.booleanList}},{propertySector:n.Sector.FEATURE_ETS,propertySet:{name:"Content",property:"content-visual",type:n.TypeName.ADJUSTABLE,etsType:n.EtsType.COMB_CONTENT,isLayout:!0,full:1}},{propertySector:n.Sector.FEATURE_ETS,propertySet:{name:"Label",property:"label-visual",type:n.TypeName.ADJUSTABLE,etsType:n.EtsType.COMB_CONTENT,full:1}}];t.etsPropertyList=[...I,...F,...t.sizeProperties,...A,...M,...i.toggleProperties,..._.checkboxProperties,..._.checkboxGroupProperties,...s.textComponentProperties,...p.textInputProperties,...l.dividerProperties,...B,...c.listProperties,...u.listItemProperties,...y.flexProperties,...d.swiperProperties,...a.refreshProperties,...f.selectProperties,...m.sliderProperties,...O,...k,...g.pickerProperties,...h.searchProperties,...P.scrollProperties,...v.navigationProperties,...b.tabsProperties,...N.tabContentProperties,...D,...E.stackProperties,...T.gridItemProperties,...S.gridProperties]},5958:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.commonPropertyList=void 0;const o=r(1513);t.commonPropertyList=[{propertySector:o.Sector.GENERAL,propertySet:{name:"BackgroundColor",property:"background-color-visual",type:o.TypeName.COLOR,etsType:o.EtsType.COMB_COLOR}},{propertySector:o.Sector.GENERAL,propertySet:{name:"Display",property:"display-visual",type:o.TypeName.SELECT,defaults:"flex",list:[o.CLEAN_VALUE_NODE,{value:"flex"},{value:"none"}]}},{propertySector:o.Sector.GENERAL,propertySet:{name:"Opacity",property:"opacity-visual",type:o.TypeName.SLIDER,etsType:o.EtsType.COMB_R_NUMBER,defaults:"1",step:.01,max:1,min:0,full:1}},{propertySector:o.Sector.GENERAL,propertySet:{name:"Overflow",property:"overflow-visual",type:o.TypeName.SELECT,defaults:"visible",list:[o.CLEAN_VALUE_NODE,{value:"visible"},{value:"hidden"},{value:"scroll"}]}},{propertySector:o.Sector.FLEX,propertySet:{name:"FlexGrow",property:"flex-grow-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.NUMBER,defaults:"0",requiresParent:{display:["flex","cleanValue"]},info:"The flex grow factor of a flex item's main size",isLayout:!0}},{propertySector:o.Sector.FLEX,propertySet:{name:"FlexShrink",property:"flex-shrink-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.NUMBER,defaults:"1",requiresParent:{display:["flex","cleanValue"]},info:"The flex shrink factor of a flex item. If the size of all flex items is larger than the flex container, items will shrink",isLayout:!0}},{propertySector:o.Sector.FLEX,propertySet:{name:"Columns",property:"columns-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.NUMBER,defaults:1,info:"The column number of flex."}},{propertySector:o.Sector.GENERAL,propertySet:{name:"Header Logo",property:"headerLogo-visual",type:o.TypeName.BASE,defaults:""}},{propertySector:o.Sector.GENERAL,propertySet:{name:"Title",property:"title-visual",type:o.TypeName.BASE,defaults:""}},{propertySector:o.Sector.GENERAL,propertySet:{name:"Status",property:"status-visual",type:o.TypeName.BASE,defaults:""}},{propertySector:o.Sector.GENERAL,propertySet:{name:"Logo",property:"logo-visual",type:o.TypeName.BASE,defaults:""}},{propertySector:o.Sector.FEATURE,propertySet:{name:"Color",property:"color-visual",type:o.TypeName.COLOR,etsType:o.EtsType.COMB_COLOR}},{propertySector:o.Sector.FEATURE,propertySet:{name:"FontFamily",property:"font-family-visual",type:o.TypeName.BASE,etsType:o.EtsType.COMB_CONTENT,defaults:"sans-serif",isLayout:!0}},{propertySector:o.Sector.FEATURE,propertySet:{name:"MaxLines",property:"max-lines-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.NUMBER,isLayout:!0}},{propertySector:o.Sector.FEATURE,propertySet:{name:"TextColor",property:"text-color-visual",type:o.TypeName.COLOR,defaults:"rgba(0,0,0,0.9)"}},{propertySector:o.Sector.FEATURE,propertySet:{name:"FocusColor",property:"focus-color-visual",type:o.TypeName.COLOR}},{propertySector:o.Sector.FEATURE,propertySet:{name:"DisappearColor",property:"disappear-color-visual",type:o.TypeName.COLOR}},{propertySector:o.Sector.FEATURE,propertySet:{name:"IndicatorColor",property:"indicator-color-visual",type:o.TypeName.COLOR}},{propertySector:o.Sector.FEATURE,propertySet:{name:"IndicatorSelectedColor",property:"indicator-selected-color-visual",type:o.TypeName.COLOR,defaults:"#ff007dff"}},{propertySector:o.Sector.FEATURE,propertySet:{name:"IndicatorSize",property:"indicator-size-visual",type:o.TypeName.INTEGER,units:["px"]}},{propertySector:o.Sector.FEATURE,propertySet:Object.assign({name:"IndicatorTop",property:"indicator-top-visual"},o.commonParamsForIndicator)},{propertySector:o.Sector.FEATURE,propertySet:Object.assign({name:"IndicatorRight",property:"indicator-right-visual"},o.commonParamsForIndicator)},{propertySector:o.Sector.FEATURE,propertySet:Object.assign({name:"IndicatorBottom",property:"indicator-bottom-visual"},o.commonParamsForIndicator)},{propertySector:o.Sector.FEATURE,propertySet:Object.assign({name:"IndicatorLeft",property:"indicator-left-visual"},o.commonParamsForIndicator)},{propertySector:o.Sector.FEATURE,propertySet:{name:"AllowScale",property:"allow-scale-visual",type:o.TypeName.SELECT,defaults:"true",list:[o.CLEAN_VALUE_NODE,{value:"true"},{value:"false"}]}},{propertySector:o.Sector.GRID,propertySet:{name:"GridRowStart",property:"grid-row-start-visual",type:o.TypeName.INTEGER,requiresParent:{display:["grid"]},info:"The start position of its row in the grid area."}},{propertySector:o.Sector.GRID,propertySet:{name:"GridColumnStart",property:"grid-column-start-visual",type:o.TypeName.INTEGER,requiresParent:{display:["grid"]},info:"The start position of its column in the grid area."}},{propertySector:o.Sector.GRID,propertySet:{name:"GridRowEnd",property:"grid-row-end-visual",type:o.TypeName.INTEGER,requiresParent:{display:["grid"]},info:"The end position of its row in the grid area."}},{propertySector:o.Sector.GRID,propertySet:{name:"GridColumnEnd",property:"grid-column-end-visual",type:o.TypeName.INTEGER,requiresParent:{display:["grid"]},info:"The end position of its column in the grid area."}},{propertySector:o.Sector.GRID,propertySet:{name:"GridTemplateRows",property:"grid-template-rows-visual",type:o.TypeName.BASE,defaults:"1fr",requires:{"display-visual":["grid"]},info:"The number of items in the grid rows."}},{propertySector:o.Sector.GRID,propertySet:{name:"GridTemplateColumns",property:"grid-template-columns-visual",type:o.TypeName.BASE,defaults:"1fr",requires:{"display-visual":["grid"]},info:"The number of items in the grid columns."}},{propertySector:o.Sector.GRID,propertySet:{name:"GridRowsGap",property:"grid-rows-gap-visual",type:o.TypeName.INTEGER,defaults:"0px",units:["px"],requires:{"display-visual":["grid"]},info:"The size of the gap between an element's grid rows."}},{propertySector:o.Sector.GRID,propertySet:{name:"GridColumnsGap",property:"grid-columns-gap-visual",type:o.TypeName.INTEGER,defaults:"0px",units:["px"],requires:{"display-visual":["grid"]},info:"The size of the gap between an element's columns."}},{propertySector:o.Sector.GRID,propertySet:{name:"GridGap",property:"grid-gap-visual",type:o.TypeName.INTEGER,units:["px"],requires:{"display-visual":["grid"]},info:"The gaps between rows and columns. It is a shorthand for row-gap and column-gap."}},{propertySector:o.Sector.FEATURE,propertySet:Object.assign({name:"MatchTextDirection",property:"match-text-direction-visual"},o.commonParamsForJudge)},{propertySector:o.Sector.FEATURE,propertySet:Object.assign({name:"FitOriginalSize",property:"fit-original-size-visual"},o.commonParamsForJudge)},{propertySector:o.Sector.FEATURE,propertySet:{name:"IconWidth",property:"icon-width-visual",type:o.TypeName.INTEGER,units:["px"]}},{propertySector:o.Sector.FEATURE,propertySet:{name:"IconHeight",property:"icon-height-visual",type:o.TypeName.INTEGER,units:["px"]}},{propertySector:o.Sector.FEATURE,propertySet:{name:"TextonColor",property:"texton-color-visual",type:o.TypeName.COLOR,defaults:"#000000"}},{propertySector:o.Sector.FEATURE,propertySet:{name:"TextoffColor",property:"textoff-color-visual",type:o.TypeName.COLOR,defaults:"#000000"}},{propertySector:o.Sector.FEATURE,propertySet:{name:"TextPadding",property:"text-padding-visual",type:o.TypeName.INTEGER,defaults:0,units:["px"]}},{propertySector:o.Sector.FEATURE,propertySet:{name:"SelectedColor",property:"selected-color-visual",type:o.TypeName.COLOR,defaults:"rgba(0,125,255,1)"}},{propertySector:o.Sector.FEATURE,propertySet:{name:"BlockColor",property:"block-color-visual",type:o.TypeName.COLOR,defaults:"#ffffff"}},{propertySector:o.Sector.FEATURE,propertySet:{name:"Radius",property:"radius-visual",type:o.TypeName.INTEGER,units:["px"]}},{propertySector:o.Sector.FEATURE,propertySet:{name:"StartAngle",property:"start-angle-visual",type:o.TypeName.INTEGER,defaults:240}},{propertySector:o.Sector.FEATURE,propertySet:{name:"TotalAngle",property:"total-angle-visual",type:o.TypeName.INTEGER,defaults:240}},{propertySector:o.Sector.FEATURE,propertySet:{name:"CenterX",property:"center-x-visual",type:o.TypeName.INTEGER}},{propertySector:o.Sector.FEATURE,propertySet:{name:"CenterY",property:"center-y-visual",type:o.TypeName.INTEGER}},{propertySector:o.Sector.FEATURE,propertySet:{name:"Colors",property:"colors-visual",type:o.TypeName.BASE}},{propertySector:o.Sector.FEATURE,propertySet:{name:"Weights",property:"weights-visual",type:o.TypeName.BASE}},{propertySector:o.Sector.FEATURE,propertySet:{name:"PlaceHolderColor",property:"placeholder-color-visual",type:o.TypeName.COLOR,defaults:"gray"}},{propertySector:o.Sector.FEATURE,propertySet:{name:"ProgressColor",property:"progress-color-visual",type:o.TypeName.COLOR,etsType:o.EtsType.COMB_COLOR,defaults:"black"}},{propertySector:o.Sector.FEATURE,propertySet:{name:"ItemExtent",property:"item-extent-visual",type:o.TypeName.INTEGER,units:["px","%"]}},{propertySector:o.Sector.FEATURE,propertySet:{name:"FadeColor",property:"fade-color-visual",type:o.TypeName.COLOR,defaults:"grey"}},{propertySector:o.Sector.FLEX,propertySet:{name:"ColumnSpan",property:"column-span-visual",type:o.TypeName.INTEGER,defaults:1,min:1,info:"The number of span."}},{propertySector:o.Sector.ATOMIC,propertySet:{name:"FlexWeight",property:"flex-weight-visual",type:o.TypeName.INTEGER}},{propertySector:o.Sector.ATOMIC,propertySet:{name:"AspectRatio",property:"aspect-ratio-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.NUMBER,isLayout:!0}},{propertySector:o.Sector.FEATURE,propertySet:{name:"SecondaryColor",property:"secondary-color-visual",type:o.TypeName.COLOR,requires:{type:["horizontal","ring","scale-ring"]}}},{propertySector:o.Sector.FEATURE,propertySet:{name:"ScaleWidth",property:"scale-width-visual",type:o.TypeName.INTEGER,requires:{type:["ring","scale-ring"]}}},{propertySector:o.Sector.FEATURE,propertySet:{name:"ScaleNumber",property:"scale-number-visual",type:o.TypeName.INTEGER,defaults:120,requires:{type:["ring","scale-ring"]}}},{propertySector:o.Sector.FEATURE,propertySet:{name:"Value",property:"value-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.NUMBER,defaults:0}},{propertySector:o.Sector.FEATURE,propertySet:{name:"Total",property:"total-visual",type:o.TypeName.INTEGER,etsType:o.EtsType.NUMBER,defaults:100}},{propertySector:o.Sector.FEATURE,propertySet:{name:"Style",property:"style-visual",type:o.TypeName.SELECT,etsType:o.EtsType.PROGRESS_STYLE,defaults:"Linear",list:[{value:"Linear"}]}}]},1513:(e,t)=>{"use strict";var r,o,n,a,i,s,p;Object.defineProperty(t,"__esModule",{value:!0}),t.alignProperties=t.booleanListWithClean=t.booleanList=t.fontWeightList=t.fontSizeUnit=t.etsUnit=t.etsLength=t.commonFontWeight=t.commonParamsForBorderRadius=t.commonParamsForIndicator=t.commonParamsForInteger=t.commonParamsForJudge=t.commonParamsForBorder=t.CLEAN_VALUE_NODE=t.EtsSpecialType=t.EtsCombinationType=t.EtsBasicType=t.EtsEnumType=t.EtsType=t.TypeName=t.Sector=void 0,function(e){e.GENERAL="general",e.DIMENSION="dimension",e.FEATURE="feature",e.FEATURE_ETS="feature_ets",e.SIZE="size",e.SPACING="spacing",e.BORDER="border",e.BACKGROUND="background",e.LAYOUT="layout",e.RENDER="render",e.FLEX="flex",e.FLEXCHILD="flexchild",e.GRID="grid",e.ATOMIC="atomic",e.CUSTOM="custom",e.TEXT="text",e.TEXTSTYLES="textstyles",e.SELECT="select",e.OPTION="option",e.EFFECT="effect",e.MORE="more",e.PAGEDATA="pagedata"}(r||(r={})),t.Sector=r,function(e){e.BASE="base",e.INTEGER="integer",e.SELECT="select",e.COLOR="color",e.COMPOSITE="composite",e.SLIDER="slider",e.DATA_SELECT_INPUT="dataSelectInput",e.ADJUSTABLE="adjustable"}(o||(o={})),t.TypeName=o,function(e){e.ARRAY="ETSArray",e.BOOLEAN="boolean",e.DATE="Date",e.NUMBER="number",e.OBJECT="object",e.STRING="string"}(n||(n={})),t.EtsBasicType=n,function(e){e.R_FLOAT="Rfloat",e.R_STRING="Rstring",e.R_COLOR="Rcolor",e.R_PLURAL="Rplural",e.R_MEDIA="Rmedia",e.R_RAWFILE="Rrawfile"}(a||(a={})),function(e){e.ALIGNMENT="Alignment",e.AXIS="Axis",e.BORDER_STYLE="BorderStyle",e.BUTTON_TYPE="ButtonType",e.COLOR="Color",e.DIRECTION="Direction",e.EDGE_EFFECT="EdgeEffect",e.ENTER_KEY_TYPE="EnterKeyType",e.NAVIGATION_TITLEMODE="NavigationTitleMode",e.FLEX_ALIGN="FlexAlign",e.FLEX_DIRECTION="FlexDirection",e.FLEX_WRAP="FlexWrap",e.FONT_STYLE="FontStyle",e.FONT_WEIGHT="FontWeight",e.HORIZONTAL_ALIGN="HorizontalAlign",e.IMAGE_FIT="ImageFit",e.IMAGE_INTERPOLATION="ImageInterpolation",e.IMAGE_RENDER_MODE="ImageRenderMode",e.IMAGE_REPERT="ImageRepeat",e.IMAGE_SIZE="ImageSize",e.INPUT_TYPE="InputType",e.ITEM_ALIGN="ItemAlign",e.LINE_CAP_STYLE="LineCapStyle",e.PROGRESS_STYLE="ProgressStyle",e.STICKY="Sticky",e.TEXT_ALIGN="TextAlign",e.TEXT_OVERFLOW="TextOverflow",e.TEXT_DECORATION_TYPE="TextDecorationType",e.TEXT_CASE="TextCase",e.TOGGLE_TYPE="ToggleType",e.VERTICAL_ALIGN="VerticalAlign",e.VISIBILITY="Visibility",e.COPY_OPTION="CopyOption",e.BAR_STATE="BarState",e.GRID_DIRECTION="GridDirection",e.SCROLL_DIRECTION="ScrollDirection",e.BAR_POSITION="BarPosition",e.BAR_MODE="BarMode"}(i||(i={})),t.EtsEnumType=i,function(e){e.COMB_COLOR="string|number|Color|Rcolor",e.COMB_LENGTH="string|number",e.COMB_R_NUMBER="number|Rfloat",e.COMB_R_LENGTH="string|number|Rfloat",e.COMB_CONTENT="string|Rstring|Rplural",e.COMB_SRC="string|Rmedia|Rrawfile",e.NON_R_COLOR="string|number|Color"}(s||(s={})),t.EtsCombinationType=s,function(e){e.SCROLLER="Scroller",e.TABS_CONTROLLER="TabsController",e.SEARCH_CONTROLLER="SearchController"}(p||(p={})),t.EtsSpecialType=p;const l=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},n),a),i),s),p);t.EtsType=l;const c={value:"cleanValue",name:"---Clean Value---"};t.CLEAN_VALUE_NODE=c;const u={type:o.SELECT,etsType:l.BORDER_STYLE,list:[c,{value:"dotted",etsEnumValue:"Dotted"},{value:"dashed",etsEnumValue:"Dashed"},{value:"solid",etsEnumValue:"Solid"}]};t.commonParamsForBorder=u;const y={type:o.SELECT,etsType:l.BOOLEAN,defaults:"false",list:[c,{value:"true"},{value:"false"}]};t.commonParamsForJudge=y;const d={type:o.INTEGER,units:["px"],placeholder:"0px"};t.commonParamsForInteger=d;const f={type:o.INTEGER,units:["px","%"]};t.commonParamsForIndicator=f;const m={type:o.INTEGER,units:["px"]};t.commonParamsForBorderRadius=m;const g=[{value:"100"},{value:"200"},{value:"300"},{value:"400"},{value:"500"},{value:"600"},{value:"700"},{value:"800"},{value:"900"}];t.commonFontWeight=g,t.etsLength=["vp","px","lpx"],t.etsUnit=["vp","px","%","lpx"],t.fontSizeUnit=["fp","px","lpx"];const h=[c,{name:"Normal",value:"normal"},{name:"Lighter",value:"lighter"},{name:"Regular",value:"regular"},{name:"Medium",value:"medium"},{name:"Bold",value:"bold"},{name:"Bolder",value:"bolder"},...g];t.fontWeightList=h;const E=[{name:"true",value:"true"},{name:"false",value:"false"}];t.booleanList=E;const T=[c,...E];t.booleanListWithClean=T;const S=[c,{name:"TopStart",value:"top-start"},{name:"Top",value:"top"},{name:"TopEnd",value:"top-end"},{name:"Start",value:"start"},{name:"Center",value:"center"},{name:"End",value:"end"},{name:"BottomStart",value:"bottom-start"},{name:"Bottom",value:"bottom"},{name:"BottomEnd",value:"bottom-end"}];t.alignProperties=S},9282:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TagTypeMap=void 0,t.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"],["select","Container"],["tabs","Container"],["tab-bar","Container"],["tab-content","Container"],["scroll","Container"],["navigation","Container"]])},4294:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.beforeCodegen=t.getCustomCompRelativePath=t.getRelativePath=t.getNpmPath=t.prepareCustomCompTagName=t.capitalize=t.getTagName=t.strToBase64=t.getUniqueName=t.getUniqueId=t.removeFromArray=t.getDataName=void 0;const o=r(2891);function n(e){let t=a(e).replace(/[/=+]/g,"");const r=t.length;return r>=4&&(t=t.substring(r/2-2,r/2+2)),t}function a(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");let r="";for(let t=0;t{const t=r.indexOf(e);-1!==t&&r.splice(t,1)})),r},t.getUniqueId=n,t.getUniqueName=function(e){return`${e}_${n(e)}`},t.strToBase64=a;const i=new Map,s=new Map;function p(e){return e[0].toUpperCase()+e.slice(1)}function l(e){const t=(0,o.getInstance)().document.path;if(0===e.size)return;const r=p(t.substring(t.lastIndexOf("/")+1));e.forEach(((e,o)=>{var n;const a=e.length,l=[...e];o===r&&l.push(t);const y=function(e){e.sort();const t=e[0],r=e[e.length-1];let o=0;for(let e=0;e1||o===r)&&(d=p(e[l].substring(y+1).split("/").join("_")),d=d.replace("src_main_supervisual_",""),d=d.replace(/-/g,"_")),s.set(e[l],d);let f=u(e[l],t);f=null!==(n=c(e[l]))&&void 0!==n?n:f,i.set(d,f)}}))}function c(e){let t=e;const r=t.match(/\/(?:\/node|oh)_modules\/(.+\/)?(?=[\w-]+\/src\/main\/)/);if(null===r)return;const o=r[0],n=r[1],a=void 0!==n&&""!==n?"@"+n:"";return t=t.replace("src/main/supervisual","src/main/ets"),t.replace(o,a)}function u(e,t){const r=e.split("/"),o=t.split("/");let n=0;for(let e=0;e1){const o=p(r[r.length-1]),n=t.get(o);void 0===n?t.set(o,[e.type]):n.push(e.type)}const o=e.children;for(let e=0;e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FormAction=t.FormModel=void 0,t.FormModel=class{constructor(){this.data=new Map,this.actions=new Map}},t.FormAction=class{constructor(e,t,r,o){this.action=e,this.abilityName=o,this.want=r,this.params=t}}},1509:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deserializeForVersion1=t.rootToVisualContent=t.visualToRootContent=t.serializeForVersion1=void 0;const o=r(2891),n=r(1933),a=r(7571),i=r(9282),s=r(5945),p=r(7977),l=r(6486),c=new Map;function u(e){c.set("textMap",new Map);const t=y(null!=e?e:(0,o.getInstance)().visualModel),r={VisualVersion:"1",content:JSON.stringify(t),extraData:JSON.stringify(m(c))};return null==e&&(r.contentV12=JSON.stringify((0,o.getInstance)(),p.replacer,4)),JSON.stringify(r)}function y(e){const t=(0,l.cloneDeep)(e);"huaweiLogin"!==t.type&&"huaweiPay"!==t.type||(t.type="button");const r=Array.from(t.property).filter((e=>(0,a.isAttribute)(e[0],t.type)));r.push(["id",t.id]);const o=Array.from(t.property).filter((e=>(0,a.isStyle)(e[0],t.type)));let n=i.TagTypeMap.get(t.type);void 0===n&&(n="Base");let s=t.property.has("content")?t.property.get("content"):[];if(t.children.length>0){if("string"==typeof s){const e=c.get("textMap");e instanceof Map&&e.set(t.id,s)}s=t.children.map((e=>y(e)))}return{id:t.id,tagName:t.type,attributes:r,idStyle:o,type:n,content:s}}function d(e,t){let r;if(t instanceof Map){const o=t.get("textMap");o instanceof Map&&(r=o.get(e.id))}const o=new n.VisualModel({id:e.id,type:e.tagName,property:new Map([...e.attributes,...e.idStyle])});return"string"==typeof r&&o.property.set("content",r),o.property.delete("id"),"string"==typeof e.content&&o.property.set("content",e.content),Array.isArray(e.content)&&(o.children=e.content.map((e=>d(e,t)))),o}function f(e){if(e instanceof Array&&e.length>0&&"$$map"===e[0]){e.shift();const t=new Map;for(const[r,o]of e)t.set(r,f(o));return t}return e}function m(e){if(e instanceof Map){const t=["$$map"];for(const[r,o]of e)t.push([r,m(o)]);return t}return e}t.serializeForVersion1=u,t.visualToRootContent=function(e){try{return u(JSON.parse(e,p.reviver).visualModel)}catch(e){console.error("convert visual model to root model failed")}return e},t.rootToVisualContent=function(e){const t=JSON.parse(e),r=JSON.parse(t.content);let o='["$$map",["textMap",["$$map"]]]';"string"==typeof t.extraData&&(o=JSON.parse(t.extraData));const n=d(r,f(o));return n.property.has("flex-direction")||n.property.set("flex-direction","column"),JSON.stringify({document:{VisualVersion:"12",type:"FA"},visualModel:n,formData:new s.FormModel},p.replacer)},t.deserializeForVersion1=function(e){try{const t=JSON.parse(e);if(null!==t.contentV12&&void 0!==t.contentV12)return void(0,o.setInstance)(JSON.parse(t.contentV12,p.reviver));const r=JSON.parse(t.content);let n='["$$map",["textMap",["$$map"]]]';"string"==typeof t.extraData&&(n=JSON.parse(t.extraData)),(0,o.getInstance)().visualModel=d(r,f(n)),(0,o.getInstance)().visualModel.property.has("flex-direction")||(0,o.getInstance)().visualModel.property.set("flex-direction","column")}catch(e){console.error("convert error")}}},2891:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setInstance=t.getInstance=t.setVisualPath=t.clearCustomInstance=t.setCustomInstance=t.getInstanceTemplate=t.getCustomInstance=void 0;const o=r(1933),n=r(5945),a=r(904),i={document:{VisualVersion:"12",type:"FA",custom:!1,path:""},visualModel:new o.VisualModel({type:"div",id:"wrapper"}),formData:new n.FormModel,imgData:void 0,customData:void 0,cloudQuery:void 0},s=new Map;t.getCustomInstance=function(){return s},t.getInstanceTemplate=function(e){return{document:{VisualVersion:"12",type:"ETS",custom:e,path:"&path"},visualModel:new o.VisualModel({type:"column",id:"wrapper"}),imgData:""}},t.setCustomInstance=function(e,t){var r;const n={path:"",document:{VisualVersion:"",type:"",custom:!0},visualModel:new o.VisualModel({type:"",id:""}),methods:[],property:[],imgData:"",originType:[],isEditable:!0,originPath:""};n.path=e.path,n.isEditable=e.isEditable,n.originPath=e.originPath;for(const e in n)Object.prototype.hasOwnProperty.call(t,e)&&(n[e]=t[e]);n.visualModel=null!==(r=n.visualModel.children[0])&&void 0!==r?r:new o.VisualModel({type:"text"}),s.set(e.path,n)},t.clearCustomInstance=function(){s.clear()},t.setVisualPath=function(e){i.document.path=e},t.getInstance=function(){return i},t.setInstance=function(e){var t,r,o,n;for(const t in i)Object.prototype.hasOwnProperty.call(e,t)&&(i[t]=e[t]);const s=i.document.type;void 0===i.document.custom&&(i.document.custom=!1),null!==((null!==(r=(null===(t=e.customData)||void 0===t?void 0:t.property.size)>0)&&void 0!==r?r:null)||(null!==(n=(null===(o=e.customData)||void 0===o?void 0:o.event.size)>0)&&void 0!==n?n:null))&&(i.customData=e.customData),(0,a.setDomain)("ETS"===s?a.Domain.ETS:"FORM"===s?a.Domain.FORM:a.Domain.FA)}},7977:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isInstanceEqual=t.reviver=t.replacer=t.serializeSketchPage=t.serializeCustom=t.deserializeCustom=t.deserialize=t.serialize=void 0;const o=r(1933),n=r(2891),a=r(1509);function i(e,t){if(t instanceof Map)return{dataType:"Map",value:Object.fromEntries(t.entries())};if(t instanceof Set)return{dataType:"Set",value:Array.from(t.entries())};if(t instanceof o.VisualModel){const e=new o.VisualModel({type:"none"}),r={};for(const o in e)Object.prototype.hasOwnProperty.call(t,o)&&(r[o]=t[o]);return{dataType:"VisualModel",value:r}}return t}function s(e,t){if("object"==typeof t&&null!=t){if("Map"===t.dataType)return new Map(Object.entries(t.value));if("Set"===t.dataType)return new Set(t.value);if("VisualModel"===t.dataType){const e=new o.VisualModel({type:""});Object.assign(e,t.value),t=e}}return t}t.serialize=function(e,t){return 1===e?(0,a.serializeForVersion1)(t):JSON.stringify(null!=t?t:(0,n.getInstance)(),i,4)},t.deserialize=function(e){if("1"===JSON.parse(e).VisualVersion)return(0,a.deserializeForVersion1)(e);const t=JSON.parse(e,s);(0,n.setInstance)(t)},t.deserializeCustom=function(e,t){const r=JSON.parse(t,s);(0,n.setCustomInstance)(e,r)},t.serializeCustom=function(e){const t=(0,n.getInstanceTemplate)(!0);return t.visualModel.property=new Map([["width","100%"],["height","100%"]]),t.visualModel.children.push(e),JSON.stringify(t,i,4)},t.serializeSketchPage=function(e){const t=(0,n.getInstanceTemplate)(!1);return t.visualModel=e,JSON.stringify(t,i,4)},t.replacer=i,t.reviver=s,t.isInstanceEqual=function(e,t){return JSON.stringify(e,i)===JSON.stringify(t,i)}},1933:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.VisualModel=void 0;const r="-visual";t.VisualModel=class{constructor(e){if(this.propertyStorage=void 0,this.dynamicPropertyStorage=void 0,this.mediaProperty=void 0,this.dynamicMediaProperty=void 0,this.mediaPropertyStorage=void 0,this.dynamicMediaPropertyStorage=void 0,this.slots=void 0,this.property=void 0!==e.property?e.property:new Map,this.dynamicProperty=void 0!==e.dynamicProperty?e.dynamicProperty:new Map,this.children=void 0!==e.children?e.children:[],"wrapper"===e.type)return this.id="wrapper",void(this.type="div");e.type.endsWith(r)&&(e.type=e.type.substring(0,e.type.length-r.length)),this.id=void 0!==e.id?e.id:"",this.type=e.type,this.slots=e.slots}getProperty(e){const t=this.dynamicProperty.get(e);return void 0!==t&&""!==t?t:this.property.get(e)}hasMediaProperty(e){if(void 0!==this.mediaProperty)for(const[,t]of this.mediaProperty)if(null==t?void 0:t.has(e))return!0;if(void 0!==this.dynamicMediaProperty)for(const[,t]of this.dynamicMediaProperty)if(null==t?void 0:t.has(e))return!0;return!1}hasProperty(e){return this.dynamicProperty.has(e)||this.property.has(e)}getChildren(){var e;const t=[...this.children];for(const[,r]of null!==(e=this.slots)&&void 0!==e?e:new Map)t.push(r);return t}accept(e){return e.visit(this)}}}},t={};function r(o){var n=t[o];if(void 0!==n)return n.exports;var a=t[o]={id:o,loaded:!1,exports:{}};return e[o].call(a.exports,a,a.exports,r),a.loaded=!0,a.exports}r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.nmd=e=>(e.paths=[],e.children||(e.children=[]),e);var o={};(()=>{"use strict";var e=o;Object.defineProperty(e,"__esModule",{value:!0});const t=r(3784),n=r(2891),a=r(8413),i=r(4435),s=r(6486),p=r(4294),l=r(6483),c={build:"",etsImport:"",etsVariable:"",etsFunction:"",aboutToAppear:""};e.genETS=function(e){var r;const o={ets:(0,s.cloneDeep)(c),errorType:"",errorMessage:""};if((0,l.parseSourceCode)(e,o),""!==o.errorType)return o.ets=(0,s.cloneDeep)(c),o;try{let e=(0,n.getInstance)().visualModel;if((0,n.getInstance)().document.custom&&(e=e.children[0],void 0===e))return o;(0,p.beforeCodegen)(e);const t=function(e){const t=new a.ETSBridge,r=e.accept(t),o=(new i.StringWriter).genETS(r);return t.getErrorCount()>0?"error":o}(e);"error"===t&&(o.errorType="codegenError"),o.ets=t}catch(e){o.errorType="modelError"}return""!==o.errorType&&(o.errorMessage=null!==(r=t.errorMap.get(o.errorType))&&void 0!==r?r:"Codegen visual file failed",o.ets=(0,s.cloneDeep)(c)),o}})();var n=exports;for(var a in o)n[a]=o[a];o.__esModule&&Object.defineProperty(n,"__esModule",{value:!0})})(); \ No newline at end of file diff --git a/compiler/compile_plugin.js b/compiler/compile_plugin.js new file mode 100644 index 0000000000000000000000000000000000000000..4775a74d83e6a6659e5380e57126d2362a1a01a4 --- /dev/null +++ b/compiler/compile_plugin.js @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2023 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. + */ + +const { initConfig } = require('./lib/fast_build/common/init_config'); +const { getCleanConfig } = require('./main'); +const { etsTransform } = require('./lib/fast_build/ets_ui/rollup-plugin-ets-typescript'); +const { etsChecker } = require('./lib/fast_build/ets_ui/rollup-plugin-ets-checker'); +const { apiTransform } = require('./lib/fast_build/system_api/rollup-plugin-system-api'); +const { genAbc } = require('./lib/fast_build/ark_compiler/rollup-plugin-gen-abc'); +const { watchChangeFiles } = require('./lib/fast_build/common/rollup-plugin-watch-change'); + +exports.etsTransform = etsTransform; +exports.apiTransform = apiTransform; +exports.etsChecker = etsChecker; +exports.genAbc = genAbc; +exports.watchChangeFiles = watchChangeFiles; +exports.initConfig = initConfig; +exports.getCleanConfig = getCleanConfig; diff --git a/compiler/components/flow_item.json b/compiler/components/flow_item.json new file mode 100644 index 0000000000000000000000000000000000000000..5ea44377de8651e914f52b45a3b876f9519ade39 --- /dev/null +++ b/compiler/components/flow_item.json @@ -0,0 +1,8 @@ +{ + "name": "FlowItem", + "parents": [ + "WaterFlow" + ], + "single": true, + "attrs": [] +} \ No newline at end of file diff --git a/compiler/components/grid_row.json b/compiler/components/grid_row.json index d66192d4f4551a5ab126d9fdb21d6a32bef4ac40..cfee5e644f71b5e0fe238e8b6b61fa04edce1f98 100644 --- a/compiler/components/grid_row.json +++ b/compiler/components/grid_row.json @@ -2,6 +2,7 @@ "name": "GridRow", "children": ["GridCol"], "attrs": [ - "onBreakpointChange" + "onBreakpointChange", + "alignItems" ] } \ No newline at end of file diff --git a/compiler/components/menu.json b/compiler/components/menu.json index 2db5287ec32a1546fe7c122fc08d37bf56e89168..749e8c0177ecb25da61446a75c735e160ed8fc6d 100644 --- a/compiler/components/menu.json +++ b/compiler/components/menu.json @@ -1,5 +1,5 @@ { "name": "Menu", - "children": ["Option"], + "children": ["Option", "MenuItem", "MenuItemGroup"], "attrs": ["show", "showPosition", "fontColor", "fontSize", "fontWeight", "fontFamily"] } \ No newline at end of file diff --git a/compiler/components/menu_item.json b/compiler/components/menu_item.json new file mode 100644 index 0000000000000000000000000000000000000000..b949f26e018e250f51352a2f41a84b7dd39b48b8 --- /dev/null +++ b/compiler/components/menu_item.json @@ -0,0 +1,5 @@ +{ + "name": "MenuItem", + "parent": ["Menu", "MenuItemGroup"], + "attrs": ["selectIcon", "onChange"] + } \ No newline at end of file diff --git a/compiler/components/menu_item_group.json b/compiler/components/menu_item_group.json new file mode 100644 index 0000000000000000000000000000000000000000..110332ad114e2a0e4ae9ce9b918c5c34da321796 --- /dev/null +++ b/compiler/components/menu_item_group.json @@ -0,0 +1,4 @@ +{ + "name": "MenuItemGroup", + "children": ["MenuItem"] + } \ No newline at end of file diff --git a/compiler/components/nav_destination.json b/compiler/components/nav_destination.json new file mode 100644 index 0000000000000000000000000000000000000000..85fe4f2f1364f307cfffe636e109090ceae93e47 --- /dev/null +++ b/compiler/components/nav_destination.json @@ -0,0 +1,4 @@ +{ + "name": "NavDestination", + "attrs": ["title", "hideTitleBar"] +} \ No newline at end of file diff --git a/compiler/components/nav_router.json b/compiler/components/nav_router.json new file mode 100644 index 0000000000000000000000000000000000000000..9b9caeea1e4ce969d3de4a6dfb196a21d5e820e9 --- /dev/null +++ b/compiler/components/nav_router.json @@ -0,0 +1,4 @@ +{ + "name": "NavRouter", + "attrs": ["onStateChange"] +} \ No newline at end of file diff --git a/compiler/components/navigation.json b/compiler/components/navigation.json index 0caa487bab2b048e9d9b9a5eb7be6bc1982fcf23..62c60a2340f1d664f5ce9c3cbcc04ca1183d407b 100644 --- a/compiler/components/navigation.json +++ b/compiler/components/navigation.json @@ -1,5 +1,6 @@ { "name": "Navigation", "attrs": ["title", "subTitle", "hideTitleBar", "hideBackButton", "titleMode", "menus", "menuCount", - "toolBar", "hideToolBar", "onTitleModeChange"] + "toolBar", "hideToolBar", "onTitleModeChange", "onNavBarStateChange", "navBarWidth", "navBarPosition", + "mode", "backButtonIcon", "hideNavBar"] } \ No newline at end of file diff --git a/compiler/components/water_flow.json b/compiler/components/water_flow.json new file mode 100644 index 0000000000000000000000000000000000000000..5c41e697ade50d28de265541ccd52e280e2a03f7 --- /dev/null +++ b/compiler/components/water_flow.json @@ -0,0 +1,16 @@ +{ + "name": "WaterFlow", + "children": [ + "FlowItem" + ], + "attrs": [ + "onReachEnd", + "onReachStart", + "itemConstraintSize", + "rowsTemplate", + "columnsTemplate", + "columnsGap", + "rowsGap", + "layoutDirection" + ] +} \ No newline at end of file diff --git a/compiler/components/web.json b/compiler/components/web.json index 4b8810ca33e43f44419f4dc74b38312162be5b16..ae728ba0b9a66a1033435018ed8580c17dd575f3 100644 --- a/compiler/components/web.json +++ b/compiler/components/web.json @@ -7,9 +7,10 @@ "onPageEnd", "onPageBegin", "onProgressChange", "onTitleReceive", "onGeolocationHide", "onGeolocationShow", "onRequestSelected", "javaScriptAccess", "fileAccess", "onAlert", "onBeforeUnload", "onlineImageAccess", "domStorageAccess", "imageAccess", "mixedMode", "zoomAccess", "geolocationAccess", "javaScriptProxy", - "userAgent", "onConfirm", "onConsole", "onErrorReceive", "onHttpErrorReceive", "onDownloadStart", "fileFromUrlAccess", + "onFullScreenExit", "onFullScreenEnter", + "userAgent", "onConfirm", "onConsole", "onErrorReceive", "onHttpErrorReceive", "onDownloadStart", "webDebuggingAccess", "onShowFileSelector", "initialScale", "onResourceLoad", "onScaleChange", "onHttpAuthRequest", "onPermissionRequest", "onContextMenuShow", "textZoomRatio", "onScroll", "mediaPlayGestureAccess", "onSslErrorEventReceive", - "onClientAuthenticationRequest" + "onClientAuthenticationRequest", "horizontalScrollBarAccess", "verticalScrollBarAccess" ] } diff --git a/compiler/form_components/badge.json b/compiler/form_components/badge.json new file mode 100755 index 0000000000000000000000000000000000000000..b4b3bc6b2d64b84a04bc5d64557690a42d3f82d4 --- /dev/null +++ b/compiler/form_components/badge.json @@ -0,0 +1,5 @@ +{ + "name": "Badge", + "atomics": true, + "attrs": [] +} \ No newline at end of file diff --git a/compiler/form_components/blank.json b/compiler/form_components/blank.json new file mode 100755 index 0000000000000000000000000000000000000000..9fe088f444585a56b0753c8c44ce76a81b7ebfb9 --- /dev/null +++ b/compiler/form_components/blank.json @@ -0,0 +1,6 @@ +{ + "name": "Blank", + "parents": ["Row", "Column"], + "atomic": true, + "attrs": ["color"] +} \ No newline at end of file diff --git a/compiler/form_components/button.json b/compiler/form_components/button.json new file mode 100755 index 0000000000000000000000000000000000000000..545d255a5b16c366ed13c261d3b11c6f8d8e3e58 --- /dev/null +++ b/compiler/form_components/button.json @@ -0,0 +1,5 @@ +{ + "name": "Button", + "single": true, + "attrs": ["type", "stateEffect", "fontColor", "fontSize", "fontWeight", "fontStyle", "fontFamily"] +} \ No newline at end of file diff --git a/compiler/form_components/canvas.json b/compiler/form_components/canvas.json new file mode 100755 index 0000000000000000000000000000000000000000..f0a8ba6e67ac73cdf6bf8c0b9b8119820a6edb98 --- /dev/null +++ b/compiler/form_components/canvas.json @@ -0,0 +1,6 @@ +{ + "name": "Canvas", + "attrs": [ + "onReady" + ] +} diff --git a/compiler/form_components/checkbox.json b/compiler/form_components/checkbox.json new file mode 100755 index 0000000000000000000000000000000000000000..533586753a84e2e4aa0844ab4d9cd917e7b8f201 --- /dev/null +++ b/compiler/form_components/checkbox.json @@ -0,0 +1,4 @@ +{ + "name": "Checkbox", + "attrs": ["select","selectedColor","onChange"] +} \ No newline at end of file diff --git a/compiler/form_components/checkboxgroup.json b/compiler/form_components/checkboxgroup.json new file mode 100755 index 0000000000000000000000000000000000000000..66e43853d7619a62cec4fd59df99c917622f8a9a --- /dev/null +++ b/compiler/form_components/checkboxgroup.json @@ -0,0 +1,4 @@ +{ + "name": "CheckboxGroup", + "attrs": ["selectAll","selectedColor","onChange"] +} \ No newline at end of file diff --git a/compiler/form_components/circle.json b/compiler/form_components/circle.json new file mode 100755 index 0000000000000000000000000000000000000000..85a8ffe8103d62e81b39ba47a915d66ae4d207cb --- /dev/null +++ b/compiler/form_components/circle.json @@ -0,0 +1,4 @@ +{ + "name": "Circle", + "atomic": true +} \ No newline at end of file diff --git a/compiler/form_components/column.json b/compiler/form_components/column.json new file mode 100755 index 0000000000000000000000000000000000000000..a80092fbfd89df1350c69f0c2e427ad0a1ed5e80 --- /dev/null +++ b/compiler/form_components/column.json @@ -0,0 +1,4 @@ +{ + "name": "Column", + "attrs": ["alignItems", "justifyContent"] +} diff --git a/compiler/form_components/common_attrs.json b/compiler/form_components/common_attrs.json new file mode 100755 index 0000000000000000000000000000000000000000..6aec23604c727df012e29638408fa6acf1816405 --- /dev/null +++ b/compiler/form_components/common_attrs.json @@ -0,0 +1,12 @@ +{ + "attrs": [ + "width", "height", "responseRegion", "size", "constraintSize", "layoutWeight", "padding", "margin", + "backgroundColor", "backgroundImage", "backgroundImageSize", "backgroundImagePosition", "backgroundBlurStyle", + "opacity", "border", "borderStyle", "borderWidth", "borderColor", "borderRadius", "borderImage", + "onClick", "animation", "transition", "blur", "brightness", "contrast", "grayscale", "colorBlend", + "saturate", "sepia", "invert", "hueRotate", "backdropBlur", "translate", "scale", "rotate", "onAppear", + "onDisAppear", "visibility", "flexGrow", "flexShrink", "flexBasis", "alignSelf", "displayPriority", + "zIndex", "direction", "align", "position", "markAnchor", "offset", "enabled", "alignRules", "aspectRatio", + "overlay", "linearGradient", "sweepGradient", "radialGradient", "shadow", "clip", "mask", "id", "stateStyles" + ] +} diff --git a/compiler/form_components/counter.json b/compiler/form_components/counter.json new file mode 100755 index 0000000000000000000000000000000000000000..d3e7350c6c56cba05967e001bb886ccafb2baf65 --- /dev/null +++ b/compiler/form_components/counter.json @@ -0,0 +1,6 @@ +{ + "name": "Counter", + "attrs": [ + "onInc", "onDec" + ] +} \ No newline at end of file diff --git a/compiler/form_components/datapanel.json b/compiler/form_components/datapanel.json new file mode 100755 index 0000000000000000000000000000000000000000..3128924d62d40428cb66ee82379bbc215f2c274e --- /dev/null +++ b/compiler/form_components/datapanel.json @@ -0,0 +1,5 @@ +{ + "name": "DataPanel", + "atomic": false, + "attrs": ["closeEffect"] +} \ No newline at end of file diff --git a/compiler/form_components/divider.json b/compiler/form_components/divider.json new file mode 100755 index 0000000000000000000000000000000000000000..75728fd5c2b94639c25a30b958c73e65155b5200 --- /dev/null +++ b/compiler/form_components/divider.json @@ -0,0 +1,5 @@ +{ + "name": "Divider", + "atomic": true, + "attrs": ["color", "vertical", "strokeWidth", "lineCap"] +} \ No newline at end of file diff --git a/compiler/form_components/ellipse.json b/compiler/form_components/ellipse.json new file mode 100755 index 0000000000000000000000000000000000000000..0f4a225bcdf388626c32fa2dd200e8b69996990a --- /dev/null +++ b/compiler/form_components/ellipse.json @@ -0,0 +1,4 @@ +{ + "name": "Ellipse", + "atomic": true +} \ No newline at end of file diff --git a/compiler/form_components/flex.json b/compiler/form_components/flex.json new file mode 100755 index 0000000000000000000000000000000000000000..32cee03f48dcd3b07fc6888c95470897f9b48d9d --- /dev/null +++ b/compiler/form_components/flex.json @@ -0,0 +1,4 @@ +{ + "name": "Flex", + "attrs": [] +} \ No newline at end of file diff --git a/compiler/form_components/gauge.json b/compiler/form_components/gauge.json new file mode 100755 index 0000000000000000000000000000000000000000..8ba00bdc2ef05c5784a90c05d21dad57c0474496 --- /dev/null +++ b/compiler/form_components/gauge.json @@ -0,0 +1,7 @@ +{ + "name": "Gauge", + "atomic": true, + "attrs": [ + "value", "startAngle", "endAngle", "colors", "strokeWidth" + ] +} \ No newline at end of file diff --git a/compiler/form_components/grid_col.json b/compiler/form_components/grid_col.json new file mode 100755 index 0000000000000000000000000000000000000000..feb1fd3f9e7fe4a8e7b0779ab892e3ce4f5f9975 --- /dev/null +++ b/compiler/form_components/grid_col.json @@ -0,0 +1,8 @@ +{ + "name": "GridCol", + "parents": ["GridRow"], + "single": true, + "attrs": [ + "span", "offset", "order" + ] +} \ No newline at end of file diff --git a/compiler/form_components/grid_row.json b/compiler/form_components/grid_row.json new file mode 100755 index 0000000000000000000000000000000000000000..d66192d4f4551a5ab126d9fdb21d6a32bef4ac40 --- /dev/null +++ b/compiler/form_components/grid_row.json @@ -0,0 +1,7 @@ +{ + "name": "GridRow", + "children": ["GridCol"], + "attrs": [ + "onBreakpointChange" + ] +} \ No newline at end of file diff --git a/compiler/form_components/image.json b/compiler/form_components/image.json new file mode 100755 index 0000000000000000000000000000000000000000..60ee17d49af4f28cb224ad35039dafde07ae7eb5 --- /dev/null +++ b/compiler/form_components/image.json @@ -0,0 +1,9 @@ +{ + "name": "Image", + "atomic": true, + "attrs": [ + "alt", "matchTextDirection", "fitOriginalSize", "fillColor", "objectFit", "objectRepeat", + "autoResize", "renderMode", "interpolation", "sourceSize", "onComplete", "onError", "onFinish", + "syncLoad", "colorFilter", "copyOption", "draggable" + ] +} \ No newline at end of file diff --git a/compiler/form_components/line.json b/compiler/form_components/line.json new file mode 100755 index 0000000000000000000000000000000000000000..bb5340aeca8f0e129138861f1daa9dd3663ede67 --- /dev/null +++ b/compiler/form_components/line.json @@ -0,0 +1,7 @@ +{ + "name": "Line", + "atomic": true, + "attrs": [ + "startPoint","endPoint" + ] +} \ No newline at end of file diff --git a/compiler/form_components/list.json b/compiler/form_components/list.json new file mode 100755 index 0000000000000000000000000000000000000000..67fe0952c4850130e2aec32f315542ebcd91174d --- /dev/null +++ b/compiler/form_components/list.json @@ -0,0 +1,9 @@ +{ + "name": "List", + "children": ["ListItem"], + "attrs": [ + "lanes", "alignListItem", "listDirection", "scrollBar", "edgeEffect", "divider", "multiSelectable", + "cachedCount", "chainAnimation", "sticky", "onScroll", "onScrollIndex", "onReachStart", "onReachEnd", + "onScrollStop", "onScrollFrameBegin" + ] +} \ No newline at end of file diff --git a/compiler/form_components/listItem.json b/compiler/form_components/listItem.json new file mode 100755 index 0000000000000000000000000000000000000000..f85f49b2b9b4fd0af40244f698df207a54aa10f9 --- /dev/null +++ b/compiler/form_components/listItem.json @@ -0,0 +1,6 @@ +{ + "name": "ListItem", + "parents": ["List"], + "single": true, + "attrs": ["selectable", "onSelect"] +} diff --git a/compiler/form_components/loadingProgress.json b/compiler/form_components/loadingProgress.json new file mode 100755 index 0000000000000000000000000000000000000000..08d1a29aae1162213bb146648b10e3db93f90734 --- /dev/null +++ b/compiler/form_components/loadingProgress.json @@ -0,0 +1,5 @@ +{ + "name": "LoadingProgress", + "atomic": true, + "attrs": ["color"] +} \ No newline at end of file diff --git a/compiler/form_components/marquee.json b/compiler/form_components/marquee.json new file mode 100755 index 0000000000000000000000000000000000000000..b29b9651edcaebd50c466aa82bbf59d7d45e7b24 --- /dev/null +++ b/compiler/form_components/marquee.json @@ -0,0 +1,7 @@ +{ + "name": "Marquee", + "attrs": [ + "fontColor", "fontSize", "allowScale", "fontWeight", "fontFamily", "onStart", + "onBounce", "onFinish" + ] +} \ No newline at end of file diff --git a/compiler/form_components/path.json b/compiler/form_components/path.json new file mode 100755 index 0000000000000000000000000000000000000000..7e3efd76b66434c830a612ca2228dd1324be8f2a --- /dev/null +++ b/compiler/form_components/path.json @@ -0,0 +1,7 @@ +{ + "name": "Path", + "atomic": true, + "attrs": [ + "commands" + ] +} \ No newline at end of file diff --git a/compiler/form_components/polygon.json b/compiler/form_components/polygon.json new file mode 100755 index 0000000000000000000000000000000000000000..bc0b1033b30c51dca975d42b7cc4fe80ccb0d9be --- /dev/null +++ b/compiler/form_components/polygon.json @@ -0,0 +1,5 @@ +{ + "name": "Polygon", + "atomic": true, + "attrs": ["points"] +} \ No newline at end of file diff --git a/compiler/form_components/polyline.json b/compiler/form_components/polyline.json new file mode 100755 index 0000000000000000000000000000000000000000..5f5862ba767a0bfe6c9edcbe51eeb4f0f1499d54 --- /dev/null +++ b/compiler/form_components/polyline.json @@ -0,0 +1,5 @@ +{ + "name": "Polyline", + "atomic": true, + "attrs": ["points"] +} \ No newline at end of file diff --git a/compiler/form_components/progress.json b/compiler/form_components/progress.json new file mode 100755 index 0000000000000000000000000000000000000000..e8c01fc458221a6004dd0caee17c1f493cb28f44 --- /dev/null +++ b/compiler/form_components/progress.json @@ -0,0 +1,7 @@ +{ + "name": "Progress", + "atomic": true, + "attrs": [ + "value", "color", "style" + ] +} \ No newline at end of file diff --git a/compiler/form_components/qrcode.json b/compiler/form_components/qrcode.json new file mode 100755 index 0000000000000000000000000000000000000000..eda56a4b739275e9b01d909b918682be0c90ec06 --- /dev/null +++ b/compiler/form_components/qrcode.json @@ -0,0 +1,4 @@ +{ + "name": "QRCode", + "attrs": ["color", "backgroundColor"] +} \ No newline at end of file diff --git a/compiler/form_components/radio.json b/compiler/form_components/radio.json new file mode 100755 index 0000000000000000000000000000000000000000..ae90392d7e30aaa1d571e94ebc5802677224fbbe --- /dev/null +++ b/compiler/form_components/radio.json @@ -0,0 +1,5 @@ +{ + "name": "Radio", + "atomic": true, + "attrs": ["checked", "onChange"] +} \ No newline at end of file diff --git a/compiler/form_components/rating.json b/compiler/form_components/rating.json new file mode 100755 index 0000000000000000000000000000000000000000..ec43a7a37987ca2cc47eef8da378b514b5c12ab0 --- /dev/null +++ b/compiler/form_components/rating.json @@ -0,0 +1,4 @@ +{ + "name": "Rating", + "attrs": ["stars", "stepSize", "starStyle", "onChange"] +} \ No newline at end of file diff --git a/compiler/form_components/rect.json b/compiler/form_components/rect.json new file mode 100755 index 0000000000000000000000000000000000000000..fce921d52d640848b48cd8b6aa36b7da57ab777e --- /dev/null +++ b/compiler/form_components/rect.json @@ -0,0 +1,7 @@ +{ + "name": "Rect", + "atomic": true, + "attrs": [ + "radiusWidth", "radiusHeight", "radius" + ] +} \ No newline at end of file diff --git a/compiler/form_components/relative_container.json b/compiler/form_components/relative_container.json new file mode 100755 index 0000000000000000000000000000000000000000..db24994b79859b2e6cc9434cabdeefd03bef77a7 --- /dev/null +++ b/compiler/form_components/relative_container.json @@ -0,0 +1,4 @@ +{ + "name": "RelativeContainer", + "attrs": [] +} \ No newline at end of file diff --git a/compiler/form_components/row.json b/compiler/form_components/row.json new file mode 100755 index 0000000000000000000000000000000000000000..3e2642143cb08129a96b48ed65614920353aa13e --- /dev/null +++ b/compiler/form_components/row.json @@ -0,0 +1,4 @@ +{ + "name": "Row", + "attrs": ["alignItems", "justifyContent"] +} diff --git a/compiler/form_components/shape.json b/compiler/form_components/shape.json new file mode 100755 index 0000000000000000000000000000000000000000..8038e5fd43d10e104112e29f1732c07656f416e3 --- /dev/null +++ b/compiler/form_components/shape.json @@ -0,0 +1,12 @@ +{ + "name": "Shape", + "children": [ + "Rect", "Path", "Circle", "Ellipse", "Shape", "Polyline", "Polygon", "Image", "Text", "Column", + "Row" + ], + "attrs": [ + "viewPort", "stroke", "fill", "strokeDashOffset", "strokeDashArray", "strokeLineCap", + "strokeLineJoin", "strokeMiterLimit", "strokeOpacity", "fillOpacity", "strokeWidth", + "antiAlias", "mesh" + ] +} diff --git a/compiler/form_components/slider.json b/compiler/form_components/slider.json new file mode 100755 index 0000000000000000000000000000000000000000..d2bf8af286fe6e68391c00a4712e9ccae197e810 --- /dev/null +++ b/compiler/form_components/slider.json @@ -0,0 +1,8 @@ +{ + "name": "Slider", + "atomic": true, + "attrs": [ + "blockColor", "trackColor", "selectedColor", "showSteps", "showTips", "trackThickness", + "onChange" + ] +} diff --git a/compiler/form_components/span.json b/compiler/form_components/span.json new file mode 100755 index 0000000000000000000000000000000000000000..d8467e61b34bee0b840773b3032dca9a6c2778aa --- /dev/null +++ b/compiler/form_components/span.json @@ -0,0 +1,8 @@ +{ + "name": "Span", + "atomic": true, + "attrs": [ + "fontColor", "fontSize", "fontStyle", "fontFamily", "fontWeight", "decoration", "letterSpacing", + "textCase" + ] +} \ No newline at end of file diff --git a/compiler/form_components/stack.json b/compiler/form_components/stack.json new file mode 100755 index 0000000000000000000000000000000000000000..7007a9f8cb487052c73022aaaaf57e13ad257b3c --- /dev/null +++ b/compiler/form_components/stack.json @@ -0,0 +1,4 @@ +{ + "name": "Stack", + "attrs": ["alignContent"] +} \ No newline at end of file diff --git a/compiler/form_components/text.json b/compiler/form_components/text.json new file mode 100755 index 0000000000000000000000000000000000000000..845819c6a7ee884d80154d28022b9a65784e844b --- /dev/null +++ b/compiler/form_components/text.json @@ -0,0 +1,9 @@ +{ + "name": "Text", + "children": ["Span"], + "attrs": [ + "fontColor", "fontSize", "minFontSize", "maxFontSize", "fontStyle", "fontWeight", + "fontFamily", "textAlign", "lineHeight", "textOverflow", "maxLines", "decoration", + "letterSpacing", "textCase", "baselineOffset", "copyOption" + ] +} \ No newline at end of file diff --git a/compiler/form_components/toggle.json b/compiler/form_components/toggle.json new file mode 100755 index 0000000000000000000000000000000000000000..fbee0bfff6168bb120e8f6fcfcc9dd2d0e6c9017 --- /dev/null +++ b/compiler/form_components/toggle.json @@ -0,0 +1,4 @@ +{ + "name": "Toggle", + "attrs": ["onChange", "selectedColor", "switchPointColor"] +} \ No newline at end of file diff --git a/compiler/main.js b/compiler/main.js index 0e33922632ee3a6f2449ddaa9f71be1ef11b0336..12179701e71c430d697954325a4d6b83d279f59b 100644 --- a/compiler/main.js +++ b/compiler/main.js @@ -17,8 +17,20 @@ const fs = require('fs'); const path = require('path'); const md5 = require('md5'); -const { readFile } = require('./lib/utils'); -const { WORKERS_DIR } = require('./lib/pre_define'); +const { + readFile, + writeFileSync +} = require('./lib/utils'); + +const { + WORKERS_DIR, + TS2ABC, + FAIL +} = require('./lib/pre_define'); + +const { + checkAotConfig +} = require('./lib/gen_aot'); const { configure, @@ -49,10 +61,12 @@ const abilityPagesFullPath = []; function initProjectConfig(projectConfig) { projectConfig.entryObj = {}; + projectConfig.cardObj = {}; projectConfig.projectPath = projectConfig.projectPath || process.env.aceModuleRoot || path.join(process.cwd(), 'sample'); projectConfig.buildPath = projectConfig.buildPath || process.env.aceModuleBuild || path.resolve(projectConfig.projectPath, 'build'); + projectConfig.aceModuleBuild = projectConfig.buildPath; // To be compatible with both webpack and rollup projectConfig.manifestFilePath = projectConfig.manifestFilePath || process.env.aceManifestPath || path.join(projectConfig.projectPath, 'manifest.json'); projectConfig.aceProfilePath = projectConfig.aceProfilePath || process.env.aceProfilePath; @@ -65,20 +79,27 @@ function initProjectConfig(projectConfig) { projectConfig.cachePath = projectConfig.cachePath || process.env.cachePath || path.resolve(__dirname, 'node_modules/.cache'); projectConfig.aceSoPath = projectConfig.aceSoPath || process.env.aceSoPath; - projectConfig.outChangedFileList = getChangedFileList(projectConfig); projectConfig.xtsMode = /ets_loader_ark$/.test(__dirname); - projectConfig.localPropertiesPath = projectConfig.localPropertiesPath || process.env.localPropertiesPath - projectConfig.projectProfilePath = projectConfig.projectProfilePath || process.env.projectProfilePath -} - -function getChangedFileList(projectConfig) { - return (projectConfig.hotReloadWatch && projectConfig.hotReloadWatch.outChangedFileList) ? - projectConfig.hotReloadWatch.outChangedFileList : path.join(projectConfig.cachePath, 'changedFileList.json'); + projectConfig.localPropertiesPath = projectConfig.localPropertiesPath || process.env.localPropertiesPath; + projectConfig.projectProfilePath = projectConfig.projectProfilePath || process.env.projectProfilePath; + projectConfig.isPreview = projectConfig.isPreview || process.env.isPreview === 'true'; + projectConfig.compileMode = projectConfig.compileMode || 'jsbundle'; + projectConfig.runtimeOS = projectConfig.runtimeOS || process.env.runtimeOS || 'default'; + projectConfig.sdkInfo = projectConfig.sdkInfo || process.env.sdkInfo || 'default'; + projectConfig.compileHar = false; + projectConfig.compileShared = false; + projectConfig.splitCommon = false; + projectConfig.checkEntry = projectConfig.checkEntry || process.env.checkEntry; + projectConfig.obfuscateHarType = projectConfig.obfuscateHarType || process.env.obfuscate; + projectConfig.packageDir = 'node_modules'; + projectConfig.packageJson = 'package.json'; + projectConfig.cardEntryObj = {}; } function loadEntryObj(projectConfig) { let manifest = {}; initProjectConfig(projectConfig); + loadBuildJson(); if (process.env.aceManifestPath && aceCompileMode === 'page') { setEntryFile(projectConfig); setFaTestRunnerFile(projectConfig); @@ -88,7 +109,7 @@ function loadEntryObj(projectConfig) { setStageTestRunnerFile(projectConfig); } - if(staticPreviewPage) { + if (staticPreviewPage) { projectConfig.entryObj['./' + staticPreviewPage] = projectConfig.projectPath + path.sep + staticPreviewPage + '.ets?entry'; } else if (abilityConfig.abilityType === 'page') { @@ -96,6 +117,7 @@ function loadEntryObj(projectConfig) { const jsonString = fs.readFileSync(projectConfig.manifestFilePath).toString(); manifest = JSON.parse(jsonString); if (manifest && manifest.minPlatformVersion) { + process.env.minPlatformVersion = manifest.minPlatformVersion; partialUpdateController(manifest.minPlatformVersion); } projectConfig.pagesJsonFileName = 'config.json'; @@ -106,22 +128,24 @@ function loadEntryObj(projectConfig) { throw Error('\u001b[31m ERROR: the manifest file ' + projectConfig.manifestFilePath.replace(/\\/g, '/') + ' or module.json is lost or format is invalid. \u001b[39m').message; } - if (manifest.pages) { - const pages = manifest.pages; - pages.forEach((element) => { - const sourcePath = element.replace(/^\.\/ets\//, ''); - const fileName = path.resolve(projectConfig.projectPath, sourcePath + '.ets'); - if (fs.existsSync(fileName)) { - projectConfig.entryObj['./' + sourcePath] = fileName + '?entry'; - } else { - throw Error(`\u001b[31m ERROR: page '${fileName.replace(/\\/g, '/')}' does not exist. \u001b[39m`) - .message; - } - }); - } else { - throw Error('\u001b[31m ERROR: missing pages attribute in ' + - projectConfig.manifestFilePath.replace(/\\/g, '/') + - '. \u001b[39m').message; + if (!projectConfig.compileHar) { + if (manifest.pages) { + const pages = manifest.pages; + pages.forEach((element) => { + const sourcePath = element.replace(/^\.\/ets\//, ''); + const fileName = path.resolve(projectConfig.projectPath, sourcePath + '.ets'); + if (fs.existsSync(fileName)) { + projectConfig.entryObj['./' + sourcePath] = fileName + '?entry'; + } else { + throw Error(`\u001b[31m ERROR: page '${fileName.replace(/\\/g, '/')}' does not exist. \u001b[39m`) + .message; + } + }); + } else { + throw Error('\u001b[31m ERROR: missing pages attribute in ' + + projectConfig.manifestFilePath.replace(/\\/g, '/') + + '. \u001b[39m').message; + } } } } @@ -131,30 +155,129 @@ function buildManifest(manifest, aceConfigPath) { const moduleConfigJson = JSON.parse(fs.readFileSync(aceConfigPath).toString()); manifest.type = process.env.abilityType; if (moduleConfigJson && moduleConfigJson.app && moduleConfigJson.app.minAPIVersion) { - partialUpdateController(moduleConfigJson.app.minAPIVersion); + if (moduleConfigJson.module && moduleConfigJson.module.metadata) { + partialUpdateController(moduleConfigJson.app.minAPIVersion, moduleConfigJson.module.metadata); + stageOptimization(moduleConfigJson.module.metadata); + } else { + partialUpdateController(moduleConfigJson.app.minAPIVersion); + } } if (moduleConfigJson.module) { - manifest.pages = getPages(moduleConfigJson); + switch (moduleConfigJson.module.type) { + case 'har': + projectConfig.compileHar = true; + getPackageJsonEntryPath(); + break; + case 'shared': + projectConfig.compileShared = true; + getPackageJsonEntryPath(); + manifest.pages = getPages(moduleConfigJson); + break; + default: + manifest.pages = getPages(moduleConfigJson); + break; + } } else { - throw Error('\u001b[31m'+ + throw Error('\u001b[31m' + 'ERROR: the config.json file miss key word module || module[abilities].' + '\u001b[39m').message; } } catch (e) { - throw Error("\x1B[31m" + 'ERROR: the module.json file is lost or format is invalid.' + - "\x1B[39m").message; + if (/BUIDERROR/.test(e)) { + throw Error(e.replace('BUIDERROR', 'ERROR')).message; + } else { + throw Error("\x1B[31m" + 'ERROR: the module.json file is lost or format is invalid.' + + "\x1B[39m").message; + } + } +} + +function getPackageJsonEntryPath() { + const rootPackageJsonPath = path.resolve(projectConfig.projectPath, '../../../' + projectConfig.packageJson); + if (fs.existsSync(rootPackageJsonPath)) { + const rootPackageJsonContent = JSON.parse(fs.readFileSync(rootPackageJsonPath, 'utf-8')); + if (rootPackageJsonContent) { + if (rootPackageJsonContent.module) { + getEntryPath(rootPackageJsonContent.module, rootPackageJsonPath); + } else if (rootPackageJsonContent.main) { + getEntryPath(rootPackageJsonContent.main, rootPackageJsonPath); + } else { + getEntryPath('', rootPackageJsonPath); + } + } else if (projectConfig.compileHar) { + throw Error('\u001b[31m' + 'lack message in ' + projectConfig.packageJson + '.' + '\u001b[39m').message; + } + } +} + +function supportSuffix(mainEntryPath) { + if (fs.existsSync(path.join(mainEntryPath, 'index.ets'))) { + mainEntryPath = path.join(mainEntryPath, 'index.ets'); + } else if (fs.existsSync(path.join(mainEntryPath, 'index.ts'))) { + mainEntryPath = path.join(mainEntryPath, 'index.ts'); + } else if (fs.existsSync(path.join(mainEntryPath, 'index.js'))) { + mainEntryPath = path.join(mainEntryPath, 'index.js'); + } else if (projectConfig.compileHar) { + throw Error('\u001b[31m' + 'not find entry file in ' + projectConfig.packageJson + '.' + '\u001b[39m').message; + } + return mainEntryPath; +} + +function supportExtName(mainEntryPath) { + if (path.extname(mainEntryPath) === '') { + if (fs.existsSync(mainEntryPath + '.ets')) { + mainEntryPath = mainEntryPath + '.ets'; + } else if (fs.existsSync(mainEntryPath + '.ts')) { + mainEntryPath = mainEntryPath + '.ts'; + } else if (fs.existsSync(mainEntryPath + '.js')) { + mainEntryPath = mainEntryPath + '.js'; + } + } + return mainEntryPath; +} + +function getEntryPath(entryPath, rootPackageJsonPath) { + let mainEntryPath = path.resolve(rootPackageJsonPath, '../', entryPath); + if (fs.existsSync(mainEntryPath) && fs.statSync(mainEntryPath).isDirectory()) { + mainEntryPath = supportSuffix(mainEntryPath); + } else { + mainEntryPath = supportExtName(mainEntryPath); + } + if (fs.existsSync(mainEntryPath) && fs.statSync(mainEntryPath).isFile()) { + const entryKey = path.relative(projectConfig.projectPath, mainEntryPath); + projectConfig.entryObj[entryKey] = mainEntryPath; + abilityPagesFullPath.push(mainEntryPath); + } else if (projectConfig.compileHar) { + throw Error('\u001b[31m' + 'not find entry file in package.json.' + '\u001b[39m').message; + } +} + +function stageOptimization(metadata) { + if (Array.isArray(metadata) && metadata.length) { + metadata.some(item => { + if (item.name && item.name === 'USE_COMMON_CHUNK' && + item.value && item.value === 'true') { + projectConfig.splitCommon = true; + return true; + } + }); } } function getPages(configJson) { - const pages = [] + const pages = []; const pagesJsonFileName = `${configJson.module.pages.replace(/\$profile\:/, '')}.json`; const modulePagePath = path.resolve(projectConfig.aceProfilePath, pagesJsonFileName); if (fs.existsSync(modulePagePath)) { - const pagesConfig = JSON.parse(fs.readFileSync(modulePagePath, 'utf-8')); - if (pagesConfig && pagesConfig.src) { - projectConfig.pagesJsonFileName = pagesJsonFileName; - return pagesConfig.src; + try { + const pagesConfig = JSON.parse(fs.readFileSync(modulePagePath, 'utf-8')); + if (pagesConfig && pagesConfig.src) { + projectConfig.pagesJsonFileName = pagesJsonFileName; + return pagesConfig.src; + } + } catch (e) { + throw Error("\x1B[31m" + `BUIDERROR: the ${modulePagePath} file format is invalid.` + + "\x1B[39m").message; } } return pages; @@ -235,7 +358,7 @@ function setAbilityFile(projectConfig, abilityPages) { projectConfig.entryObj[entryPageKey] = projectAbilityPath + '?entry'; } else { throw Error( - `\u001b[31m ERROR: srcEntrance file '${projectAbilityPath.replace(/\\/g, '/')}' does not exist. \u001b[39m` + `\u001b[31m ERROR: srcEntry file '${projectAbilityPath.replace(/\\/g, '/')}' does not exist. \u001b[39m` ).message; } }); @@ -245,7 +368,11 @@ function readAbilityEntrance(moduleJson) { let abilityPages = []; if (moduleJson.module) { const moduleSrcEntrance = moduleJson.module.srcEntrance; - if (moduleSrcEntrance) { + const moduleSrcEntry = moduleJson.module.srcEntry; + if (moduleSrcEntry) { + abilityPages.push(moduleSrcEntry); + abilityPagesFullPath.push(getAbilityFullPath(projectConfig.projectPath, moduleSrcEntry)); + } else if (moduleSrcEntrance) { abilityPages.push(moduleSrcEntrance); abilityPagesFullPath.push(getAbilityFullPath(projectConfig.projectPath, moduleSrcEntrance)); } @@ -254,6 +381,7 @@ function readAbilityEntrance(moduleJson) { } if (moduleJson.module.extensionAbilities && moduleJson.module.extensionAbilities.length > 0) { setEntrance(moduleJson.module.extensionAbilities, abilityPages); + setCardPages(moduleJson.module.extensionAbilities); } } return abilityPages; @@ -262,7 +390,10 @@ function readAbilityEntrance(moduleJson) { function setEntrance(abilityConfig, abilityPages) { if (abilityConfig && abilityConfig.length > 0) { abilityConfig.forEach(ability => { - if (ability.srcEntrance) { + if (ability.srcEntry) { + abilityPages.push(ability.srcEntry) + abilityPagesFullPath.push(getAbilityFullPath(projectConfig.projectPath, ability.srcEntry)) + } else if (ability.srcEntrance) { abilityPages.push(ability.srcEntrance); abilityPagesFullPath.push(getAbilityFullPath(projectConfig.projectPath, ability.srcEntrance)); } @@ -270,6 +401,46 @@ function setEntrance(abilityConfig, abilityPages) { } } +function setCardPages(extensionAbilities) { + if (extensionAbilities && extensionAbilities.length > 0) { + extensionAbilities.forEach(extensionAbility => { + if (extensionAbility.metadata) { + extensionAbility.metadata.forEach(metadata => { + if (metadata.resource) { + readCardResource(metadata.resource); + } + }); + } + }); + } +} + +function readCardResource(resource) { + const cardJsonFileName = `${resource.replace(/\$profile\:/, '')}.json`; + const modulePagePath = path.resolve(projectConfig.aceProfilePath, cardJsonFileName); + if (fs.existsSync(modulePagePath)) { + const cardConfig = JSON.parse(fs.readFileSync(modulePagePath, 'utf-8')); + if (cardConfig.forms) { + cardConfig.forms.forEach(form => { + readCardForm(form); + }); + } + } +} + +function readCardForm(form) { + if ((form.type && form.type === 'eTS') || + (form.uiSyntax && form.uiSyntax === 'arkts')) { + const sourcePath = form.src.replace(/\.ets$/, ''); + const cardPath = path.resolve(projectConfig.projectPath, '..', sourcePath + '.ets'); + if (cardPath && fs.existsSync(cardPath)) { + projectConfig.entryObj['../' + sourcePath] = cardPath + '?entry'; + projectConfig.cardEntryObj['../' + sourcePath] = cardPath; + projectConfig.cardObj[cardPath] = sourcePath.replace(/^\.\//, ''); + } + } +} + function getAbilityFullPath(projectPath, abilityPath) { let finalPath = path.resolve(path.resolve(projectPath, '../'), abilityPath); finalPath = finalPath.replace(/\\/g, '/'); @@ -294,50 +465,89 @@ function loadWorker(projectConfig, workerFileEntry) { .replace(/\.(ts|js)$/, '').replace(/\\/g, '/'); projectConfig.entryObj[`./${WORKERS_DIR}/` + relativePath] = item; } - }) + }); } } } +let aceBuildJson = {}; +function loadBuildJson() { + if (projectConfig.aceBuildJson && fs.existsSync(projectConfig.aceBuildJson)) { + aceBuildJson = JSON.parse(fs.readFileSync(projectConfig.aceBuildJson).toString()); + } + if (aceBuildJson.packageManagerType === 'ohpm') { + projectConfig.packageDir = 'oh_modules'; + projectConfig.packageJson = 'oh-package.json5'; + } +} + +function initBuildInfo() { + projectConfig.projectRootPath = aceBuildJson.projectRootPath; + if (projectConfig.compileHar && aceBuildJson.moduleName && + aceBuildJson.modulePathMap[aceBuildJson.moduleName]) { + projectConfig.moduleRootPath = aceBuildJson.modulePathMap[aceBuildJson.moduleName]; + } +} + function readWorkerFile() { const workerFileEntry = {}; - if (projectConfig.aceBuildJson && fs.existsSync(projectConfig.aceBuildJson)) { - const workerConfig = JSON.parse(fs.readFileSync(projectConfig.aceBuildJson).toString()); - if (workerConfig.workers) { - workerConfig.workers.forEach(worker => { - if (!/\.(ts|js)$/.test(worker)) { - worker += '.ts'; - } - const relativePath = path.relative(projectConfig.projectPath, worker); - if (filterWorker(relativePath)) { - workerFileEntry[relativePath.replace(/\.(ts|js)$/, '').replace(/\\/g, '/')] = worker; + if (aceBuildJson.workers) { + aceBuildJson.workers.forEach(worker => { + if (!/\.(ts|js)$/.test(worker)) { + worker += '.ts'; + } + const relativePath = path.relative(projectConfig.projectPath, worker); + if (filterWorker(relativePath)) { + const workerKey = relativePath.replace(/\.(ts|js)$/, '').replace(/\\/g, '/'); + if (workerFileEntry[workerKey]) { + throw Error( + '\u001b[31m ERROR: The worker file cannot use the same file name: \n' + + workerFileEntry[workerKey] + '\n' + worker + '\u001b[39m' + ).message; + } else { + workerFileEntry[workerKey] = worker; } - }); - return workerFileEntry; - } + } + }); + return workerFileEntry; } return null; } +function readPatchConfig() { + if (aceBuildJson.patchConfig) { + projectConfig.hotReload = process.env.watchMode === 'true' && !projectConfig.isPreview; + projectConfig.patchAbcPath = aceBuildJson.patchConfig.patchAbcPath; + projectConfig.changedFileList = aceBuildJson.patchConfig.changedFileList ? + aceBuildJson.patchConfig.changedFileList : path.join(projectConfig.cachePath, 'changedFileList.json'); + if (projectConfig.hotReload) { + writeFileSync(projectConfig.changedFileList, JSON.stringify({ + modifiedFiles: [], + removedFiles: [] + })); + } + } +} + function filterWorker(workerPath) { return /\.(ts|js)$/.test(workerPath); } ;(function initSystemResource() { - const sysResourcePath = path.resolve('./sysResource.js'); + const sysResourcePath = path.resolve(__dirname, './sysResource.js'); if (fs.existsSync(sysResourcePath)) { resources.sys = require(sysResourcePath).sys; } })(); ;(function readSystemModules() { - const systemModulesPath = path.resolve(__dirname,'../../api'); + const systemModulesPath = path.resolve(__dirname, '../../api'); if (fs.existsSync(systemModulesPath)) { systemModules.push(...fs.readdirSync(systemModulesPath)); } })() -function readAppResource(resources, filePath) { +function readAppResource(filePath) { if (fs.existsSync(filePath)) { const appResource = fs.readFileSync(filePath, "utf-8"); const resourceArr = appResource.split(/\n/); @@ -367,7 +577,7 @@ function processResourceArr(resourceArr, resourceMap, filePath) { resourceMap.set(resourceData[0], obj); } } else { - logger.warn(`\u001b[31m ETS:WARN The format of file '${filePath}' is incorrect. \u001b[39m`); + logger.warn(`\u001b[31m ArkTS:WARN The format of file '${filePath}' is incorrect. \u001b[39m`); break; } } @@ -381,22 +591,47 @@ function hashProjectPath(projectPath) { function loadModuleInfo(projectConfig, envArgs) { if (projectConfig.aceBuildJson && fs.existsSync(projectConfig.aceBuildJson)) { const buildJsonInfo = JSON.parse(fs.readFileSync(projectConfig.aceBuildJson).toString()); - projectConfig.compileMode = buildJsonInfo.compileMode; + if (buildJsonInfo.compileMode) { + projectConfig.compileMode = buildJsonInfo.compileMode; + } projectConfig.projectRootPath = buildJsonInfo.projectRootPath; projectConfig.modulePathMap = buildJsonInfo.modulePathMap; projectConfig.isOhosTest = buildJsonInfo.isOhosTest; - projectConfig.processTs = false; - projectConfig.buildArkMode = envArgs.buildMode; + let faultHandler = function (error) { + // rollup's error will be handled in fast build + if (process.env.compileTool === 'rollup') { + return; + } + logger.error(error); + process.exit(FAIL); + } + if (checkAotConfig(buildJsonInfo, faultHandler)) { + projectConfig.processTs = true; + projectConfig.pandaMode = TS2ABC; + projectConfig.anBuildOutPut = buildJsonInfo.anBuildOutPut; + projectConfig.anBuildMode = buildJsonInfo.anBuildMode; + projectConfig.apPath = buildJsonInfo.apPath; + } else { + projectConfig.processTs = false; + projectConfig.pandaMode = buildJsonInfo.pandaMode; + } + if (envArgs !== undefined) { + projectConfig.buildArkMode = envArgs.buildMode; + } if (buildJsonInfo.compileMode === 'esmodule') { projectConfig.nodeModulesPath = buildJsonInfo.nodeModulesPath; + projectConfig.harNameOhmMap = buildJsonInfo.harNameOhmMap; + } + if (projectConfig.compileHar && buildJsonInfo.moduleName && + buildJsonInfo.modulePathMap[buildJsonInfo.moduleName]) { + projectConfig.moduleRootPath = buildJsonInfo.modulePathMap[buildJsonInfo.moduleName]; } - projectConfig.pandaMode = buildJsonInfo.pandaMode; } } function checkAppResourcePath(appResourcePath, config) { if (appResourcePath) { - readAppResource(resources, appResourcePath); + readAppResource(appResourcePath); if (fs.existsSync(appResourcePath) && config.cache) { config.cache.buildDependencies.config.push(appResourcePath); } @@ -436,13 +671,40 @@ function addSDKBuildDependencies(config) { } } -function partialUpdateController(minAPIVersion) { - if (partialUpdateConfig.alwaysClose) { - return; +function getCleanConfig(workerFile) { + const cleanPath = []; + if (projectConfig.compileMode === 'esmodule') { + return cleanPath; + } + cleanPath.push(projectConfig.buildPath); + if (workerFile) { + const workerFilesPath = Object.keys(workerFile); + for (const workerFilePath of workerFilesPath) { + cleanPath.push(path.join(projectConfig.buildPath, workerFilePath, '..')); + } } + return cleanPath; +} + +function isPartialUpdate(metadata) { + if (Array.isArray(metadata) && metadata.length) { + metadata.some(item => { + if (item.name && item.name === 'ArkTSPartialUpdate' && + item.value && item.value === 'false') { + partialUpdateConfig.partialUpdateMode = false; + } + return !partialUpdateConfig.partialUpdateMode; + }); + } +} + +function partialUpdateController(minAPIVersion, metadata = null) { if (minAPIVersion >= 9) { partialUpdateConfig.partialUpdateMode = true; } + if (metadata) { + isPartialUpdate(metadata); + } } const globalProgram = { @@ -451,7 +713,6 @@ const globalProgram = { }; const partialUpdateConfig = { - alwaysClose: true, partialUpdateMode: false }; @@ -468,4 +729,7 @@ exports.loadModuleInfo = loadModuleInfo; exports.systemModules = systemModules; exports.checkAppResourcePath = checkAppResourcePath; exports.addSDKBuildDependencies = addSDKBuildDependencies; -exports.partialUpdateConfig = partialUpdateConfig; \ No newline at end of file +exports.partialUpdateConfig = partialUpdateConfig; +exports.readPatchConfig = readPatchConfig; +exports.initBuildInfo = initBuildInfo; +exports.getCleanConfig = getCleanConfig; diff --git a/compiler/npm-install.js b/compiler/npm-install.js index 32ae7ec450f5e4d1aef3a9b6615c4ba4541c7a08..799f7ac367f815e6a4e9358f91a3bac98a36a8a4 100644 --- a/compiler/npm-install.js +++ b/compiler/npm-install.js @@ -49,3 +49,12 @@ exec('npm install', { cwd: cwd }, function(err, stdout, stderr) { console.error('[31m', `npm install filed: ${err}`, '[39m'); } }); + +cwd = path.join(cwd, "legacy_api8"); + +exec('npm install', { cwd: cwd }, function(err, stdout, stderr) { + console.log('[31m', stdout, '[39m'); + if (err !== null) { + console.error('[31m', `npm install filed: ${err}`, '[39m'); + } +}); \ No newline at end of file diff --git a/compiler/package-lock.json b/compiler/package-lock.json index 37da748696d1727ce363b299dc8a11ce67cb2e3e..e58a90602763c60ecc7d7cf756ad1500eac255aa 100644 --- a/compiler/package-lock.json +++ b/compiler/package-lock.json @@ -249,7 +249,6 @@ "version": "7.18.6", "resolved": "https://repo.huaweicloud.com/repository/npm/@babel/helper-module-imports/-/helper-module-imports-7.18.6.tgz", "integrity": "sha512-0NFvs3VkuSYbFi1x2Vd6tKrywq+z/cLeYC/RJNFrIX/30Bf5aiGYbtvGXolEktzJH8o5E5KJ3tT+nkxuuZFVlA==", - "dev": true, "requires": { "@babel/types": "^7.18.6" } @@ -340,8 +339,7 @@ "@babel/helper-validator-identifier": { "version": "7.18.6", "resolved": "https://repo.huaweicloud.com/repository/npm/@babel/helper-validator-identifier/-/helper-validator-identifier-7.18.6.tgz", - "integrity": "sha512-MmetCkz9ej86nJQV+sFCxoGGrUbU3q02kgLciwkrt9QqEB7cP39oKEY0PakknEO0Gu20SskMRi+AYZ3b1TpN9g==", - "dev": true + "integrity": "sha512-MmetCkz9ej86nJQV+sFCxoGGrUbU3q02kgLciwkrt9QqEB7cP39oKEY0PakknEO0Gu20SskMRi+AYZ3b1TpN9g==" }, "@babel/helper-validator-option": { "version": "7.18.6", @@ -1248,7 +1246,6 @@ "version": "7.18.7", "resolved": "https://repo.huaweicloud.com/repository/npm/@babel/types/-/types-7.18.7.tgz", "integrity": "sha512-QG3yxTcTIBoAcQmkCs+wAPYZhu7Dk9rXKacINfNbdJDNERTbLQbHGyVG8q/YGMPeCJRIhSY0+fTc5+xuh6WPSQ==", - "dev": true, "requires": { "@babel/helper-validator-identifier": "^7.18.6", "to-fast-properties": "^2.0.0" @@ -1383,6 +1380,88 @@ "fastq": "^1.6.0" } }, + "@rollup/plugin-babel": { + "version": "6.0.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/@rollup/plugin-babel/-/plugin-babel-6.0.3.tgz", + "integrity": "sha512-fKImZKppa1A/gX73eg4JGo+8kQr/q1HBQaCGKECZ0v4YBBv3lFqi14+7xyApECzvkLTHCifx+7ntcrvtBIRcpg==", + "requires": { + "@babel/helper-module-imports": "^7.18.6", + "@rollup/pluginutils": "^5.0.1" + } + }, + "@rollup/plugin-commonjs": { + "version": "23.0.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/@rollup/plugin-commonjs/-/plugin-commonjs-23.0.2.tgz", + "integrity": "sha512-e9ThuiRf93YlVxc4qNIurvv+Hp9dnD+4PjOqQs5vAYfcZ3+AXSrcdzXnVjWxcGQOa6KGJFcRZyUI3ktWLavFjg==", + "requires": { + "@rollup/pluginutils": "^5.0.1", + "commondir": "^1.0.1", + "estree-walker": "^2.0.2", + "glob": "^8.0.3", + "is-reference": "1.2.1", + "magic-string": "^0.26.4" + }, + "dependencies": { + "brace-expansion": { + "version": "2.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/brace-expansion/-/brace-expansion-2.0.1.tgz", + "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", + "requires": { + "balanced-match": "^1.0.0" + } + }, + "glob": { + "version": "8.0.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/glob/-/glob-8.0.3.tgz", + "integrity": "sha512-ull455NHSHI/Y1FqGaaYFaLGkNMMJbavMrEGFXG/PGrg6y7sutWHUHrz6gy6WEBH6akM1M414dWKCNs+IhKdiQ==", + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^5.0.1", + "once": "^1.3.0" + } + }, + "minimatch": { + "version": "5.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/minimatch/-/minimatch-5.1.0.tgz", + "integrity": "sha512-9TPBGGak4nHfGZsPBohm9AWg6NoT7QTCehS3BIJABslyZbzxfV78QM2Y6+i741OPZIafFAaiiEMh5OyIrJPgtg==", + "requires": { + "brace-expansion": "^2.0.1" + } + } + } + }, + "@rollup/plugin-node-resolve": { + "version": "15.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@rollup/plugin-node-resolve/-/plugin-node-resolve-15.0.1.tgz", + "integrity": "sha512-ReY88T7JhJjeRVbfCyNj+NXAG3IIsVMsX9b5/9jC98dRP8/yxlZdz7mHZbHk5zHr24wZZICS5AcXsFZAXYUQEg==", + "requires": { + "@rollup/pluginutils": "^5.0.1", + "@types/resolve": "1.20.2", + "deepmerge": "^4.2.2", + "is-builtin-module": "^3.2.0", + "is-module": "^1.0.0", + "resolve": "^1.22.1" + } + }, + "@rollup/pluginutils": { + "version": "5.0.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/@rollup/pluginutils/-/pluginutils-5.0.2.tgz", + "integrity": "sha512-pTd9rIsP92h+B6wWwFbW8RkZv4hiR/xKsqre4SIuAOaOEQRxi0lqLke9k2/7WegC85GgUs9pjmOjCUi3In4vwA==", + "requires": { + "@types/estree": "^1.0.0", + "estree-walker": "^2.0.2", + "picomatch": "^2.3.1" + }, + "dependencies": { + "@types/estree": { + "version": "1.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/@types/estree/-/estree-1.0.0.tgz", + "integrity": "sha512-WulqXMDUTYAXCjZnk6JtIHPigp55cVtDgDrO2gHRwhyJto21+1zbVCtOYB2L1F9w4qCQ0rOGWBnBe0FNTiEJIQ==" + } + } + }, "@types/eslint": { "version": "8.4.3", "resolved": "https://repo.huaweicloud.com/repository/npm/@types/eslint/-/eslint-8.4.3.tgz", @@ -1406,6 +1485,14 @@ "resolved": "https://repo.huaweicloud.com/repository/npm/@types/estree/-/estree-0.0.51.tgz", "integrity": "sha512-CuPgU6f3eT/XgKKPqKd/gLZV1Xmvf1a2R5POBOGQa6uv82xpls89HU5zKeVoyR8XzHd1RGNOlQlvUe3CFkjWNQ==" }, + "@types/fs-extra": { + "version": "8.1.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/@types/fs-extra/-/fs-extra-8.1.2.tgz", + "integrity": "sha512-SvSrYXfWSc7R4eqnOzbQF4TZmfpNSM9FrSWLU3EUnWBuyZqNBOrv1B1JA3byUDPUl9z4Ab3jeZG2eDdySlgNMg==", + "requires": { + "@types/node": "*" + } + }, "@types/glob": { "version": "7.2.0", "resolved": "https://repo.huaweicloud.com/repository/npm/@types/glob/-/glob-7.2.0.tgz", @@ -1430,6 +1517,11 @@ "resolved": "https://repo.huaweicloud.com/repository/npm/@types/node/-/node-18.0.0.tgz", "integrity": "sha512-cHlGmko4gWLVI27cGJntjs/Sj8th9aYwplmZFwmmgYQQvL5NUsgVJG7OddLvNfLqYS31KFN0s3qlaD9qCaxACA==" }, + "@types/resolve": { + "version": "1.20.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/@types/resolve/-/resolve-1.20.2.tgz", + "integrity": "sha512-60BCwRFOZCQhDncwQdxxeOEEkbc5dIMccYLwbxsS4TUNeVECQ/pBJ0j09mrHOl/JJvpRPGwO9SvE4nR2Nb/a4Q==" + }, "@types/source-list-map": { "version": "0.1.2", "resolved": "https://repo.huaweicloud.com/repository/npm/@types/source-list-map/-/source-list-map-0.1.2.tgz", @@ -1734,6 +1826,15 @@ "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", "dev": true }, + "aggregate-error": { + "version": "3.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/aggregate-error/-/aggregate-error-3.1.0.tgz", + "integrity": "sha512-4I7Td01quW/RpocfNayFdFVk1qSuoh0E7JrbRJ16nH01HhKFQ88INq9Sd+nd72zqRySlr9BmDA8xlEJ6vJMrYA==", + "requires": { + "clean-stack": "^2.0.0", + "indent-string": "^4.0.0" + } + }, "ajv": { "version": "6.12.6", "resolved": "https://repo.huaweicloud.com/repository/npm/ajv/-/ajv-6.12.6.tgz", @@ -1961,6 +2062,11 @@ "resolved": "https://repo.huaweicloud.com/repository/npm/buffer-from/-/buffer-from-1.1.2.tgz", "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==" }, + "builtin-modules": { + "version": "3.3.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/builtin-modules/-/builtin-modules-3.3.0.tgz", + "integrity": "sha512-zhaCDicdLuWN5UbN5IMnFqNMhNfo919sH85y2/ea+5Yg9TsTkeZxpL+JLbp6cgYFS4sRLp3YV4S6yDuqVWHYOw==" + }, "call-bind": { "version": "1.0.2", "resolved": "https://repo.huaweicloud.com/repository/npm/call-bind/-/call-bind-1.0.2.tgz", @@ -2045,6 +2151,11 @@ "resolved": "https://repo.huaweicloud.com/repository/npm/chrome-trace-event/-/chrome-trace-event-1.0.3.tgz", "integrity": "sha512-p3KULyQg4S7NIHixdwbGX+nFHkoBiA4YQmyWtjb8XngSKV124nJmRysgAeujbUVb15vh+RvFUfCPqU7rXk+hZg==" }, + "clean-stack": { + "version": "2.2.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/clean-stack/-/clean-stack-2.2.0.tgz", + "integrity": "sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A==" + }, "clean-webpack-plugin": { "version": "3.0.0", "resolved": "https://repo.huaweicloud.com/repository/npm/clean-webpack-plugin/-/clean-webpack-plugin-3.0.0.tgz", @@ -2101,8 +2212,7 @@ "commondir": { "version": "1.0.1", "resolved": "https://repo.huaweicloud.com/repository/npm/commondir/-/commondir-1.0.1.tgz", - "integrity": "sha512-W9pAhw0ja1Edb5GVdIF1mjZw/ASI0AlShXM83UUGe2DVr5TdAPEA1OA8m/g8zWp9x6On7gqufY+FatDbC3MDQg==", - "dev": true + "integrity": "sha512-W9pAhw0ja1Edb5GVdIF1mjZw/ASI0AlShXM83UUGe2DVr5TdAPEA1OA8m/g8zWp9x6On7gqufY+FatDbC3MDQg==" }, "concat-map": { "version": "0.0.1", @@ -2243,6 +2353,11 @@ "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", "dev": true }, + "deepmerge": { + "version": "4.2.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/deepmerge/-/deepmerge-4.2.2.tgz", + "integrity": "sha512-FJ3UgI4gIl+PHZm53knsuSFpE+nESMr7M4v9QcgB7S63Kj/6WqMiFQJpBBYz1Pt+66bZpP3Q7Lye0Oo9MPKEdg==" + }, "define-properties": { "version": "1.1.4", "resolved": "https://repo.huaweicloud.com/repository/npm/define-properties/-/define-properties-1.1.4.tgz", @@ -2534,6 +2649,11 @@ "resolved": "https://repo.huaweicloud.com/repository/npm/estraverse/-/estraverse-4.3.0.tgz", "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==" }, + "estree-walker": { + "version": "2.0.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/estree-walker/-/estree-walker-2.0.2.tgz", + "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==" + }, "esutils": { "version": "2.0.3", "resolved": "https://repo.huaweicloud.com/repository/npm/esutils/-/esutils-2.0.3.tgz", @@ -2707,7 +2827,6 @@ "version": "2.3.2", "resolved": "https://repo.huaweicloud.com/repository/npm/fsevents/-/fsevents-2.3.2.tgz", "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", - "dev": true, "optional": true }, "function-bind": { @@ -2894,6 +3013,11 @@ "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", "dev": true }, + "indent-string": { + "version": "4.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/indent-string/-/indent-string-4.0.0.tgz", + "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==" + }, "inflight": { "version": "1.0.6", "resolved": "https://repo.huaweicloud.com/repository/npm/inflight/-/inflight-1.0.6.tgz", @@ -2927,6 +3051,14 @@ "resolved": "https://repo.huaweicloud.com/repository/npm/is-buffer/-/is-buffer-1.1.6.tgz", "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==" }, + "is-builtin-module": { + "version": "3.2.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-builtin-module/-/is-builtin-module-3.2.0.tgz", + "integrity": "sha512-phDA4oSGt7vl1n5tJvTWooWWAsXLY+2xCnxNqvKhGEzujg+A43wPlPOyDg3C8XQHN+6k/JTQWJ/j0dQh/qr+Hw==", + "requires": { + "builtin-modules": "^3.3.0" + } + }, "is-core-module": { "version": "2.9.0", "resolved": "https://repo.huaweicloud.com/repository/npm/is-core-module/-/is-core-module-2.9.0.tgz", @@ -2954,6 +3086,11 @@ "is-extglob": "^2.1.1" } }, + "is-module": { + "version": "1.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-module/-/is-module-1.0.0.tgz", + "integrity": "sha512-51ypPSPCoTEIN9dy5Oy+h4pShgJmPCygKfyRCISBI+JoWT/2oJvK8QPxmwv7b/p239jXrm9M1mlQbyKJ5A152g==" + }, "is-number": { "version": "7.0.0", "resolved": "https://repo.huaweicloud.com/repository/npm/is-number/-/is-number-7.0.0.tgz", @@ -2994,6 +3131,14 @@ "isobject": "^3.0.1" } }, + "is-reference": { + "version": "1.2.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-reference/-/is-reference-1.2.1.tgz", + "integrity": "sha512-U82MsXXiFIrjCK4otLT+o2NA2Cd2g5MLoOVXUZjIOhLurrRxpEXzI8O0KZHr3IjLvlAH1kTPYSuqer5T9ZVBKQ==", + "requires": { + "@types/estree": "*" + } + }, "isarray": { "version": "1.0.0", "resolved": "https://repo.huaweicloud.com/repository/npm/isarray/-/isarray-1.0.0.tgz", @@ -3119,6 +3264,11 @@ "p-locate": "^4.1.0" } }, + "lodash": { + "version": "4.17.21", + "resolved": "https://repo.huaweicloud.com/repository/npm/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==" + }, "lodash.debounce": { "version": "4.0.8", "resolved": "https://repo.huaweicloud.com/repository/npm/lodash.debounce/-/lodash.debounce-4.0.8.tgz", @@ -3175,6 +3325,14 @@ "yallist": "^4.0.0" } }, + "magic-string": { + "version": "0.26.7", + "resolved": "https://repo.huaweicloud.com/repository/npm/magic-string/-/magic-string-0.26.7.tgz", + "integrity": "sha512-hX9XH3ziStPoPhJxLq1syWuZMxbDvGNbVchfrdCtanC7D13888bMFow61x8axrx+GfHLtVeAx2kxL7tTGRl+Ow==", + "requires": { + "sourcemap-codec": "^1.4.8" + } + }, "make-dir": { "version": "2.1.0", "resolved": "https://repo.huaweicloud.com/repository/npm/make-dir/-/make-dir-2.1.0.tgz", @@ -3592,12 +3750,6 @@ "integrity": "sha512-Dp6zGqpTdETdR63lehJYPeIOqpiNBNtc7BpWSLrOje7UaIsE5aY92r/AunQA7rsXvet3lrJ3JnZX29UPTKXyKQ==", "dev": true }, - "pegjs": { - "version": "0.10.0", - "resolved": "https://repo.huaweicloud.com/repository/npm/pegjs/-/pegjs-0.10.0.tgz", - "integrity": "sha512-qI5+oFNEGi3L5HAxDwN2LA4Gg7irF70Zs25edhjld9QemOgp0CbvMtbFcMvFtEo1OityPrcCzkQFB8JP/hxgow==", - "dev": true - }, "picocolors": { "version": "1.0.0", "resolved": "https://repo.huaweicloud.com/repository/npm/picocolors/-/picocolors-1.0.0.tgz", @@ -3839,6 +3991,147 @@ "glob": "^7.1.3" } }, + "rollup": { + "version": "3.5.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/rollup/-/rollup-3.5.0.tgz", + "integrity": "sha512-TYu2L+TGhmNsXCtByont89u+ATQLcDy6A+++PwLXYunRtOm7XnaD+65s1pvewaOxMYR0eOkMXn9/i0saBxxpnQ==", + "requires": { + "fsevents": "~2.3.2" + } + }, + "rollup-plugin-copy": { + "version": "3.4.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/rollup-plugin-copy/-/rollup-plugin-copy-3.4.0.tgz", + "integrity": "sha512-rGUmYYsYsceRJRqLVlE9FivJMxJ7X6jDlP79fmFkL8sJs7VVMSVyA2yfyL+PGyO/vJs4A87hwhgVfz61njI+uQ==", + "requires": { + "@types/fs-extra": "^8.0.1", + "colorette": "^1.1.0", + "fs-extra": "^8.1.0", + "globby": "10.0.1", + "is-plain-object": "^3.0.0" + }, + "dependencies": { + "array-union": { + "version": "2.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/array-union/-/array-union-2.1.0.tgz", + "integrity": "sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==" + }, + "colorette": { + "version": "1.4.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/colorette/-/colorette-1.4.0.tgz", + "integrity": "sha512-Y2oEozpomLn7Q3HFP7dpww7AtMJplbM9lGZP6RDfHqmbeRjiwRg4n6VM6j4KLmRke85uWEI7JqF17f3pqdRA0g==" + }, + "fs-extra": { + "version": "8.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/fs-extra/-/fs-extra-8.1.0.tgz", + "integrity": "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==", + "requires": { + "graceful-fs": "^4.2.0", + "jsonfile": "^4.0.0", + "universalify": "^0.1.0" + } + }, + "globby": { + "version": "10.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/globby/-/globby-10.0.1.tgz", + "integrity": "sha512-sSs4inE1FB2YQiymcmTv6NWENryABjUNPeWhOvmn4SjtKybglsyPZxFB3U1/+L1bYi0rNZDqCLlHyLYDl1Pq5A==", + "requires": { + "@types/glob": "^7.1.1", + "array-union": "^2.1.0", + "dir-glob": "^3.0.1", + "fast-glob": "^3.0.3", + "glob": "^7.1.3", + "ignore": "^5.1.1", + "merge2": "^1.2.3", + "slash": "^3.0.0" + } + }, + "is-plain-object": { + "version": "3.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-plain-object/-/is-plain-object-3.0.1.tgz", + "integrity": "sha512-Xnpx182SBMrr/aBik8y+GuR4U1L9FqMSojwDQwPMmxyC6bvEqly9UBCxhauBF5vNh2gwWJNX6oDV7O+OM4z34g==" + }, + "jsonfile": { + "version": "4.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/jsonfile/-/jsonfile-4.0.0.tgz", + "integrity": "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==", + "requires": { + "graceful-fs": "^4.1.6" + } + }, + "universalify": { + "version": "0.1.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/universalify/-/universalify-0.1.2.tgz", + "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==" + } + } + }, + "rollup-plugin-delete": { + "version": "2.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/rollup-plugin-delete/-/rollup-plugin-delete-2.0.0.tgz", + "integrity": "sha512-/VpLMtDy+8wwRlDANuYmDa9ss/knGsAgrDhM+tEwB1npHwNu4DYNmDfUL55csse/GHs9Q+SMT/rw9uiaZ3pnzA==", + "requires": { + "del": "^5.1.0" + }, + "dependencies": { + "array-union": { + "version": "2.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/array-union/-/array-union-2.1.0.tgz", + "integrity": "sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==" + }, + "del": { + "version": "5.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/del/-/del-5.1.0.tgz", + "integrity": "sha512-wH9xOVHnczo9jN2IW68BabcecVPxacIA3g/7z6vhSU/4stOKQzeCRK0yD0A24WiAAUJmmVpWqrERcTxnLo3AnA==", + "requires": { + "globby": "^10.0.1", + "graceful-fs": "^4.2.2", + "is-glob": "^4.0.1", + "is-path-cwd": "^2.2.0", + "is-path-inside": "^3.0.1", + "p-map": "^3.0.0", + "rimraf": "^3.0.0", + "slash": "^3.0.0" + } + }, + "globby": { + "version": "10.0.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/globby/-/globby-10.0.2.tgz", + "integrity": "sha512-7dUi7RvCoT/xast/o/dLN53oqND4yk0nsHkhRgn9w65C4PofCLOoJ39iSOg+qVDdWQPIEj+eszMHQ+aLVwwQSg==", + "requires": { + "@types/glob": "^7.1.1", + "array-union": "^2.1.0", + "dir-glob": "^3.0.1", + "fast-glob": "^3.0.3", + "glob": "^7.1.3", + "ignore": "^5.1.1", + "merge2": "^1.2.3", + "slash": "^3.0.0" + } + }, + "is-path-inside": { + "version": "3.0.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-path-inside/-/is-path-inside-3.0.3.tgz", + "integrity": "sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ==" + }, + "p-map": { + "version": "3.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/p-map/-/p-map-3.0.0.tgz", + "integrity": "sha512-d3qXVTF/s+W+CdJ5A29wywV2n8CQQYahlgz2bFiA+4eVNJbHJodPZ+/gXwPGh0bOqA+j8S+6+ckmvLGPk1QpxQ==", + "requires": { + "aggregate-error": "^3.0.0" + } + }, + "rimraf": { + "version": "3.0.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/rimraf/-/rimraf-3.0.2.tgz", + "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", + "requires": { + "glob": "^7.1.3" + } + } + } + }, "run-parallel": { "version": "1.2.0", "resolved": "https://repo.huaweicloud.com/repository/npm/run-parallel/-/run-parallel-1.2.0.tgz", @@ -3929,6 +4222,11 @@ "source-map": "^0.6.0" } }, + "sourcemap-codec": { + "version": "1.4.8", + "resolved": "https://repo.huaweicloud.com/repository/npm/sourcemap-codec/-/sourcemap-codec-1.4.8.tgz", + "integrity": "sha512-9NykojV5Uih4lgo5So5dtw+f0JgJX30KCNI8gwhz2J9A15wD0Ml6tjHKwf6fTSa6fAdVBdZeNOs9eJ71qCk8vA==" + }, "sprintf-js": { "version": "1.0.3", "resolved": "https://repo.huaweicloud.com/repository/npm/sprintf-js/-/sprintf-js-1.0.3.tgz", @@ -4079,8 +4377,7 @@ "to-fast-properties": { "version": "2.0.0", "resolved": "https://repo.huaweicloud.com/repository/npm/to-fast-properties/-/to-fast-properties-2.0.0.tgz", - "integrity": "sha512-/OaKK0xYrs3DmxRYqL/yDc+FxFUVYhDlXMhRmv3z915w2HF1tnN1omB354j8VUGO/hbRzyD6Y3sA7v7GS/ceog==", - "dev": true + "integrity": "sha512-/OaKK0xYrs3DmxRYqL/yDc+FxFUVYhDlXMhRmv3z915w2HF1tnN1omB354j8VUGO/hbRzyD6Y3sA7v7GS/ceog==" }, "to-regex-range": { "version": "5.0.1", @@ -4162,7 +4459,7 @@ }, "typescript": { "version": "file:deps/ohos-typescript-4.2.3-r2.tgz", - "integrity": "sha512-jBZS5mCU3BP1lfQpS2thP5uIRNObHEmH2cqJgEzpmh0H5Hgn4XZVMCCzyfUPbze6Gm+qEwAXWOL4ljcwbjZDEA==" + "integrity": "sha512-EgfQyxAFWaYxjuDw26Ub4al9+ihVhymnE7fp84C5AoTfyclZLFeRVv7Duv20Pgku7+euJ8vBeh3oFgHl7jhbEg==" }, "uglify-js": { "version": "3.16.1", diff --git a/compiler/package.json b/compiler/package.json index 8f9972544c25bb871d6073aff35b6ff11db915a4..4c01e7bb46aee06200795df5fa07dbdc228102ea 100644 --- a/compiler/package.json +++ b/compiler/package.json @@ -10,13 +10,13 @@ ], "scripts": { "lint": "eslint --fix ./src --ext .ts", - "build": "npm run generateSyntaxParser && npm run generateDeclarations && ./node_modules/.bin/babel ./src --out-dir lib --extensions .ts && node uglify-source.js lib", + "build": "npm run generateDeclarations && ./node_modules/.bin/babel ./src --out-dir lib --extensions .ts && node uglify-source.js lib", "create": "node ./lib/create.js --env projectName", "compile": "webpack --config webpack.config.js --env buildMode=debug projectName", "test": "npm run build && mocha -r mocha-context/register test/test.js && mocha -r mocha-context/register test/test.js --partialUpdate", "generateDeclarations": "node ./build_declarations_file.js ../../../interface/sdk-js/api/@internal/component/ets ./declarations ./lib", - "generateSyntaxParser": "node build_parser.js ./syntax_parser/dist", - "postinstall": "node npm-install.js" + "postinstall": "node npm-install.js", + "fastbuild": "rollup -c rollup.config.js" }, "devDependencies": { "@babel/cli": "^7.8.4", @@ -32,19 +32,25 @@ "file-loader": "^6.2.0", "mocha": "^8.2.1", "mocha-context": "^0.1.5", - "pegjs": "^0.10.0", "ts-node": "^9.1.1", "uglify-js": "^3.13.0", "url-loader": "^4.1.1" }, "dependencies": { + "@rollup/plugin-babel": "^6.0.3", + "@rollup/plugin-commonjs": "^23.0.2", + "@rollup/plugin-node-resolve": "^15.0.1", "clean-webpack-plugin": "^3.0.0", "copy-webpack-plugin": "^8.1.0", "deccjsunit": "^1.0.8", "hypium": "^1.0.0", "ignore-loader": "^0.1.2", + "lodash": "^4.17.21", "log4js": "^6.3.0", "md5": "^2.3.0", + "rollup": "^3.5.0", + "rollup-plugin-copy": "^3.4.0", + "rollup-plugin-delete": "^2.0.0", "ts-loader": "^8.0.12", "typescript": "file:./deps/ohos-typescript-4.2.3-r2.tgz", "webpack": "^5.70.0", diff --git a/compiler/rollup.config.js b/compiler/rollup.config.js new file mode 100644 index 0000000000000000000000000000000000000000..38dce619ee4b4c00237f6605e6d81ea5d611f394 --- /dev/null +++ b/compiler/rollup.config.js @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2023 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. + */ + +const path = require('path'); +const commonjs = require('@rollup/plugin-commonjs'); +const resolve = require('@rollup/plugin-node-resolve'); +const copyPlugin = require('rollup-plugin-copy'); +const deletePlugin = require('rollup-plugin-delete'); +const { getBabelOutputPlugin } = require('@rollup/plugin-babel'); + +const { + projectConfig, + readAppResource, + getCleanConfig +} = require('./main'); +const { + getEntryObj, + workerFile, + setCopyPluginConfig +} = require('./lib/fast_build/common/process_project_config'); +const { + getResolveModules +} = require('./lib/utils'); +const { etsTransform } = require('./lib/fast_build/ets_ui/rollup-plugin-ets-typescript'); +const { etsChecker } = require('./lib/fast_build/ets_ui/rollup-plugin-ets-checker'); +const { apiTransform } = require('./lib/fast_build/system_api/rollup-plugin-system-api'); +const { watchChangeFiles } = require('./lib/fast_build/common/rollup-plugin-watch-change'); +const { initArkConfig } = require('./lib/fast_build/ark_compiler/common/process_ark_config'); +const { genAbc } = require('./lib/fast_build/ark_compiler/rollup-plugin-gen-abc'); + +process.env.watchMode = (process.env.watchMode && process.env.watchMode === 'true') || 'false'; +process.env.compileTool = 'rollup'; + +getEntryObj(); +if (process.env.appResource) { + readAppResource(process.env.appResource); +} +initArkConfig(process.env, projectConfig); + +const external = []; +if (projectConfig.compileMode === 'esmodule' && projectConfig.harNameOhmMap) { + for (const harName in projectConfig.harNameOhmMap) { + external.push(RegExp('^(' + harName + ')($|\/\S+)')); + } +} + +const config = { + input: projectConfig.entryObj, + watch: { + buildDelay: 10 + }, + output: { + dir: path.resolve(__dirname, projectConfig.buildPath), + chunkFileNames: '[name].js', + format: 'cjs', + sourcemap: true + }, + external: external, + plugins: [ + // copyPlugin({targets: setCopyPluginConfig(projectConfig, process.env.appResource)}), + resolve({ + extensions: ['.js', '.ets', '.ts', '.d.ts', '.d.ets'], + modulePaths: [ + path.resolve(projectConfig.projectPath), + path.resolve('node_modules'), + path.resolve(__dirname, 'node_modules'), + path.resolve(__dirname, '../../api'), + projectConfig.aceModuleJsonPath ? + ...getResolveModules(path.resolve(projectConfig.projectPath), false) : + ...getResolveModules(path.resolve(projectConfig.projectPath), true) + ] + }), + commonjs(), + getBabelOutputPlugin({ + plugins: [ + '@babel/plugin-proposal-class-properties' + ], + compact: false + }), + watchChangeFiles(), + etsChecker(), + apiTransform(), + etsTransform(), + genAbc(), + deletePlugin({ + targets: getCleanConfig(workerFile), + runOnce: true + }) + ] +}; + +module.exports = config; diff --git a/compiler/server/build_pipe_server.js b/compiler/server/build_pipe_server.js index 1d13c0a60897f7870783af95942cf87eed113d8c..eb9d7518055cabe89b51a6ca260f2b5a5a5f2aad 100644 --- a/compiler/server/build_pipe_server.js +++ b/compiler/server/build_pipe_server.js @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 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 @@ -17,13 +17,18 @@ const WebSocket = require('ws'); const ts = require('typescript'); const path = require('path'); const fs = require('fs'); -const pipeProcess = require('child_process'); +const { spawn } = require('child_process'); +const _ = require('lodash'); const { processComponentChild } = require('../lib/process_component_build'); const { createWatchCompilerHost } = require('../lib/ets_checker'); const { writeFileSync } = require('../lib/utils'); const { projectConfig } = require('../main'); const { props } = require('../lib/compile_info'); +const { + isResource, + processResourceData +} = require('../lib/process_ui_syntax'); const WebSocketServer = WebSocket.Server; @@ -34,7 +39,7 @@ let supplement = { line: 0, column: 0, fileName: '' -} +}; const pluginCommandChannelMessageHandlers = { 'compileComponent': handlePluginCompileComponent, @@ -48,30 +53,63 @@ let start = false; let checkStatus = false; let compileStatus = false; let receivedMsg_; -let errorInfo; +let errorInfo = []; let compileWithCheck; +let globalVariable = []; +let propertyVariable = []; +let globalDeclaration = new Map(); +let connectNum = 0; +const maxConnectNum = 8; + +let callback = undefined; + +function buildPipeServer() { + return { + init(cachePath, buildPath, cb) { + previewCacheFilePath = path.join(cachePath || buildPath, 'preview.ets'); + const rootFileNames = []; + writeFileSync(previewCacheFilePath, ''); + rootFileNames.push(previewCacheFilePath); + ts.createWatchProgram( + createWatchCompilerHost(rootFileNames, resolveDiagnostic, delayPrintLogCount, ()=>{}, true)); + callback = cb; + }, + compileComponent(jsonData) { + handlePluginCompileComponent(jsonData); + } + } +} function init(port) { previewCacheFilePath = path.join(projectConfig.cachePath || projectConfig.buildPath, 'preview.ets'); const rootFileNames = []; - if (!fs.existsSync(previewCacheFilePath)) { - writeFileSync(previewCacheFilePath, ''); - } + writeFileSync(previewCacheFilePath, ''); rootFileNames.push(previewCacheFilePath); ts.createWatchProgram( - createWatchCompilerHost(rootFileNames, resolveDiagnostic, delayPrintLogCount, true)); - const wss = new WebSocketServer({port: port}); + createWatchCompilerHost(rootFileNames, resolveDiagnostic, delayPrintLogCount, ()=>{}, true)); + const wss = new WebSocketServer({ + port: port, + host: '127.0.0.1' + }); wss.on('connection', function(ws) { - pluginSocket = ws; - handlePluginConnect(ws); + if (connectNum < maxConnectNum) { + connectNum++; + handlePluginConnect(ws); + } else { + ws.terminate(); + } }); } function handlePluginConnect(ws) { ws.on('message', function(message) { - const jsonData = JSON.parse(message); - handlePluginCommand(jsonData); + pluginSocket = ws; + try { + const jsonData = JSON.parse(message); + handlePluginCommand(jsonData); + } catch (e) { + } }); } @@ -87,26 +125,24 @@ function handlePluginCompileComponent(jsonData) { if (receivedMsg_) { return; } - } else if (messages.length > 0){ + } else if (messages.length > 0) { jsonData = messages[0]; } else { - return + return; } start = true; - const receivedMsg = jsonData; + const receivedMsg = _.cloneDeep(jsonData); const compilerOptions = ts.readConfigFile( path.resolve(__dirname, '../tsconfig.json'), ts.sys.readFile).config.compilerOptions; - Object.assign(compilerOptions, { - "sourceMap": false, - }); + Object.assign(compilerOptions, { + 'sourceMap': false + }); const sourceNode = ts.createSourceFile('preview.ets', 'struct preview{build(){' + receivedMsg.data.script + '}}', ts.ScriptTarget.Latest, true, ts.ScriptKind.ETS, compilerOptions); compileWithCheck = jsonData.data.compileWithCheck || 'true'; - if (previewCacheFilePath && fs.existsSync(previewCacheFilePath) - && compileWithCheck === 'true') { - writeFileSync(previewCacheFilePath, 'struct preview{build(){' + receivedMsg.data.script + '}}'); - } + receivedMsg.data.variableScript = ''; + checkPreparation(receivedMsg, sourceNode); const previewStatements = []; const log = []; supplement = { @@ -114,28 +150,70 @@ function handlePluginCompileComponent(jsonData) { line: parseInt(JSON.parse(receivedMsg.data.offset).line), column: parseInt(JSON.parse(receivedMsg.data.offset).column), fileName: receivedMsg.data.filePath || '' - } + }; processComponentChild(sourceNode.statements[0].members[1].body, previewStatements, log, supplement); supplement.isAcceleratePreview = false; const newSource = ts.factory.updateSourceFile(sourceNode, previewStatements); + const transformedSourceFile = transformResourceNode(newSource, log); const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed }); - const result = printer.printNode(ts.EmitHint.Unspecified, newSource, newSource); + const result = printer.printNode(ts.EmitHint.Unspecified, transformedSourceFile, transformedSourceFile); receivedMsg.data.script = ts.transpileModule(result, {}).outputText; - if (receivedMsg.data.offset) { - for (let i = 0; i < log.length; i++) { - let line = parseInt(sourceNode.getLineAndCharacterOfPosition(log[i].pos).line); - let column = parseInt(sourceNode.getLineAndCharacterOfPosition(log[i].pos).character); - if (line === 0) { - log[i].line = parseInt(JSON.parse(receivedMsg.data.offset).line); - log[i].column = parseInt(JSON.parse(receivedMsg.data.offset).column) + column - 15; - } else { - log[i].line = parseInt(JSON.parse(receivedMsg.data.offset).line) + line; - log[i].column = column; + receivedMsg.data.log = log; + if (receivedMsg.data.viewID) { + receivedMsg.data.script = receivedMsg.data.variableScript + `function quickPreview(context) { + const fastPreview = function build(){ + ${receivedMsg.data.script} + }.bind(context); + fastPreview(); + } + quickPreview(GetRootView().findChildByIdForPreview(${receivedMsg.data.viewID}))`; + } + callEs2abc(receivedMsg); +} + +function transformResourceNode(newSource, log) { + const transformerFactory = (context) => { + return (rootNode) => { + function visit(node) { + node = ts.visitEachChild(node, visit, context); + return processResourceNode(node, log); + } + return ts.visitNode(rootNode, visit); + }; + }; + const transformationResult = ts.transform(newSource, [transformerFactory]); + return transformationResult.transformed[0]; +} + +function processResourceNode(node, log) { + if (isResource(node)) { + return processResourceData(node, {isAcceleratePreview: true, log: log}); + } else { + return node; + } +} + +function checkPreparation(receivedMsg, sourceNode) { + let variableScript = ''; + if (previewCacheFilePath && fs.existsSync(previewCacheFilePath) && compileWithCheck === 'true') { + globalVariable = receivedMsg.data.globalVariable || globalVariable; + globalVariable = globalVariable.map((item) => { + globalDeclaration.set(item.identifier, item.declaration); + return item.identifier; + }); + for (const [key, value] of sourceNode.identifiers) { + if (globalVariable.includes(key)) { + variableScript += globalDeclaration.get(key) + '\n'; } } + propertyVariable = receivedMsg.data.propertyVariable || propertyVariable; + receivedMsg.data.variableScript = ts.transpileModule(variableScript, {}).outputText; + writeFileSync(previewCacheFilePath, variableScript + 'struct preview{build(){' + receivedMsg.data.script + '}}'); } - receivedMsg.data.log = log; - if (fs.existsSync(es2abcFilePath + '.exe') || fs.existsSync(es2abcFilePath)){ +} + +function callEs2abc(receivedMsg) { + if (fs.existsSync(es2abcFilePath + '.exe') || fs.existsSync(es2abcFilePath)) { es2abc(receivedMsg); } else { es2abcFilePath = path.join(__dirname, '../bin/ark/build-mac/bin/es2abc'); @@ -145,36 +223,36 @@ function handlePluginCompileComponent(jsonData) { } } - function es2abc(receivedMsg) { - const cmd = es2abcFilePath + ' --base64Input ' + - Buffer.from(receivedMsg.data.script).toString('base64') + ' --base64Output'; try { - pipeProcess.exec(cmd, (error, stdout, stderr) => { - if (stdout) { - receivedMsg.data.script = stdout; - } else { - receivedMsg.data.script = ""; - } + const transCode = spawn(es2abcFilePath, + ['--base64Input', Buffer.from(receivedMsg.data.script).toString('base64'), '--base64Output'], {windowsHide: true}); + transCode.stdout.on('data', (data) => { + receivedMsg.data.script = data.toString(); compileStatus = true; receivedMsg_ = receivedMsg; responseToPlugin(); - }) + }); + transCode.stderr.on('data', (data) => { + receivedMsg.data.script = ''; + compileStatus = true; + receivedMsg_ = receivedMsg; + responseToPlugin(); + }); } catch (e) { } } function resolveDiagnostic(diagnostic) { - errorInfo = []; const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'); if (validateError(message)) { if (diagnostic.file) { const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start); - errorInfo.push( - `ETS:ERROR File: ${diagnostic.file.fileName}:${line + 1}:${character + 1}\n ${message}\n`); + errorInfo.push( + `ArkTS:ERROR File: ${diagnostic.file.fileName}:${line + 1}:${character + 1}\n ${message}\n`); } else { - errorInfo.push(`ETS:ERROR: ${message}`); + errorInfo.push(`ArkTS:ERROR: ${message}`); } } } @@ -187,33 +265,41 @@ function delayPrintLogCount() { } function responseToPlugin() { - if ((compileWithCheck !== "true" && compileStatus == true) || - (compileWithCheck === "true" && compileStatus == true && checkStatus == true) ) { + if ((compileWithCheck !== 'true' && compileStatus == true) || + (compileWithCheck === 'true' && compileStatus == true && checkStatus == true)) { if (receivedMsg_) { - if (errorInfo) { + if (errorInfo && errorInfo.length) { receivedMsg_.data.log = receivedMsg_.data.log || []; receivedMsg_.data.log.push(...errorInfo); } - pluginSocket.send(JSON.stringify(receivedMsg_), (err) => { - start = false; - checkStatus = false; - compileStatus = false; - errorInfo = undefined; - receivedMsg_ = undefined; - messages.shift(); - if (messages.length > 0) { - handlePluginCompileComponent(); - } - }); + if (callback) { + callback(JSON.stringify(receivedMsg_)); + afterResponse(); + } else { + pluginSocket.send(JSON.stringify(receivedMsg_), (err) => { + afterResponse(); + }); + } } } } +function afterResponse() { + start = false; + checkStatus = false; + compileStatus = false; + errorInfo = []; + receivedMsg_ = undefined; + globalDeclaration.clear(); + messages.shift(); + if (messages.length > 0) { + handlePluginCompileComponent(); + } +} + function validateError(message) { - const propInfoReg = /Cannot find name\s*'(\$?\$?[_a-zA-Z0-9]+)'/; const stateInfoReg = /Property\s*'(\$?[_a-zA-Z0-9]+)' does not exist on type/; - if (matchMessage(message, props, propInfoReg) || - matchMessage(message, props, stateInfoReg)) { + if (matchMessage(message, [...propertyVariable, ...props], stateInfoReg)) { return false; } return true; @@ -230,5 +316,6 @@ function matchMessage(message, nameArr, reg) { } module.exports = { - init -}; \ No newline at end of file + init, + buildPipeServer +}; diff --git a/compiler/src/ark_utils.ts b/compiler/src/ark_utils.ts new file mode 100644 index 0000000000000000000000000000000000000000..514fe314edbbd2616116280946185183f4254af0 --- /dev/null +++ b/compiler/src/ark_utils.ts @@ -0,0 +1,397 @@ +/* + * Copyright (c) 2023 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 path from 'path'; +import fs from 'fs'; +import { minify, MinifyOutput } from 'terser'; + +import { OH_MODULES } from './fast_build/ark_compiler/common/ark_define'; +import { + PACKAGES, + TEMPORARY, + ZERO, + ONE, + EXTNAME_JS, + EXTNAME_TS, + EXTNAME_MJS, + EXTNAME_CJS, + EXTNAME_ABC, + EXTNAME_ETS, + EXTNAME_TS_MAP, + EXTNAME_JS_MAP, + ESMODULE, + FAIL, + TS2ABC, + ES2ABC, + EXTNAME_PROTO_BIN, +} from './pre_define'; +import { + isMac, + isWindows, + isPackageModulesFile, + genTemporaryPath, + getExtensionIfUnfullySpecifiedFilepath, + mkdirsSync, + toUnixPath, + validateFilePathLength +} from './utils'; + +const red: string = '\u001b[31m'; +const reset: string = '\u001b[39m'; + +export const SRC_MAIN: string = 'src/main'; + +export var newSourceMaps: Object = {}; +export const packageCollection: Map> = new Map(); + +export function getOhmUrlByFilepath(filePath: string, projectConfig: any, logger: any): string { + let unixFilePath: string = toUnixPath(filePath); + unixFilePath = unixFilePath.substring(0, filePath.lastIndexOf('.')); // remove extension + const REG_PROJECT_SRC: RegExp = /(\S+)\/src\/(?:main|ohosTest)\/(ets|js)\/(\S+)/; + + const packageInfo: string[] = getPackageInfo(projectConfig.aceModuleJsonPath); + const bundleName: string = packageInfo[0]; + const moduleName: string = packageInfo[1]; + const moduleRootPath: string = toUnixPath(projectConfig.modulePathMap[moduleName]); + const projectRootPath: string = toUnixPath(projectConfig.projectRootPath); + // case1: /entry/src/main/ets/xxx/yyy + // case2: /node_modules/xxx/yyy + // case3: /entry/node_modules/xxx/yyy + const projectFilePath: string = unixFilePath.replace(projectRootPath, ''); + const packageDir: string = projectConfig.packageDir; + const result: RegExpMatchArray | null = projectFilePath.match(REG_PROJECT_SRC); + if (result && result[1].indexOf(packageDir) === -1) { + return `${bundleName}/${moduleName}/${result[2]}/${result[3]}`; + } + + if (projectFilePath.indexOf(packageDir) !== -1) { + const tryProjectPkg: string = toUnixPath(path.join(projectRootPath, packageDir)); + if (unixFilePath.indexOf(tryProjectPkg) !== -1) { + return unixFilePath.replace(tryProjectPkg, `${packageDir}/${ONE}`).replace(packageDir, PACKAGES); + } + + const tryModulePkg: string = toUnixPath(path.join(moduleRootPath, packageDir)); + if (unixFilePath.indexOf(tryModulePkg) !== -1) { + return unixFilePath.replace(tryModulePkg, `${packageDir}/${ZERO}`).replace(packageDir, PACKAGES); + } + } + + logger.error(red, `ArkTS:ERROR Failed to get an resolved OhmUrl by filepath "${filePath}"`, reset); + return filePath; +} + +export function genSourceMapFileName(temporaryFile: string): string { + let abcFile: string = temporaryFile; + if (temporaryFile.endsWith(EXTNAME_TS)) { + abcFile = temporaryFile.replace(/\.ts$/, EXTNAME_TS_MAP); + } else { + abcFile = temporaryFile.replace(/\.js$/, EXTNAME_JS_MAP); + } + return abcFile; +} + +export function getBuildModeInLowerCase(projectConfig: any): string { + return (process.env.compileTool === 'rollup' ? projectConfig.buildMode : projectConfig.buildArkMode).toLowerCase(); +} + +export function writeFileSyncByString(sourcePath: string, sourceCode: string, projectConfig: any, logger: any): void { + const filePath: string = genTemporaryPath(sourcePath, projectConfig.projectPath, process.env.cachePath, projectConfig); + if (filePath.length === 0) { + return; + } + mkdirsSync(path.dirname(filePath)); + if (/\.js$/.test(sourcePath)) { + sourceCode = transformModuleSpecifier(sourcePath, sourceCode, projectConfig); + if (projectConfig.buildArkMode === 'debug') { + fs.writeFileSync(filePath, sourceCode); + return; + } + writeMinimizedSourceCode(sourceCode, filePath, logger); + } + if (/\.json$/.test(sourcePath)) { + fs.writeFileSync(filePath, sourceCode); + } +} + +export function transformModuleSpecifier(sourcePath: string, sourceCode: string, projectConfig: any): string { + // replace relative moduleSpecifier with ohmURl + const REG_RELATIVE_DEPENDENCY: RegExp = /(?:import|from)(?:\s*)['"]((?:\.\/|\.\.\/)[^'"]+|(?:\.\/?|\.\.\/?))['"]/g; + const REG_HAR_DEPENDENCY: RegExp = /(?:import|from)(?:\s*)['"]([^\.\/][^'"]+)['"]/g; + // replace requireNapi and requireNativeModule with import + const REG_REQUIRE_NATIVE_MODULE: RegExp = /var (\S+) = globalThis.requireNativeModule\(['"](\S+)['"]\);/g; + const REG_REQUIRE_NAPI_APP: RegExp = /var (\S+) = globalThis.requireNapi\(['"](\S+)['"], true, ['"](\S+)['"]\);/g; + const REG_REQUIRE_NAPI_OHOS: RegExp = /var (\S+) = globalThis.requireNapi\(['"](\S+)['"]\);/g; + + return sourceCode.replace(REG_HAR_DEPENDENCY, (item, moduleRequest) => { + return replaceHarDependency(item, moduleRequest, projectConfig); + }).replace(REG_RELATIVE_DEPENDENCY, (item, moduleRequest) => { + return replaceRelativeDependency(item, moduleRequest, toUnixPath(sourcePath), projectConfig); + }).replace(REG_REQUIRE_NATIVE_MODULE, (_, moduleRequest, moduleName) => { + return `import ${moduleRequest} from '@native:${moduleName}';`; + }).replace(REG_REQUIRE_NAPI_APP, (_, moduleRequest, soName, moudlePath) => { + return `import ${moduleRequest} from '@app:${moudlePath}/${soName}';`; + }).replace(REG_REQUIRE_NAPI_OHOS, (_, moduleRequest, moduleName) => { + return `import ${moduleRequest} from '@ohos:${moduleName}';`; + }); +} + +export function getOhmUrlByHarName(moduleRequest: string, projectConfig: any): string | undefined { + if (projectConfig.harNameOhmMap) { + // case1: "@ohos/lib" ---> "@bundle:bundleName/lib/ets/index" + if (projectConfig.harNameOhmMap.hasOwnProperty(moduleRequest)) { + return projectConfig.harNameOhmMap[moduleRequest]; + } + // case2: "@ohos/lib/src/main/ets/pages/page1" ---> "@bundle:bundleName/lib/ets/pages/page1" + for (const harName in projectConfig.harNameOhmMap) { + if (moduleRequest.startsWith(harName + '/')) { + const idx: number = projectConfig.harNameOhmMap[harName].split('/', 2).join('/').length; + const harOhmName: string = projectConfig.harNameOhmMap[harName].substring(0, idx); + if (moduleRequest.indexOf(harName + '/' + SRC_MAIN) === 0) { + return moduleRequest.replace(harName + '/' + SRC_MAIN, harOhmName); + } else { + return moduleRequest.replace(harName, harOhmName); + } + } + } + } + return undefined; +} + +function replaceHarDependency(item:string, moduleRequest: string, projectConfig: any): string { + const harOhmUrl: string | undefined = getOhmUrlByHarName(moduleRequest, projectConfig); + if (harOhmUrl !== undefined) { + return item.replace(/(['"])(?:\S+)['"]/, (_, quotation) => { + return quotation + harOhmUrl + quotation; + }); + } + return item; +} + +function locateActualFilePathWithModuleRequest(absolutePath: string): string { + if (!fs.existsSync(absolutePath) || !fs.statSync(absolutePath).isDirectory()) { + return absolutePath + } + + const filePath: string = absolutePath + getExtensionIfUnfullySpecifiedFilepath(absolutePath); + if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) { + return absolutePath; + } + + return path.join(absolutePath, 'index'); +} + +function replaceRelativeDependency(item:string, moduleRequest: string, sourcePath: string, projectConfig: any): string { + if (sourcePath && projectConfig.compileMode === ESMODULE) { + // remove file extension from moduleRequest + const SUFFIX_REG: RegExp = /\.(?:[cm]?js|[e]?ts|json)$/; + moduleRequest = moduleRequest.replace(SUFFIX_REG, ''); + + // normalize the moduleRequest + item = item.replace(/(['"])(?:\S+)['"]/, (_, quotation) => { + let normalizedModuleRequest: string = toUnixPath(path.normalize(moduleRequest)); + if (moduleRequest.startsWith("./")) { + normalizedModuleRequest = "./" + normalizedModuleRequest; + } + return quotation + normalizedModuleRequest + quotation; + }); + + const filePath: string = + locateActualFilePathWithModuleRequest(path.resolve(path.dirname(sourcePath), moduleRequest)); + const result: RegExpMatchArray | null = + filePath.match(/(\S+)(\/|\\)src(\/|\\)(?:main|ohosTest)(\/|\\)(ets|js)(\/|\\)(\S+)/); + if (result && projectConfig.aceModuleJsonPath) { + const npmModuleIdx: number = result[1].search(/(\/|\\)node_modules(\/|\\)/); + const projectRootPath: string = projectConfig.projectRootPath; + if (npmModuleIdx === -1 || npmModuleIdx === projectRootPath.search(/(\/|\\)node_modules(\/|\\)/)) { + const packageInfo: string[] = getPackageInfo(projectConfig.aceModuleJsonPath); + const bundleName: string = packageInfo[0]; + const moduleName: string = packageInfo[1]; + moduleRequest = `@bundle:${bundleName}/${moduleName}/${result[5]}/${toUnixPath(result[7])}`; + item = item.replace(/(['"])(?:\S+)['"]/, (_, quotation) => { + return quotation + moduleRequest + quotation; + }); + } + } + } + return item; +} + +export async function writeMinimizedSourceCode(content: string, filePath: string, logger: any): Promise { + let result: MinifyOutput; + try { + result = await minify(content, { + compress: { + join_vars: false, + sequences: 0 + }, + format: { + semicolons: false, + beautify: true, + indent_level: 2 + } + }); + } catch { + logger.error(red, `ArkTS:ERROR Failed to source code obfuscation.`, reset); + process.exit(FAIL); + } + fs.writeFileSync(filePath, result.code); +} + +export function genBuildPath(filePath: string, projectPath: string, buildPath: string, projectConfig: any): string { + filePath = toUnixPath(filePath); + if (filePath.endsWith(EXTNAME_MJS)) { + filePath = filePath.replace(/\.mjs$/, EXTNAME_JS); + } + if (filePath.endsWith(EXTNAME_CJS)) { + filePath = filePath.replace(/\.cjs$/, EXTNAME_JS); + } + projectPath = toUnixPath(projectPath); + + if (isPackageModulesFile(filePath, projectConfig)) { + const packageDir: string = projectConfig.packageDir; + const fakePkgModulesPath: string = toUnixPath(path.join(projectConfig.projectRootPath, packageDir)); + let output: string = ''; + if (filePath.indexOf(fakePkgModulesPath) === -1) { + const hapPath: string = toUnixPath(projectConfig.projectRootPath); + const tempFilePath: string = filePath.replace(hapPath, ''); + const sufStr: string = tempFilePath.substring(tempFilePath.indexOf(packageDir) + packageDir.length + 1); + output = path.join(projectConfig.nodeModulesPath, ZERO, sufStr); + } else { + output = filePath.replace(fakePkgModulesPath, path.join(projectConfig.nodeModulesPath, ONE)); + } + return output; + } + + if (filePath.indexOf(projectPath) !== -1) { + const sufStr: string = filePath.replace(projectPath, ''); + const output: string = path.join(buildPath, sufStr); + return output; + } + + return ''; +} + +export function getPackageInfo(configFile: string): Array { + if (packageCollection.has(configFile)) { + return packageCollection.get(configFile); + } + const data: any = JSON.parse(fs.readFileSync(configFile).toString()); + const bundleName: string = data.app.bundleName; + const moduleName: string = data.module.name; + packageCollection.set(configFile, [bundleName, moduleName]); + return [bundleName, moduleName]; +} + +export function generateSourceFilesToTemporary(sourcePath: string, sourceContent: string, sourceMap: any, + projectConfig: any, logger: any): void { + let jsFilePath: string = genTemporaryPath(sourcePath, projectConfig.projectPath, process.env.cachePath, projectConfig); + if (jsFilePath.length === 0) { + return; + } + if (jsFilePath.endsWith(EXTNAME_ETS)) { + jsFilePath = jsFilePath.replace(/\.ets$/, EXTNAME_JS); + } else { + jsFilePath = jsFilePath.replace(/\.ts$/, EXTNAME_JS); + } + let sourceMapFile: string = genSourceMapFileName(jsFilePath); + if (sourceMapFile.length > 0 && projectConfig.buildArkMode === 'debug') { + let source = toUnixPath(sourcePath).replace(toUnixPath(projectConfig.projectRootPath) + '/', ''); + // adjust sourceMap info + sourceMap.sources = [source]; + sourceMap.file = path.basename(sourceMap.file); + delete sourceMap.sourcesContent; + newSourceMaps[source] = sourceMap; + } + sourceContent = transformModuleSpecifier(sourcePath, sourceContent, projectConfig); + + mkdirsSync(path.dirname(jsFilePath)); + if (projectConfig.buildArkMode === 'debug') { + fs.writeFileSync(jsFilePath, sourceContent); + return; + } + + writeMinimizedSourceCode(sourceContent, jsFilePath, logger); +} + +export function genAbcFileName(temporaryFile: string): string { + let abcFile: string = temporaryFile; + if (temporaryFile.endsWith(EXTNAME_TS)) { + abcFile = temporaryFile.replace(/\.ts$/, EXTNAME_ABC); + } else { + abcFile = temporaryFile.replace(/\.js$/, EXTNAME_ABC); + } + return abcFile; +} + +export function isOhModules(projectConfig: any): boolean { + return projectConfig.packageDir === OH_MODULES; +} + +export function isEs2Abc(projectConfig: any): boolean { + return projectConfig.pandaMode === ES2ABC || projectConfig.pandaMode === "undefined" || + projectConfig.pandaMode === undefined; +} + +export function isTs2Abc(projectConfig: any): boolean { + return projectConfig.pandaMode === TS2ABC; +} + +export function genProtoFileName(temporaryFile: string): string { + return temporaryFile.replace(/\.(?:[tj]s|json)$/, EXTNAME_PROTO_BIN); +} + +export function genMergeProtoFileName(temporaryFile: string): string { + let protoTempPathArr: string[] = temporaryFile.split(TEMPORARY); + const sufStr: string = protoTempPathArr[protoTempPathArr.length - 1]; + let protoBuildPath: string = path.join(process.env.cachePath, "protos", sufStr); + + return protoBuildPath; +} + +export function removeDuplicateInfo(moduleInfos: Array): Array { + const tempModuleInfos: any[] = Array(); + moduleInfos.forEach((item) => { + let check: boolean = tempModuleInfos.every((newItem) => { + return item.tempFilePath !== newItem.tempFilePath; + }); + if (check) { + tempModuleInfos.push(item); + } + }); + moduleInfos = tempModuleInfos; + + return moduleInfos; +} + +export function buildCachePath(tailName: string, projectConfig: any, logger: any): string { + let pathName: string = process.env.cachePath !== undefined ? + path.join(projectConfig.cachePath, tailName) : path.join(projectConfig.aceModuleBuild, tailName); + validateFilePathLength(pathName, logger); + return pathName; +} + +export function getArkBuildDir(arkDir: string): string { + if (isWindows()) { + return path.join(arkDir, 'build-win'); + } else if (isMac()) { + return path.join(arkDir, 'build-mac'); + } else { + return path.join(arkDir, 'build'); + } +} + +export function getBuildBinDir(arkDir: string): string { + return path.join(getArkBuildDir(arkDir), 'bin'); +} diff --git a/compiler/src/compile_info.ts b/compiler/src/compile_info.ts index 8915de307603959cd69ba49840c4de98f1b20dad..088c1576f3c7122401e62b86a35f1bf78da848f9 100644 --- a/compiler/src/compile_info.ts +++ b/compiler/src/compile_info.ts @@ -34,18 +34,27 @@ import { } from './validate_ui_syntax'; import { circularFile, - mkDir, - writeFileSync + writeUseOSFiles, + writeFileSync, + parseErrorMessage, + genTemporaryPath, + shouldWriteChangedList, + getHotReloadFiles } from './utils'; import { MODULE_ETS_PATH, MODULE_SHARE_PATH, BUILD_SHARE_PATH, - ESMODULE + EXTNAME_JS, + EXTNAME_JS_MAP } from './pre_define'; import { - createLanguageService, - createWatchCompilerHost + serviceChecker, + createWatchCompilerHost, + hotReloadSupportFiles, + printDiagnostic, + checkerResult, + incrementWatchFile } from './ets_checker'; import { globalProgram, @@ -60,6 +69,7 @@ configure({ export const logger = getLogger('ETS'); export const props: string[] = []; +const checkErrorMessage: Set = new Set([]); interface Info { message?: string; @@ -77,17 +87,15 @@ export interface CacheFileName { error: boolean } -interface NeedUpdateFlag { - flag: boolean; +interface hotReloadIncrementalTime { + hotReloadIncrementalStartTime: string; + hotReloadIncrementalEndTime: string; } -export let cache: Cache = {}; -export const shouldResolvedFiles: Set = new Set() -type Cache = Record; - export class ResultStates { private mStats: Stats; private mErrorCount: number = 0; + private mPreErrorCount: number = 0; private mWarningCount: number = 0; private warningCount: number = 0; private noteCount: number = 0; @@ -96,9 +104,26 @@ export class ResultStates { private blue: string = '\u001b[34m'; private reset: string = '\u001b[39m'; private moduleSharePaths: Set = new Set([]); + private removedFiles: string[] = []; + private hotReloadIncrementalTime: hotReloadIncrementalTime = { + hotReloadIncrementalStartTime: '', + hotReloadIncrementalEndTime: '' + } + private incrementalFileInHar: Map = new Map(); public apply(compiler: Compiler): void { compiler.hooks.compilation.tap('SourcemapFixer', compilation => { + compilation.hooks.processAssets.tap('RemoveHar', (assets) => { + if (!projectConfig.compileHar) { + return; + } + Object.keys(compilation.assets).forEach(key => { + if (path.extname(key) === EXTNAME_JS || path.extname(key) === EXTNAME_JS_MAP) { + delete assets[key]; + } + }); + }); + compilation.hooks.afterProcessAssets.tap('SourcemapFixer', assets => { Reflect.ownKeys(assets).forEach(key => { if (/\.map$/.test(key.toString()) && assets[key]._value) { @@ -111,7 +136,7 @@ export class ResultStates { if (map && map.size != 0) { let names: Array = Array.from(map).flat(); let sourcemapObj: any = JSON.parse(assets[key]._value); - sourcemapObj.names = names; + sourcemapObj.nameMap = names; assets[key]._value = JSON.stringify(sourcemapObj); } } @@ -120,6 +145,21 @@ export class ResultStates { } ); + compilation.hooks.succeedModule.tap('findModule', (module) => { + if (module && module.error) { + const errorLog: string = module.error.toString(); + if (module.resourceResolveData && module.resourceResolveData.path && + /Module parse failed/.test(errorLog) && /Invalid regular expression:/.test(errorLog)) { + this.mErrorCount++; + const errorInfos: string[] = errorLog.split('\n>')[1].split(';'); + if (errorInfos && errorInfos.length > 0 && errorInfos[0]) { + const errorInformation: string = `ERROR in ${module.resourceResolveData.path}\n The following syntax is incorrect.\n > ${errorInfos[0]}`; + this.printErrorMessage(parseErrorMessage(errorInformation), false, module.error); + } + } + } + }); + compilation.hooks.buildModule.tap('findModule', (module) => { if (module.context) { if (module.context.indexOf(projectConfig.projectPath) >= 0) { @@ -136,6 +176,8 @@ export class ResultStates { } } }); + + compilation.hooks.finishModules.tap('finishModules', handleFinishModules.bind(this)); }); compiler.hooks.afterCompile.tap('copyFindModule', () => { @@ -200,79 +242,53 @@ export class ResultStates { }); if (process.env.watchMode === 'true') { globalProgram.watchProgram = ts.createWatchProgram( - createWatchCompilerHost(rootFileNames, this.printDiagnostic.bind(this), - this.delayPrintLogCount.bind(this))); + createWatchCompilerHost(rootFileNames, printDiagnostic, + this.delayPrintLogCount.bind(this), this.resetTsErrorCount)); } else { - let languageService: ts.LanguageService = null; - let cacheFile: string = null; - if (projectConfig.xtsMode) { - languageService = createLanguageService(rootFileNames); - } else { - cacheFile = path.resolve(projectConfig.cachePath, '../.ts_checker_cache'); - cache = fs.existsSync(cacheFile) ? JSON.parse(fs.readFileSync(cacheFile).toString()) : {}; - const filterFiles: string[] = filterInput(rootFileNames); - languageService = createLanguageService(filterFiles); - } - globalProgram.program = languageService.getProgram(); - const allDiagnostics: ts.Diagnostic[] = globalProgram.program - .getSyntacticDiagnostics() - .concat(globalProgram.program.getSemanticDiagnostics()) - .concat(globalProgram.program.getDeclarationDiagnostics()); - allDiagnostics.forEach((diagnostic: ts.Diagnostic) => { - this.printDiagnostic(diagnostic); - }); - if (process.env.watchMode !== 'true' && !projectConfig.xtsMode) { - fs.writeFileSync(cacheFile, JSON.stringify(cache, null, 2)); - } + serviceChecker(rootFileNames); } }); compiler.hooks.watchRun.tap('WatchRun', (comp) => { + process.env.watchEts = 'start'; + checkErrorMessage.clear(); + this.clearCount(); comp.modifiedFiles = comp.modifiedFiles || []; comp.removedFiles = comp.removedFiles || []; const watchModifiedFiles: string[] = [...comp.modifiedFiles]; - const watchRemovedFiles: string[] = [...comp.removedFiles]; + let watchRemovedFiles: string[] = [...comp.removedFiles]; + if (watchRemovedFiles.length) { + this.removedFiles = watchRemovedFiles; + } if (watchModifiedFiles.length) { - const isTsAndEtsFile: boolean = watchModifiedFiles.some((item: string) => { - return /.(ts|ets)$/.test(item); + watchModifiedFiles.some((item: string) => { + if (fs.statSync(item).isFile() && !/.(ts|ets)$/.test(item)) { + process.env.watchTs = 'end'; + return true; + } }); - if (!isTsAndEtsFile) { - process.env.watchTs = 'end'; - } } - if (this.shouldWriteChangedList(watchModifiedFiles, watchRemovedFiles)) { - interface filesObj { - modifiedFiles: string[], - removedFiles: string[] - } - const filesObj: filesObj = { - modifiedFiles: watchModifiedFiles.filter((file) => { - return fs.statSync(file).isFile(); - }), - removedFiles: watchRemovedFiles - }; - writeFileSync(projectConfig.outChangedFileList, JSON.stringify(filesObj)); + if (shouldWriteChangedList(watchModifiedFiles, watchRemovedFiles)) { + writeFileSync(projectConfig.changedFileList, JSON.stringify( + getHotReloadFiles(watchModifiedFiles, watchRemovedFiles, hotReloadSupportFiles))); } - const changedFiles: string[] = [...watchModifiedFiles, ...watchRemovedFiles]; - if (changedFiles.length) { - shouldResolvedFiles.clear(); - } - changedFiles.forEach((file) => { - this.judgeFileShouldResolved(file, shouldResolvedFiles) - }) - }) + incrementWatchFile(watchModifiedFiles, watchRemovedFiles); + }); compiler.hooks.done.tap('Result States', (stats: Stats) => { if (projectConfig.isPreview && projectConfig.aceSoPath && useOSFiles && useOSFiles.size > 0) { - this.writeUseOSFiles(); + writeUseOSFiles(useOSFiles); + } + if (projectConfig.compileHar) { + this.incrementalFileInHar.forEach((jsBuildFilePath, jsCacheFilePath) => { + const sourceCode: string = fs.readFileSync(jsCacheFilePath, 'utf-8'); + writeFileSync(jsBuildFilePath, sourceCode); + }); } this.mStats = stats; this.warningCount = 0; this.noteCount = 0; - if (this.mStats.compilation.errors) { - this.mErrorCount += this.mStats.compilation.errors.length; - } if (this.mStats.compilation.warnings) { this.mWarningCount = this.mStats.compilation.warnings.length; } @@ -280,60 +296,8 @@ export class ResultStates { }); } - private shouldWriteChangedList(watchModifiedFiles: string[], watchRemovedFiles: string[]): boolean { - return projectConfig.compileMode === ESMODULE && process.env.watchMode === 'true' && !projectConfig.isPreview && - projectConfig.outChangedFileList && (watchRemovedFiles.length + watchModifiedFiles.length) && - !(watchModifiedFiles.length === 1 && watchModifiedFiles[0] == projectConfig.projectPath); - } - - private judgeFileShouldResolved(file: string, shouldResolvedFiles: Set): void { - if (shouldResolvedFiles.has(file)) { - return; - } - shouldResolvedFiles.add(file); - if (cache && cache[file] && cache[file].parent) { - cache[file].parent.forEach((item)=>{ - this.judgeFileShouldResolved(item, shouldResolvedFiles); - }) - cache[file].parent = []; - } - if (cache && cache[file] && cache[file].children) { - cache[file].children.forEach((item)=>{ - this.judgeFileShouldResolved(item, shouldResolvedFiles); - }) - cache[file].children = []; - } - } - - private printDiagnostic(diagnostic: ts.Diagnostic): void { - const message: string = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'); - if (this.validateError(message)) { - if (process.env.watchMode !== 'true' && !projectConfig.xtsMode) { - updateErrorFileCache(diagnostic); - } - this.mErrorCount += 1; - if (diagnostic.file) { - const { line, character }: ts.LineAndCharacter = - diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start!); - logger.error(this.red, - `ETS:ERROR File: ${diagnostic.file.fileName}:${line + 1}:${character + 1}\n ${message}\n`); - } else { - logger.error(this.red, `ETS:ERROR: ${message}`); - } - } - } - - private writeUseOSFiles(): void { - let info: string = ''; - if (!fs.existsSync(projectConfig.aceSoPath)) { - const parent: string = path.join(projectConfig.aceSoPath, '..'); - if (!(fs.existsSync(parent) && !fs.statSync(parent).isFile())) { - mkDir(parent); - } - } else { - info = fs.readFileSync(projectConfig.aceSoPath, 'utf-8') + '\n'; - } - fs.writeFileSync(projectConfig.aceSoPath, info + Array.from(useOSFiles).join('\n')); + private resetTsErrorCount(): void { + checkerResult.count = 0; } private printResult(): void { @@ -341,31 +305,38 @@ export class ResultStates { this.printError(); if (process.env.watchMode === 'true') { process.env.watchEts = 'end'; - this.delayPrintLogCount(); + this.delayPrintLogCount(true); } else { this.printLogCount(); } } - private delayPrintLogCount() { + private delayPrintLogCount(isCompile: boolean = false) { if (process.env.watchEts === 'end' && process.env.watchTs === 'end') { this.printLogCount(); - process.env.watchEts = 'start'; process.env.watchTs = 'start'; + this.removedFiles = []; + } else if (isCompile && this.removedFiles.length && this.mErrorCount === 0 && this.mPreErrorCount > 0) { + this.printLogCount(); } + this.mPreErrorCount = this.mErrorCount; } private printLogCount(): void { - if (this.mErrorCount + this.warningCount + this.noteCount > 0) { + let errorCount: number = this.mErrorCount + checkerResult.count; + if (errorCount + this.warningCount + this.noteCount > 0 || process.env.abcCompileSuccess === 'false') { let result: string; let resultInfo: string = ''; - if (this.mErrorCount > 0) { - resultInfo += `ERROR:${this.mErrorCount}`; + if (errorCount > 0) { + resultInfo += `ERROR:${errorCount}`; result = 'FAIL '; process.exitCode = 1; } else { result = 'SUCCESS '; } + if (process.env.abcCompileSuccess === 'false') { + result = 'FAIL '; + } if (this.warningCount > 0) { resultInfo += ` WARN:${this.warningCount}`; } @@ -384,26 +355,30 @@ export class ResultStates { console.info(this.blue, 'COMPILE RESULT:SUCCESS ', this.reset); } } - this.clearCount(); } private clearCount(): void { this.mErrorCount = 0; this.warningCount = 0; this.noteCount = 0; + process.env.abcCompileSuccess = 'true'; } private printPreviewResult(resultInfo: string = ''): void { const workerNum: number = Object.keys(cluster.workers).length; - const printSuccessInfo = this.printSuccessInfo; const blue: string = this.blue; const reset: string = this.reset; if (workerNum === 0) { - printSuccessInfo(blue, reset, resultInfo); + this.printSuccessInfo(blue, reset, resultInfo); } } private printSuccessInfo(blue: string, reset: string, resultInfo: string): void { + if (projectConfig.hotReload) { + this.hotReloadIncrementalTime.hotReloadIncrementalEndTime = new Date().getTime().toString(); + console.info(blue, 'Incremental build start: ' + this.hotReloadIncrementalTime.hotReloadIncrementalStartTime + +'\n' + 'Incremental build end: ' + this.hotReloadIncrementalTime.hotReloadIncrementalEndTime, reset); + } if (resultInfo.length === 0) { console.info(blue, 'COMPILE RESULT:SUCCESS ', reset); } else { @@ -419,11 +394,17 @@ export class ResultStates { const message: string = warnings[index].message.replace(/^Module Warning\s*.*:\n/, '') .replace(/\(Emitted value instead of an instance of Error\) BUILD/, ''); if (/^NOTE/.test(message)) { - this.noteCount++; - logger.info(this.blue, message, this.reset, '\n'); + if (!checkErrorMessage.has(message)) { + this.noteCount++; + logger.info(this.blue, message.replace(/^NOTE/, 'ArkTS:NOTE'), this.reset, '\n'); + checkErrorMessage.add(message); + } } else { - this.warningCount++; - logger.warn(this.yellow, message.replace(/^WARN/, 'ETS:WARN'), this.reset, '\n'); + if (!checkErrorMessage.has(message)) { + this.warningCount++; + logger.warn(this.yellow, message.replace(/^WARN/, 'ArkTS:WARN'), this.reset, '\n'); + checkErrorMessage.add(message); + } } } if (this.mWarningCount > length) { @@ -433,64 +414,50 @@ export class ResultStates { } private printError(): void { - if (this.mErrorCount > 0) { + if (this.mStats.compilation.errors.length > 0) { const errors: Info[] = [...this.mStats.compilation.errors]; for (let index = 0; index < errors.length; index++) { if (errors[index].issue) { - const position: string = errors[index].issue.location - ? `:${errors[index].issue.location.start.line}:${errors[index].issue.location.start.column}` - : ''; - const location: string = errors[index].issue.file.replace(/\\/g, '/') + position; - const detail: string = errors[index].issue.message; - logger.error(this.red, 'ETS:ERROR File: ' + location, this.reset); - logger.error(this.red, detail, this.reset, '\n'); + if (!checkErrorMessage.has(errors[index].issue)) { + this.mErrorCount++; + const position: string = errors[index].issue.location + ? `:${errors[index].issue.location.start.line}:${errors[index].issue.location.start.column}` + : ''; + const location: string = errors[index].issue.file.replace(/\\/g, '/') + position; + const detail: string = errors[index].issue.message; + logger.error(this.red, 'ArkTS:ERROR File: ' + location, this.reset); + logger.error(this.red, detail, this.reset, '\n'); + checkErrorMessage.add(errors[index].issue); + } } else if (/BUILDERROR/.test(errors[index].message)) { - const errorMessage: string = errors[index].message.replace(/^Module Error\s*.*:\n/, '') - .replace(/\(Emitted value instead of an instance of Error\) BUILD/, '') - .replace(/^ERROR/, 'ETS:ERROR'); - this.printErrorMessage(errorMessage, true, errors[index]); - } else if (!/TS[0-9]+:/.test(errors[index].message.toString())) { + if (!checkErrorMessage.has(errors[index].message)) { + this.mErrorCount++; + const errorMessage: string = errors[index].message.replace(/^Module Error\s*.*:\n/, '') + .replace(/\(Emitted value instead of an instance of Error\) BUILD/, '') + .replace(/^ERROR/, 'ArkTS:ERROR'); + this.printErrorMessage(errorMessage, true, errors[index]); + checkErrorMessage.add(errors[index].message); + } + } else if (!/TS[0-9]+:/.test(errors[index].message.toString()) && + !/Module parse failed/.test(errors[index].message.toString())) { + this.mErrorCount++; let errorMessage: string = `${errors[index].message.replace(/\[tsl\]\s*/, '') .replace(/\u001b\[.*?m/g, '').replace(/\.ets\.ts/g, '.ets').trim()}\n`; errorMessage = this.filterModuleError(errorMessage) - .replace(/^ERROR in /, 'ETS:ERROR File: ').replace(/\s{6}TS/g, ' TS') + .replace(/^ERROR in /, 'ArkTS:ERROR File: ').replace(/\s{6}TS/g, ' TS') .replace(/\(([0-9]+),([0-9]+)\)/, ':$1:$2'); - this.printErrorMessage(errorMessage, false, errors[index]); + this.printErrorMessage(parseErrorMessage(errorMessage), false, errors[index]); } } } } private printErrorMessage(errorMessage: string, lineFeed: boolean, errorInfo: Info): void { - if (this.validateError(errorMessage)) { - const formatErrMsg = errorMessage.replace(/\\/g, '/'); - if (lineFeed) { - logger.error(this.red, formatErrMsg + '\n', this.reset); - } else { - logger.error(this.red, formatErrMsg, this.reset); - } + const formatErrMsg = errorMessage.replace(/\\/g, '/'); + if (lineFeed) { + logger.error(this.red, formatErrMsg + '\n', this.reset); } else { - const errorsIndex = this.mStats.compilation.errors.indexOf(errorInfo); - this.mStats.compilation.errors.splice(errorsIndex, 1); - this.mErrorCount = this.mErrorCount - 1; - } - } - private validateError(message: string): boolean { - const propInfoReg: RegExp = /Cannot find name\s*'(\$?\$?[_a-zA-Z0-9]+)'/; - const stateInfoReg: RegExp = /Property\s*'(\$?[_a-zA-Z0-9]+)' does not exist on type/; - if (this.matchMessage(message, props, propInfoReg) || - this.matchMessage(message, props, stateInfoReg)) { - return false; + logger.error(this.red, formatErrMsg, this.reset); } - return true; - } - private matchMessage(message: string, nameArr: any, reg: RegExp): boolean { - if (reg.test(message)) { - const match: string[] = message.match(reg); - if (match[1] && nameArr.includes(match[1])) { - return true; - } - } - return false; } private filterModuleError(message: string): string { if (/You may need an additional loader/.test(message) && transformLog && transformLog.sourceFile) { @@ -504,44 +471,25 @@ export class ResultStates { } } -function updateErrorFileCache(diagnostic: ts.Diagnostic): void { - if (diagnostic.file && cache[path.resolve(diagnostic.file.fileName)]) { - cache[path.resolve(diagnostic.file.fileName)].error = true; - } -} - -function filterInput(rootFileNames: string[]): string[] { - return rootFileNames.filter((file: string) => { - const needUpdate: NeedUpdateFlag = { flag: false }; - const alreadyCheckedFiles: Set = new Set(); - checkNeedUpdateFiles(path.resolve(file), needUpdate, alreadyCheckedFiles); - return needUpdate.flag; - }); -} - -function checkNeedUpdateFiles(file: string, needUpdate: NeedUpdateFlag, alreadyCheckedFiles: Set): void { - if (alreadyCheckedFiles.has(file)) { - return; - } else { - alreadyCheckedFiles.add(file); - } - - if (needUpdate.flag) { - return; - } - - const value: CacheFileName = cache[file]; - const mtimeMs: number = fs.statSync(file).mtimeMs; - if (value) { - if (value.error || value.mtimeMs !== mtimeMs) { - needUpdate.flag = true; - return; - } - for (let i = 0; i < value.children.length; ++i) { - checkNeedUpdateFiles(value.children[i], needUpdate, alreadyCheckedFiles); - } - } else { - cache[file] = { mtimeMs, children: [], parent: [], error: false }; - needUpdate.flag = true; +function handleFinishModules(modules, callback) { + if (projectConfig.compileHar) { + modules.forEach(module => { + if (module !== undefined && module.resourceResolveData !== undefined) { + const filePath: string = module.resourceResolveData.path; + if (!filePath.match(/node_modules/)) { + const jsCacheFilePath: string = genTemporaryPath(filePath, projectConfig.moduleRootPath, process.env.cachePath, + projectConfig); + const jsBuildFilePath: string = genTemporaryPath(filePath, projectConfig.moduleRootPath, + projectConfig.buildPath, projectConfig, true); + if (filePath.match(/\.e?ts$/)) { + this.incrementalFileInHar.set(jsCacheFilePath.replace(/\.ets$/, '.d.ets').replace(/\.ts$/, '.d.ts'), + jsBuildFilePath.replace(/\.ets$/, '.d.ets').replace(/\.ts$/, '.d.ts')); + this.incrementalFileInHar.set(jsCacheFilePath.replace(/\.e?ts$/, '.js'), jsBuildFilePath.replace(/\.e?ts$/, '.js')); + } else { + this.incrementalFileInHar.set(jsCacheFilePath, jsBuildFilePath); + } + } + } + }); } } diff --git a/compiler/src/component_map.ts b/compiler/src/component_map.ts index a7a0f5bf9901ab8fb90091492f797feae0b82846..0397fa7e880c31f376094acbb2ad51fe6b354e0f 100644 --- a/compiler/src/component_map.ts +++ b/compiler/src/component_map.ts @@ -17,27 +17,42 @@ const fs = require('fs'); const path = require('path'); import ts from 'typescript'; +const COMPONENTS = 'components'; +const FORM_COMPONENTS = 'form_components'; export const COMPONENT_MAP: any = {}; +export const FORM_MAP: any = {}; export let COMMON_ATTRS: Set = new Set([]); (function readComponents() { - const componentsFile: string = path.join(__dirname, '../components'); - const files: string[] = fs.readdirSync(componentsFile); - files.forEach(function(item) { - const fPath: string = path.join(componentsFile, item); - const json: any = require(fPath); - const stat: any = fs.statSync(fPath); - if (stat.isFile()) { - if (json.name) { - const compName: string = json.name; - delete json.name; - COMPONENT_MAP[compName] = json; - } else { - COMMON_ATTRS = new Set(json.attrs); + const componentPath: Map = new Map([ + [`${COMPONENTS}`, `../${COMPONENTS}`], + [`${FORM_COMPONENTS}`, `../${FORM_COMPONENTS}`] + ]); + for (const [id, relPath] of componentPath.entries()) { + const componentsFile: string = path.join(__dirname, relPath); + const files: string[] = fs.readdirSync(componentsFile); + files.forEach(function (item) { + const fPath: string = path.join(componentsFile, item); + const json: any = require(fPath); + const stat: any = fs.statSync(fPath); + if (stat.isFile()) { + if (json.name) { + const compName: string = json.name; + delete json.name; + if (id === COMPONENTS) { + COMPONENT_MAP[compName] = json; + } else if (id === FORM_COMPONENTS) { + FORM_MAP[compName] = json; + } + } else { + if (id === COMPONENTS) { + COMMON_ATTRS = new Set(json.attrs); + } + } } - } - }); + }); + } })(); const TRANSITION_COMMON_ATTRS: Set = new Set([ @@ -53,7 +68,8 @@ export const forbiddenUseStateType: Set = new Set(['Scroller', 'SwiperSc 'VideoController', 'WebController', 'CustomDialogController', 'SwiperController', 'TabsController', 'CalendarController', 'AbilityController', 'XComponentController', 'CanvasRenderingContext2D', 'CanvasGradient', 'ImageBitmap', 'ImageData', 'Path2D', - 'RenderingContextSettings', 'OffscreenCanvasRenderingContext2D', 'PatternLockController' + 'RenderingContextSettings', 'OffscreenCanvasRenderingContext2D', 'PatternLockController', + 'TextAreaController', 'TextInputController', 'TextTimerController', 'SearchController' ]); export const INNER_COMPONENT_NAMES: Set = new Set(); @@ -97,7 +113,7 @@ export const JS_BIND_COMPONENTS: Set = new Set([ export const NEEDPOP_COMPONENT: Set = new Set(['Blank', 'Search']); export const CUSTOM_BUILDER_PROPERTIES: Set = new Set(['bindPopup', 'bindMenu', 'bindContextMenu', 'title', - 'menus', 'toolBar', 'tabBar', 'onDragStart', 'onItemDragStart']); + 'menus', 'toolBar', 'tabBar', 'onDragStart', 'onItemDragStart', 'swipeAction']); (function initComponent() { Object.keys(COMPONENT_MAP).forEach((componentName) => { diff --git a/compiler/src/ets_checker.ts b/compiler/src/ets_checker.ts index d5ad3e711b2245cab935171c41b9497a2aae63d8..c844a548fdf8206808a46f37d42ddc04ce00ae55 100644 --- a/compiler/src/ets_checker.ts +++ b/compiler/src/ets_checker.ts @@ -19,7 +19,8 @@ import * as ts from 'typescript'; import { projectConfig, - systemModules + systemModules, + globalProgram } from '../main'; import { processSystemApi, @@ -34,21 +35,22 @@ import { $$, PROPERTIES_ADD_DOUBLE_DOLLAR, $$_BLOCK_INTERFACE, - COMPONENT_EXTEND_DECORATOR + COMPONENT_EXTEND_DECORATOR, + EXTNAME_D_ETS, + EXTNAME_JS, + FOREACH_LAZYFOREACH } from './pre_define'; import { getName } from './process_component_build'; import { INNER_COMPONENT_NAMES } from './component_map'; -import { props } from './compile_info'; -import { resolveSourceFile } from './resolve_ohm_url'; import { - CacheFileName, - cache, - shouldResolvedFiles + props, + logger } from './compile_info'; import { hasDecorator } from './utils'; +import { generateSourceFilesInHar } from './utils'; import { isExtendFunction, isOriginalExtend } from './process_ui_syntax'; -function readDeaclareFiles(): string[] { +export function readDeaclareFiles(): string[] { const declarationsFileNames: string[] = []; fs.readdirSync(path.resolve(__dirname, '../declarations')) .forEach((fileName: string) => { @@ -87,6 +89,11 @@ function setCompilerOptions() { 'lib.es2020.d.ts' ] }); + if (projectConfig.packageDir === 'oh_modules') { + Object.assign(compilerOptions, { + 'packageManagerType': 'ohpm' + }); + } } interface extendInfo { @@ -107,7 +114,7 @@ export function createLanguageService(rootFileNames: string[]): ts.LanguageServi return undefined; } if (/(? { + let needCheckResult: boolean = false; + if (/compiler\/declarations/.test(sourceFileName) || /ets-loader\/declarations/.test(sourceFileName)) { + needCheckResult = true; + } + return { + needCheck: needCheckResult, + checkConfig: [{ + tagName: "form", + message: "'{0}' can't support form application.", + needConditionCheck: false, + type: ts.DiagnosticCategory.Error, + specifyCheckConditionFuncName: '', + tagNameShouldExisted: true + }] + } + } }; return ts.createLanguageService(servicesHost, ts.createDocumentRegistry()); } -function getOhmUrlFile(moduleName: string): {modulePath: string, suffix: string} { - const modulePath: string = resolveSourceFile(moduleName); - let suffix: string = path.extname(modulePath); - if (suffix === 'ts' && modulePath.endsWith('.d.ts')) { - suffix = '.d.ts'; +interface CacheFileName { + mtimeMs: number, + children: string[], + parent: string[], + error: boolean +} +interface NeedUpdateFlag { + flag: boolean; +} +interface CheckerResult { + count: number +} +interface WholeCache { + runtimeOS: string, + sdkInfo: string, + fileList: Cache +} +type Cache = Record; +export let cache: Cache = {}; +export const hotReloadSupportFiles: Set = new Set(); +export const shouldResolvedFiles: Set = new Set(); +const allResolvedModules: Set = new Set(); + +let fastBuildLogger = null; + +export const checkerResult: CheckerResult = {count: 0}; +export function serviceChecker(rootFileNames: string[], newLogger: any = null): void { + fastBuildLogger = newLogger; + let languageService: ts.LanguageService = null; + let cacheFile: string = null; + if (projectConfig.xtsMode) { + languageService = createLanguageService(rootFileNames); + } else { + cacheFile = path.resolve(projectConfig.cachePath, '../.ts_checker_cache'); + const wholeCache: WholeCache = fs.existsSync(cacheFile) ? + JSON.parse(fs.readFileSync(cacheFile).toString()) : + {'runtimeOS': projectConfig.runtimeOS, 'sdkInfo': projectConfig.sdkInfo, 'fileList': {}}; + if (wholeCache.runtimeOS === projectConfig.runtimeOS && wholeCache.sdkInfo === projectConfig.sdkInfo) { + cache = wholeCache.fileList; + } else { + cache = {}; + } + const filterFiles: string[] = filterInput(rootFileNames); + languageService = createLanguageService(filterFiles); + } + globalProgram.program = languageService.getProgram(); + const allDiagnostics: ts.Diagnostic[] = globalProgram.program + .getSyntacticDiagnostics() + .concat(globalProgram.program.getSemanticDiagnostics()) + .concat(globalProgram.program.getDeclarationDiagnostics()); + allDiagnostics.forEach((diagnostic: ts.Diagnostic) => { + printDiagnostic(diagnostic); + }); + if (process.env.watchMode !== 'true' && !projectConfig.xtsMode) { + fs.writeFileSync(cacheFile, JSON.stringify({ + 'runtimeOS': projectConfig.runtimeOS, + 'sdkInfo': projectConfig.sdkInfo, + 'fileList': cache + }, null, 2)); } + if (projectConfig.compileHar || projectConfig.compileShared) { + [...allResolvedModules, ...rootFileNames].forEach(moduleFile => { + if (!(moduleFile.match(new RegExp(projectConfig.packageDir)) && projectConfig.compileHar)) { + try { + const emit: any = languageService.getEmitOutput(moduleFile, true, true); + if (emit.outputFiles[0]) { + generateSourceFilesInHar(moduleFile, emit.outputFiles[0].text, '.d' + path.extname(moduleFile), + projectConfig); + } else { + console.warn(this.yellow, + "ArkTS:WARN doesn't generate .d" + path.extname(moduleFile) + ' for ' + moduleFile, this.reset); + } + } catch (err) {} + } + }); + } +} - return {modulePath, suffix}; +export function printDiagnostic(diagnostic: ts.Diagnostic): void { + const message: string = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'); + if (validateError(message)) { + if (process.env.watchMode !== 'true' && !projectConfig.xtsMode) { + updateErrorFileCache(diagnostic); + } + + // FIXME: will be instead of ts.Diagnostics config + if (diagnostic.file) { + const absPath = diagnostic.file.fileName; + const relativePath = path.relative(projectConfig.projectPath, absPath); + const cardEntryObjKey = `.././${relativePath}`.replace(/\.ets$/, ''); + if (!projectConfig.cardEntryObj[cardEntryObjKey] && + /can't support form application./.test(message)) { + return; + } + } + + checkerResult.count += 1; + if (diagnostic.file) { + const { line, character }: ts.LineAndCharacter = + diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start!); + fastBuildLogger ? + fastBuildLogger.error('\u001b[31m' + + `ArkTS:ERROR File: ${diagnostic.file.fileName}:${line + 1}:${character + 1}\n ${message}\n`) : + logger.error('\u001b[31m', + `ArkTS:ERROR File: ${diagnostic.file.fileName}:${line + 1}:${character + 1}\n ${message}\n`); + } else { + fastBuildLogger ? fastBuildLogger.error('\u001b[31m' + `ArkTS:ERROR: ${message}`) : + logger.error('\u001b[31m', `ArkTS:ERROR: ${message}`); + } + } +} + +function validateError(message: string): boolean { + const propInfoReg: RegExp = /Cannot find name\s*'(\$?\$?[_a-zA-Z0-9]+)'/; + const stateInfoReg: RegExp = /Property\s*'(\$?[_a-zA-Z0-9]+)' does not exist on type/; + if (matchMessage(message, props, propInfoReg) || + matchMessage(message, props, stateInfoReg)) { + return false; + } + return true; +} +function matchMessage(message: string, nameArr: any, reg: RegExp): boolean { + if (reg.test(message)) { + const match: string[] = message.match(reg); + if (match[1] && nameArr.includes(match[1])) { + return true; + } + } + return false; +} + +function updateErrorFileCache(diagnostic: ts.Diagnostic): void { + if (diagnostic.file && cache[path.resolve(diagnostic.file.fileName)]) { + cache[path.resolve(diagnostic.file.fileName)].error = true; + } +} + +function filterInput(rootFileNames: string[]): string[] { + return rootFileNames.filter((file: string) => { + const needUpdate: NeedUpdateFlag = { flag: false }; + const alreadyCheckedFiles: Set = new Set(); + checkNeedUpdateFiles(path.resolve(file), needUpdate, alreadyCheckedFiles); + return needUpdate.flag; + }); +} + +function checkNeedUpdateFiles(file: string, needUpdate: NeedUpdateFlag, alreadyCheckedFiles: Set): void { + if (alreadyCheckedFiles.has(file)) { + return; + } else { + alreadyCheckedFiles.add(file); + } + + if (needUpdate.flag) { + return; + } + + const value: CacheFileName = cache[file]; + const mtimeMs: number = fs.statSync(file).mtimeMs; + if (value) { + if (value.error || value.mtimeMs !== mtimeMs) { + needUpdate.flag = true; + return; + } + for (let i = 0; i < value.children.length; ++i) { + checkNeedUpdateFiles(value.children[i], needUpdate, alreadyCheckedFiles); + } + } else { + cache[file] = { mtimeMs, children: [], parent: [], error: false }; + needUpdate.flag = true; + } } const resolvedModulesCache: Map = new Map(); @@ -153,13 +340,17 @@ function resolveModuleNames(moduleNames: string[], containingFile: string): ts.R } }); if (result.resolvedModule) { - resolvedModules.push(result.resolvedModule); - } else if (/^@bundle:/.test(moduleName.trim())) { - const module: {modulePath: string, suffix: string} = getOhmUrlFile(moduleName.trim()); - if (ts.sys.fileExists(module.modulePath)) { - resolvedModules.push(getResolveModule(module.modulePath, module.suffix)); + if (result.resolvedModule.resolvedFileName && + path.extname(result.resolvedModule.resolvedFileName) === EXTNAME_JS) { + const resultDETSPath: string = + result.resolvedModule.resolvedFileName.replace(EXTNAME_JS, EXTNAME_D_ETS); + if (ts.sys.fileExists(resultDETSPath)) { + resolvedModules.push(getResolveModule(resultDETSPath, EXTNAME_D_ETS)); + } else { + resolvedModules.push(result.resolvedModule); + } } else { - resolvedModules.push(null); + resolvedModules.push(result.resolvedModule); } } else if (/^@(system|ohos)\./i.test(moduleName.trim())) { const modulePath: string = path.resolve(__dirname, '../../../api', moduleName + '.d.ts'); @@ -168,7 +359,7 @@ function resolveModuleNames(moduleNames: string[], containingFile: string): ts.R } else { resolvedModules.push(null); } - } else if (/\.ets$/.test(moduleName)) { + } else if (/\.ets$/.test(moduleName) && !/\.d\.ets$/.test(moduleName)) { const modulePath: string = path.resolve(path.dirname(containingFile), moduleName); if (ts.sys.fileExists(modulePath)) { resolvedModules.push(getResolveModule(modulePath, '.ets')); @@ -188,21 +379,45 @@ function resolveModuleNames(moduleNames: string[], containingFile: string): ts.R const jsModulePath: string = path.resolve(__dirname, '../node_modules', moduleName + suffix); const fileModulePath: string = path.resolve(__dirname, '../node_modules', moduleName + '/index.js'); + const DETSModulePath: string = path.resolve(path.dirname(containingFile), + /\.d\.ets$/.test(moduleName) ? moduleName : moduleName + EXTNAME_D_ETS); if (ts.sys.fileExists(modulePath)) { resolvedModules.push(getResolveModule(modulePath, '.d.ts')); } else if (ts.sys.fileExists(jsModulePath)) { resolvedModules.push(getResolveModule(jsModulePath, '.js')); } else if (ts.sys.fileExists(fileModulePath)) { resolvedModules.push(getResolveModule(fileModulePath, '.js')); + } else if (ts.sys.fileExists(DETSModulePath)) { + resolvedModules.push(getResolveModule(DETSModulePath, '.d.ets')); } else { - resolvedModules.push(null); + const srcIndex: number = projectConfig.projectPath.indexOf('src' + path.sep + 'main'); + let DETSModulePathFromModule: string; + if (srcIndex > 0) { + DETSModulePathFromModule = path.resolve( + projectConfig.projectPath.substring(0, srcIndex), moduleName + path.sep + 'index' + EXTNAME_D_ETS); + if (DETSModulePathFromModule && ts.sys.fileExists(DETSModulePathFromModule)) { + resolvedModules.push(getResolveModule(DETSModulePathFromModule, '.d.ets')); + } else { + resolvedModules.push(null); + } + } else { + resolvedModules.push(null); + } } } + if (projectConfig.hotReload && resolvedModules.length && + resolvedModules[resolvedModules.length - 1]) { + hotReloadSupportFiles.add(path.resolve(resolvedModules[resolvedModules.length - 1].resolvedFileName)); + } + if ((projectConfig.compileHar || projectConfig.compileShared) && resolvedModules[resolvedModules.length - 1] && + path.resolve(resolvedModules[resolvedModules.length - 1].resolvedFileName).match(/(\.[^d]|[^\.]d|[^\.][^d])\.e?ts$/)) { + allResolvedModules.add(resolvedModules[resolvedModules.length - 1].resolvedFileName); + } } if (!projectConfig.xtsMode) { createOrUpdateCache(resolvedModules, containingFile); } - resolvedModulesCache[path.resolve(containingFile)] = resolvedModules + resolvedModulesCache[path.resolve(containingFile)] = resolvedModules; return resolvedModules; } return resolvedModulesCache[path.resolve(containingFile)]; @@ -230,18 +445,29 @@ function createOrUpdateCache(resolvedModules: ts.ResolvedModuleFull[], containin }); cache[path.resolve(containingFile)] = { mtimeMs: fs.statSync(containingFile).mtimeMs, children, parent: cache[path.resolve(containingFile)] && cache[path.resolve(containingFile)].parent ? - cache[path.resolve(containingFile)].parent : [], error }; + cache[path.resolve(containingFile)].parent : [], error }; } export function createWatchCompilerHost(rootFileNames: string[], - reportDiagnostic: ts.DiagnosticReporter, delayPrintLogCount: Function, isPipe: boolean = false -): ts.WatchCompilerHostOfFilesAndCompilerOptions { + reportDiagnostic: ts.DiagnosticReporter, delayPrintLogCount: Function, resetErrorCount: Function, + isPipe: boolean = false): ts.WatchCompilerHostOfFilesAndCompilerOptions { + if (projectConfig.hotReload) { + rootFileNames.forEach(fileName => { + hotReloadSupportFiles.add(fileName); + }); + } setCompilerOptions(); const createProgram = ts.createSemanticDiagnosticsBuilderProgram; const host = ts.createWatchCompilerHost( [...rootFileNames, ...readDeaclareFiles()], compilerOptions, ts.sys, createProgram, reportDiagnostic, (diagnostic: ts.Diagnostic) => { + if ([6031, 6032].includes(diagnostic.code)) { + if (!isPipe) { + process.env.watchTs = 'start'; + resetErrorCount(); + } + } // End of compilation in watch mode flag. if ([6193, 6194].includes(diagnostic.code)) { if (!isPipe) { @@ -255,7 +481,7 @@ export function createWatchCompilerHost(rootFileNames: string[], return undefined; } if (/(? {}, () => {})); +} + function instanceInsteadThis(content: string, fileName: string, extendFunctionInfo: extendInfo[]): string { checkUISyntax(content, fileName, extendFunctionInfo); extendFunctionInfo.reverse().forEach((item) => { @@ -293,7 +525,8 @@ export const importModuleCollection: Set = new Set(); function checkUISyntax(source: string, fileName: string, extendFunctionInfo: extendInfo[]): void { if (/\.ets$/.test(fileName)) { - if (path.basename(fileName) !== 'app.ets') { + if (process.env.compileMode === 'moduleJson' || + path.resolve(fileName) !== path.resolve(projectConfig.projectPath, 'app.ets')) { const sourceFile: ts.SourceFile = ts.createSourceFile(fileName, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.ETS); parseAllNode(sourceFile, sourceFile, extendFunctionInfo); @@ -340,6 +573,12 @@ function parseAllNode(node: ts.Node, sourceFileNode: ts.SourceFile, extendFuncti node.getChildren().forEach((item: ts.Node) => parseAllNode(item, sourceFileNode, extendFunctionInfo)); } +function isForeachAndLzayForEach(node: ts.Node): boolean { + return ts.isCallExpression(node) && node.expression && ts.isIdentifier(node.expression) && + FOREACH_LAZYFOREACH.has(node.expression.escapedText.toString()) && node.arguments && node.arguments[1] && + ts.isArrowFunction(node.arguments[1]) && node.arguments[1].body && ts.isBlock(node.arguments[1].body); +} + function traverseBuild(node: ts.Node, index: number): void { if (ts.isExpressionStatement(node)) { let parentComponentName: string = getName(node); @@ -350,7 +589,11 @@ function traverseBuild(node: ts.Node, index: number): void { node = node.expression; if (ts.isEtsComponentExpression(node) && node.body && ts.isBlock(node.body) && !$$_BLOCK_INTERFACE.has(node.expression.escapedText.toString())) { - node.body.statements.forEach((item, indexBlock) => { + node.body.statements.forEach((item: ts.Statement, indexBlock: number) => { + traverseBuild(item, indexBlock); + }); + } else if (isForeachAndLzayForEach(node)) { + node.arguments[1].body.statements.forEach((item: ts.Statement, indexBlock: number) => { traverseBuild(item, indexBlock); }); } else { @@ -444,10 +687,40 @@ function processDraw(source: string): string { }); } -function processContent(source: string, sourcePath: string): string { - source = processSystemApi(source, false, sourcePath); +function processContent(source: string): string { + source = processSystemApi(source, false); source = preprocessExtend(source, extendCollection); source = preprocessNewExtend(source, extendCollection); source = processDraw(source); return source; } + +function judgeFileShouldResolved(file: string, shouldResolvedFiles: Set): void { + if (shouldResolvedFiles.has(file)) { + return; + } + shouldResolvedFiles.add(file); + if (cache && cache[file] && cache[file].parent) { + cache[file].parent.forEach((item) => { + judgeFileShouldResolved(item, shouldResolvedFiles); + }); + cache[file].parent = []; + } + if (cache && cache[file] && cache[file].children) { + cache[file].children.forEach((item) => { + judgeFileShouldResolved(item, shouldResolvedFiles); + }); + cache[file].children = []; + } +} + +export function incrementWatchFile(watchModifiedFiles: string[], + watchRemovedFiles: string[]): void { + const changedFiles: string[] = [...watchModifiedFiles, ...watchRemovedFiles]; + if (changedFiles.length) { + shouldResolvedFiles.clear(); + } + changedFiles.forEach((file) => { + judgeFileShouldResolved(file, shouldResolvedFiles); + }); +} diff --git a/compiler/syntax_parser/src/exclude_comment.peg b/compiler/src/fast_build/ark_compiler/bundle/bundle_build_mode.ts similarity index 55% rename from compiler/syntax_parser/src/exclude_comment.peg rename to compiler/src/fast_build/ark_compiler/bundle/bundle_build_mode.ts index d3ac07f11616ce7536978bd1c5f04e192b415926..139e591b7ee01c0d8ca02a81b9063579409c67b8 100644 --- a/compiler/syntax_parser/src/exclude_comment.peg +++ b/compiler/src/fast_build/ark_compiler/bundle/bundle_build_mode.ts @@ -1,37 +1,30 @@ -/* - * 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. - */ - -{ - const syntax_parser = require('./syntax_parser.js'); -} - -start = blocks: block* -{ - return syntax_parser.parse(blocks.join('')); -} - -block = comments/notComment - -comments = comment:$("/*" (!"*/" .)* "*/") { - let num = comment.split("\n").length-1; - let result = ''; - while (num>0) { - result += '\n'; - num -= 1; - } - return result; -} - -notComment = $((!comments .)+) +/* + * Copyright (c) 2023 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 { BundleMode } from './bundle_mode'; + +export class BundleBuildMode extends BundleMode { + constructor(rollupObject: any, rollupBundleFileSet: any) { + super(rollupObject, rollupBundleFileSet); + } + + generateAbc() { + if (this.filterIntermediateJsBundle.length === 0) { + super.afterCompilationProcess(); + return; + } + super.executeArkCompiler(); + } +} diff --git a/compiler/src/fast_build/ark_compiler/bundle/bundle_mode.ts b/compiler/src/fast_build/ark_compiler/bundle/bundle_mode.ts new file mode 100644 index 0000000000000000000000000000000000000000..f1e58fba472893c8256e59b1e9562c9101e84abd --- /dev/null +++ b/compiler/src/fast_build/ark_compiler/bundle/bundle_mode.ts @@ -0,0 +1,388 @@ +/* + * Copyright (c) 2023 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 path from 'path'; +import fs from 'fs'; +import cluster from 'cluster'; +import childProcess from 'child_process'; + +import { CommonMode } from '../common/common_mode'; +import { + changeFileExtension, + genCachePath, + getEs2abcFileThreadNumber, + genTemporaryModuleCacheDirectoryForBundle, + isMasterOrPrimary, + isSpecifiedExt +} from '../utils'; +import { + ES2ABC, + EXTNAME_ABC, + EXTNAME_JS, + FILESINFO_TXT, + JSBUNDLE, + MAX_WORKER_NUMBER, + TEMP_JS, + TS2ABC, + red, + blue, + FAIL, + reset +} from '../common/ark_define'; +import { + mkDir, + toHashData, + toUnixPath, + unlinkSync, + validateFilePathLength +} from '../../../utils'; +import { + isEs2Abc, + isTs2Abc +} from '../../../ark_utils'; + +interface File { + filePath: string; + cacheFilePath: string; + sourceFile: string; + size: number; +} + +export class BundleMode extends CommonMode { + intermediateJsBundle: Map; + filterIntermediateJsBundle: Array; + hashJsonObject: any; + filesInfoPath: string; + + constructor(rollupObject: any, rollupBundleFileSet: any) { + super(rollupObject); + this.intermediateJsBundle = new Map(); + this.filterIntermediateJsBundle = []; + this.hashJsonObject = {}; + this.filesInfoPath = ''; + this.prepareBundleFileListForCompilation(rollupBundleFileSet); + } + + prepareBundleFileListForCompilation(rollupBundleFileSet: any) { + this.collectBundleFileList(rollupBundleFileSet); + this.filterBundleFileListWithHashJson(); + } + + collectBundleFileList(rollupBundleFileSet: any) { + Object.keys(rollupBundleFileSet).forEach((fileName) => { + // choose *.js + if (this.projectConfig.aceModuleBuild && isSpecifiedExt(fileName, EXTNAME_JS)) { + const tempFilePath: string = changeFileExtension(fileName, TEMP_JS); + const outputPath: string = path.resolve(this.projectConfig.aceModuleBuild, tempFilePath); + const cacheOutputPath: string = this.genCacheBundleFilePath(outputPath, tempFilePath); + let rollupBundleSourceCode: string = ''; + if (rollupBundleFileSet[fileName].type === 'asset') { + rollupBundleSourceCode = rollupBundleFileSet[fileName].source; + } else if (rollupBundleFileSet[fileName].type === 'chunk') { + rollupBundleSourceCode = rollupBundleFileSet[fileName].code; + } else { + this.throwArkTsCompilerError('ArkTS:ERROR failed to get rollup bundle file source code'); + } + fs.writeFileSync(cacheOutputPath, rollupBundleSourceCode, 'utf-8'); + if (!fs.existsSync(cacheOutputPath)) { + this.throwArkTsCompilerError('ArkTS:ERROR failed to generate cached source file'); + } + this.collectIntermediateJsBundle(outputPath, cacheOutputPath); + } + }); + } + + filterBundleFileListWithHashJson() { + if (this.intermediateJsBundle.size === 0) { + return; + } + if (!fs.existsSync(this.hashJsonFilePath) || this.hashJsonFilePath.length === 0) { + this.intermediateJsBundle.forEach((value) => { + this.filterIntermediateJsBundle.push(value); + }); + return; + } + let updatedJsonObject: any = {}; + let jsonObject: any = {}; + let jsonFile: string = ''; + jsonFile = fs.readFileSync(this.hashJsonFilePath).toString(); + jsonObject = JSON.parse(jsonFile); + this.filterIntermediateJsBundle = []; + for (const value of this.intermediateJsBundle.values()) { + const cacheFilePath: string = value.cacheFilePath; + const cacheAbcFilePath: string = changeFileExtension(cacheFilePath, EXTNAME_ABC); + if (!fs.existsSync(cacheFilePath)) { + this.throwArkTsCompilerError(`ArkTS:ERROR ${cacheFilePath} is lost`); + } + if (fs.existsSync(cacheAbcFilePath)) { + const hashCacheFileContentData: any = toHashData(cacheFilePath); + const hashAbcContentData: any = toHashData(cacheAbcFilePath); + if (jsonObject[cacheFilePath] === hashCacheFileContentData && + jsonObject[cacheAbcFilePath] === hashAbcContentData) { + updatedJsonObject[cacheFilePath] = hashCacheFileContentData; + updatedJsonObject[cacheAbcFilePath] = hashAbcContentData; + continue; + } + } + this.filterIntermediateJsBundle.push(value); + } + + this.hashJsonObject = updatedJsonObject; + } + + executeArkCompiler() { + if (isEs2Abc(this.projectConfig)) { + this.filesInfoPath = this.generateFileInfoOfBundle(); + this.generateEs2AbcCmd(this.filesInfoPath); + this.executeEs2AbcCmd(); + } else if (isTs2Abc(this.projectConfig)) { + const splittedBundles: any[] = this.getSplittedBundles(); + this.invokeTs2AbcWorkersToGenAbc(splittedBundles); + } else { + this.throwArkTsCompilerError(`Invalid projectConfig.pandaMode for bundle build, should be either + "${TS2ABC}" or "${ES2ABC}"`); + } + } + + afterCompilationProcess() { + this.writeHashJson(); + this.copyFileFromCachePathToOutputPath(); + this.cleanCacheFiles(); + } + + private generateEs2AbcCmd(filesInfoPath: string) { + const fileThreads: number = getEs2abcFileThreadNumber(); + this.cmdArgs.push( + `"@${filesInfoPath}"`, + '--file-threads', + `"${fileThreads}"` + ); + } + + private generateFileInfoOfBundle(): string { + const filesInfoPath: string = genCachePath(FILESINFO_TXT, this.projectConfig, this.logger); + let filesInfo: string = ''; + this.filterIntermediateJsBundle.forEach((info) => { + const cacheFilePath: string = info.cacheFilePath; + const recordName: string = 'null_recordName'; + const moduleType: string = 'script'; + const sourceFile: string = info.sourceFile; + const abcFilePath: string = changeFileExtension(cacheFilePath, EXTNAME_ABC); + filesInfo += `${cacheFilePath};${recordName};${moduleType};${sourceFile};${abcFilePath}\n`; + }); + fs.writeFileSync(filesInfoPath, filesInfo, 'utf-8'); + + return filesInfoPath; + } + + private executeEs2AbcCmd() { + // collect data error from subprocess + let errMsg: string = ''; + const genAbcCmd: string = this.cmdArgs.join(' '); + try { + const child = this.triggerAsync(() => { + return childProcess.exec(genAbcCmd, { windowsHide: true }); + }); + child.on('exit', (code: any) => { + if (code === FAIL) { + this.throwArkTsCompilerError('ArkTS:ERROR failed to execute es2abc'); + } + this.afterCompilationProcess(); + this.triggerEndSignal(); + }); + + child.on('error', (err: any) => { + this.throwArkTsCompilerError(err.toString()); + }); + + child.stderr.on('data', (data: any) => { + errMsg += data.toString(); + }); + + child.stderr.on('end', () => { + if (errMsg !== undefined && errMsg.length > 0) { + this.logger.error(red, errMsg, reset); + } + }); + } catch (e) { + this.throwArkTsCompilerError('ArkTS:ERROR failed to execute es2abc with async handler: ' + e.toString()); + } + } + + private genCacheBundleFilePath(outputPath: string, tempFilePath: string): string { + let cacheOutputPath: string = ''; + if (this.projectConfig.cachePath) { + cacheOutputPath = path.join(genTemporaryModuleCacheDirectoryForBundle(this.projectConfig), tempFilePath); + } else { + cacheOutputPath = outputPath; + } + validateFilePathLength(cacheOutputPath, this.logger); + const parentDir: string = path.join(cacheOutputPath, '..'); + if (!(fs.existsSync(parentDir) && fs.statSync(parentDir).isDirectory())) { + mkDir(parentDir); + } + + return cacheOutputPath; + } + + private collectIntermediateJsBundle(filePath: string, cacheFilePath: string) { + const fileSize: any = fs.statSync(cacheFilePath).size; + filePath = toUnixPath(filePath); + cacheFilePath = toUnixPath(cacheFilePath); + let sourceFile: string = changeFileExtension(filePath, '_.js', TEMP_JS); + if (!this.projectConfig.isDebug && this.projectConfig.projectRootPath) { + sourceFile = toUnixPath(sourceFile.replace(this.projectConfig.projectRootPath + path.sep, '')); + } else { + sourceFile = toUnixPath(sourceFile); + } + const bundleFile: File = { + filePath: filePath, + cacheFilePath: cacheFilePath, + sourceFile: sourceFile, + size: fileSize + }; + this.intermediateJsBundle.set(filePath, bundleFile); + } + + private getSplittedBundles(): any[] { + const splittedBundles: any[] = this.splitJsBundlesBySize(this.filterIntermediateJsBundle, MAX_WORKER_NUMBER); + return splittedBundles; + } + + private invokeTs2AbcWorkersToGenAbc(splittedBundles) { + if (isMasterOrPrimary()) { + this.setupCluster(cluster); + const workerNumber: number = splittedBundles.length < MAX_WORKER_NUMBER ? splittedBundles.length : MAX_WORKER_NUMBER; + for (let i = 0; i < workerNumber; ++i) { + const workerData: any = { + inputs: JSON.stringify(splittedBundles[i]), + cmd: this.cmdArgs.join(' '), + mode: JSBUNDLE + }; + this.triggerAsync(() => { + const worker: any = cluster.fork(workerData); + worker.on('message', (errorMsg) => { + this.logger.error(red, errorMsg.data.toString(), reset); + this.throwArkTsCompilerError('ArkTS:ERROR failed to execute ts2abc, received error message.'); + }); + }); + } + + let workerCount: number = 0; + cluster.on('exit', (worker, code, signal) => { + if (code === FAIL) { + this.throwArkTsCompilerError('ArkTS:ERROR failed to execute ts2abc, exit code non-zero'); + } + workerCount++; + if (workerCount === workerNumber) { + this.afterCompilationProcess(); + } + this.triggerEndSignal(); + }); + } + } + + private getSmallestSizeGroup(groupSize: Map): any { + const groupSizeArray: any = Array.from(groupSize); + groupSizeArray.sort(function(g1, g2) { + return g1[1] - g2[1]; // sort by size + }); + return groupSizeArray[0][0]; + } + + private splitJsBundlesBySize(bundleArray: Array, groupNumber: number): any { + const result: any = []; + if (bundleArray.length < groupNumber) { + for (const value of bundleArray) { + result.push([value]); + } + return result; + } + + bundleArray.sort(function(f1: File, f2: File) { + return f2.size - f1.size; + }); + const groupFileSize: any = new Map(); + for (let i = 0; i < groupNumber; ++i) { + result.push([]); + groupFileSize.set(i, 0); + } + + let index: number = 0; + while (index < bundleArray.length) { + const smallestGroup: any = this.getSmallestSizeGroup(groupFileSize); + result[smallestGroup].push(bundleArray[index]); + const sizeUpdate: any = groupFileSize.get(smallestGroup) + bundleArray[index].size; + groupFileSize.set(smallestGroup, sizeUpdate); + index++; + } + return result; + } + + private writeHashJson() { + if (this.hashJsonFilePath.length === 0) { + return; + } + + for (let i = 0; i < this.filterIntermediateJsBundle.length; ++i) { + const cacheFilePath: string = this.filterIntermediateJsBundle[i].cacheFilePath; + const cacheAbcFilePath: string = changeFileExtension(cacheFilePath, EXTNAME_ABC); + if (!fs.existsSync(cacheFilePath) || !fs.existsSync(cacheAbcFilePath)) { + this.throwArkTsCompilerError(`ArkTS:ERROR ${cacheFilePath} or ${cacheAbcFilePath} is lost`); + } + const hashCacheFileContentData: any = toHashData(cacheFilePath); + const hashCacheAbcContentData: any = toHashData(cacheAbcFilePath); + this.hashJsonObject[cacheFilePath] = hashCacheFileContentData; + this.hashJsonObject[cacheAbcFilePath] = hashCacheAbcContentData; + } + + fs.writeFileSync(this.hashJsonFilePath, JSON.stringify(this.hashJsonObject), 'utf-8'); + } + + private copyFileFromCachePathToOutputPath() { + for (const value of this.intermediateJsBundle.values()) { + const abcFilePath: string = changeFileExtension(value.filePath, EXTNAME_ABC, TEMP_JS); + const cacheAbcFilePath: string = changeFileExtension(value.cacheFilePath, EXTNAME_ABC); + if (!fs.existsSync(cacheAbcFilePath)) { + this.throwArkTsCompilerError(`ArkTS:ERROR ${cacheAbcFilePath} is lost`); + } + const parent: string = path.join(abcFilePath, '..'); + if (!(fs.existsSync(parent) && fs.statSync(parent).isDirectory())) { + mkDir(parent); + } + // for preview mode, cache path and old abc file both exist, should copy abc file for updating + if (this.projectConfig.cachePath !== undefined) { + fs.copyFileSync(cacheAbcFilePath, abcFilePath); + } + } + } + + private cleanCacheFiles() { + // in xts mode, as cache path is not provided, cache files are located in output path, clear them + if (this.projectConfig.cachePath !== undefined) { + return; + } + + for (const value of this.intermediateJsBundle.values()) { + if (fs.existsSync(value.cacheFilePath)) { + fs.unlinkSync(value.cacheFilePath); + } + } + + if (isEs2Abc(this.projectConfig) && fs.existsSync(this.filesInfoPath)) { + unlinkSync(this.filesInfoPath); + } + } +} diff --git a/compiler/syntax_parser/src/parse_extend.peg b/compiler/src/fast_build/ark_compiler/bundle/bundle_preview_mode.ts similarity index 57% rename from compiler/syntax_parser/src/parse_extend.peg rename to compiler/src/fast_build/ark_compiler/bundle/bundle_preview_mode.ts index fc1459bb07c3d19207725e6561275ae01524f7ac..bac0fd7b6486c924652251bfef6d115dfe747713 100644 --- a/compiler/syntax_parser/src/parse_extend.peg +++ b/compiler/src/fast_build/ark_compiler/bundle/bundle_preview_mode.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2023 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 @@ -13,15 +13,17 @@ * limitations under the License. */ -start = extendAttributes:whiteSpace extendAttribute+ -{ - return {location: location()}; -} +import { BundleMode } from './bundle_mode'; + +export class BundlePreviewMode extends BundleMode { + constructor(rollupObject: any, rollupBundleFileSet: any) { + super(rollupObject, rollupBundleFileSet); + } -extendAttribute = (whiteSpace '.' whiteSpace attribute item)/(comment) -attribute = attr_head attr_tail -attr_head = $ [a-zA-Z_$]+ -attr_tail = $ [a-zA-Z0-9_$]* -item = whiteSpace '(' [^()]* item* [^()]* ')' whiteSpace -comment = "//" (![\r\n] .)* whiteSpace -whiteSpace = [ \t\r\n]* + generateAbc() { + if (this.filterIntermediateJsBundle.length === 0) { + return; + } + super.executeArkCompiler(); + } +} diff --git a/compiler/src/fast_build/ark_compiler/common/ark_define.ts b/compiler/src/fast_build/ark_compiler/common/ark_define.ts new file mode 100644 index 0000000000000000000000000000000000000000..e57275d4f01f111fa7a3b6033b1d4f51094e6a36 --- /dev/null +++ b/compiler/src/fast_build/ark_compiler/common/ark_define.ts @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2023 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. + */ + +export const ENTRY_TXT: string = 'entry.txt'; +export const FILESINFO_TXT: string = 'filesInfo.txt'; +export const FILESINFO: string = 'filesInfo'; +export const NPMENTRIES_TXT: string = 'npmEntries.txt'; +export const MODULES_CACHE: string = 'modules.cache'; +export const MODULES_ABC: string = 'modules.abc'; +export const WIDGETS_ABC: string = 'widgets.abc'; +export const MODULELIST_JSON: string = 'moduleList.json'; +export const PREBUILDMODE_JSON: string = 'preBuildMode.json'; +export const SOURCEMAPS_JSON: string = 'sourceMaps.json'; +export const SOURCEMAPS: string = 'sourceMaps.map'; +export const PROTO_FILESINFO_TXT: string = 'protoFilesInfo.txt'; +export const AOT_FULL: string = 'full'; +export const AOT_TYPE: string = 'type'; +export const AOT_PARTIAL: string = 'partial'; +export const AOT_PROFILE_SUFFIX: string = '.ap'; +export const NPM_ENTRIES_PROTO_BIN: string = 'npm_entries.protoBin'; +export const PACKAGE_JSON: string = 'package.json'; +export const FAKE_JS: string = 'fake.js'; + +export const ESMODULE: string = 'esmodule'; +export const JSBUNDLE: string = 'jsbundle'; +export const ARK: string = 'ark'; +export const TEMPORARY: string = 'temporary'; +export const MAIN: string = 'main'; +export const AUXILIARY: string = 'auxiliary'; +export const HAP_PACKAGE: string = '0'; +export const PROJECT_PACKAGE: string = '1'; +export const EXTNAME_ETS: string = '.ets'; +export const EXTNAME_JS: string = '.js'; +export const EXTNAME_TS: string = '.ts'; +export const EXTNAME_JS_MAP: string = '.js.map'; +export const EXTNAME_TS_MAP: string = '.ts.map'; +export const EXTNAME_MJS: string = '.mjs'; +export const EXTNAME_CJS: string = '.cjs'; +export const EXTNAME_D_TS: string = '.d.ts'; +export const EXTNAME_ABC: string = '.abc'; +export const EXTNAME_JSON: string = '.json'; +export const EXTNAME_PROTO_BIN: string = '.protoBin'; +export const PATCH_SYMBOL_TABLE: string = 'symbol.txt'; +export const TEMP_JS: string = '.temp.js'; +export const HASH_FILE_NAME: string = 'gen_hash.json'; +export const EXTNAME_TXT: string = '.txt'; +export const PROTOS: string = 'protos'; + +export const TS2ABC: string = 'ts2abc'; +export const ES2ABC: string = 'es2abc'; + +export const MAX_WORKER_NUMBER: number = 3; + +export const GEN_ABC_SCRIPT: string = 'gen_abc.js'; + +export const NODE_MODULES: string = 'node_modules'; +export const OH_MODULES: string = 'oh_modules'; +export const PACKAGES: string = 'pkg_modules'; + +export const TS_NOCHECK: string = '// @ts-nocheck'; + +export const WINDOWS: string = 'Windows_NT'; +export const LINUX: string = 'Linux'; +export const MAC: string = 'Darwin'; + +export const COMMONJS: string = 'commonjs'; +export const ESM: string = 'esm'; +export const SCRIPT: string = 'script'; + +export const SRC_MAIN: string = 'src/main'; +export const GEN_ABC_PLUGIN_NAME: string = 'Gen_Abc_Plugin'; + +export const SUCCESS: number = 0; +export const FAIL: number = 1; + +export const red: string = '\u001b[31m'; +export const yellow: string = '\u001b[33m'; +export const blue: string = '\u001b[34m'; +export const reset: string = '\u001b[39m'; + +export const DEBUG: string = 'debug'; +export const RELEASE: string = 'release'; + +export const TRUE: string = 'true'; +export const FALSE: string = 'false'; diff --git a/compiler/src/fast_build/ark_compiler/common/common_mode.ts b/compiler/src/fast_build/ark_compiler/common/common_mode.ts new file mode 100644 index 0000000000000000000000000000000000000000..7cc34fb02600137bc98f7753769b071bb94a6818 --- /dev/null +++ b/compiler/src/fast_build/ark_compiler/common/common_mode.ts @@ -0,0 +1,129 @@ +/* + * Copyright (c) 2023 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 fs from 'fs'; +import path from 'path'; + +import { + HASH_FILE_NAME, + GEN_ABC_PLUGIN_NAME, + GEN_ABC_SCRIPT, + blue, + reset +} from './ark_define'; +import { initArkConfig } from './process_ark_config'; +import { + nodeLargeOrEqualTargetVersion, + mkdirsSync, + validateFilePathLength +} from '../../../utils'; +import { + isEs2Abc, + isOhModules, + isTs2Abc +} from '../../../ark_utils'; +import { + genTemporaryModuleCacheDirectoryForBundle +} from '../utils'; + +export class CommonMode { + projectConfig: any; + arkConfig: any; + cmdArgs: string[] = []; + logger: any; + throwArkTsCompilerError: any; + hashJsonFilePath: string; + genAbcScriptPath: string; + triggerAsync: any; + triggerEndSignal: any; + + constructor(rollupObject: any) { + this.projectConfig = Object.assign(rollupObject.share.arkProjectConfig, rollupObject.share.projectConfig); + this.arkConfig = initArkConfig(this.projectConfig); + this.cmdArgs = this.initCmdEnv(); + this.logger = rollupObject.share.getLogger(GEN_ABC_PLUGIN_NAME); + this.throwArkTsCompilerError = rollupObject.share.throwArkTsCompilerError; + this.hashJsonFilePath = this.genHashJsonFilePath(); + this.genAbcScriptPath = path.resolve(__dirname, GEN_ABC_SCRIPT); + // Each time triggerAsync() was called, IDE will wait for asynchronous operation to finish before continue excuting. + // The finish signal was passed to IDE by calling triggerEndSignal() in the child process created by triggerAsync() + // When multiple workers were invoked by triggerAsync(), IDE will wait until the times of calling + // triggerEndSignal() matches the number of workers invoked. + // If the child process throws an error by calling throwArkTsCompilerError(), IDE will reset the counting state. + this.triggerAsync = rollupObject.async; + this.triggerEndSignal = rollupObject.signal; + } + + private initCmdEnv() { + let args: string[] = []; + + if (isTs2Abc(this.projectConfig)) { + let ts2abc: string = this.arkConfig.ts2abcPath; + validateFilePathLength(ts2abc, this.logger); + + ts2abc = '"' + ts2abc + '"'; + args = [`${this.arkConfig.nodePath}`, '--expose-gc', ts2abc]; + if (this.arkConfig.isDebug) { + args.push('--debug'); + } + if (isOhModules(this.projectConfig)) { + args.push('--oh-modules'); + } + } else if (isEs2Abc(this.projectConfig)) { + const es2abc: string = this.arkConfig.es2abcPath; + validateFilePathLength(es2abc, this.logger); + + args = ['"' + es2abc + '"']; + if (this.arkConfig.isDebug) { + args.push('--debug-info'); + } + } else { + this.throwArkTsCompilerError('ArkTS:ERROR please set panda mode'); + } + + return args; + } + + private genHashJsonFilePath() { + if (this.projectConfig.cachePath) { + if (!fs.existsSync(this.projectConfig.cachePath) || !fs.statSync(this.projectConfig.cachePath).isDirectory()) { + this.logger.debug(blue, `ArkTS:WARN cache path does bit exist or is not directory`, reset); + return ''; + } + const hashJsonPath: string = path.join(genTemporaryModuleCacheDirectoryForBundle(this.projectConfig), HASH_FILE_NAME); + validateFilePathLength(hashJsonPath, this.logger); + mkdirsSync(path.dirname(hashJsonPath)); + return hashJsonPath; + } else { + this.logger.debug(blue, `ArkTS:WARN cache path not specified`, reset); + return ''; + } + } + + setupCluster(cluster: any): void { + cluster.removeAllListeners('exit'); + if (nodeLargeOrEqualTargetVersion(16)) { + cluster.setupPrimary({ + exec: this.genAbcScriptPath, + windowsHide: true + }); + } else { + cluster.setupMaster({ + exec: this.genAbcScriptPath, + windowsHide: true + }); + } + } +} diff --git a/compiler/src/fast_build/ark_compiler/common/gen_abc.ts b/compiler/src/fast_build/ark_compiler/common/gen_abc.ts new file mode 100644 index 0000000000000000000000000000000000000000..8dde73b2112eb513d3815557fb1d7b9c6c3f045c --- /dev/null +++ b/compiler/src/fast_build/ark_compiler/common/gen_abc.ts @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2023 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 childProcess from 'child_process'; +import cluster from 'cluster'; +import fs from 'fs'; +import path from 'path'; +import process from 'process'; + +import { + COMMONJS, + ESM, + ESMODULE, + EXTNAME_ABC, + JSBUNDLE, + FAIL, + SUCCESS +} from './ark_define'; +import { changeFileExtension} from '../utils'; + +function genAbcByWorkersOfBundleMode(jsonInput: string, cmd: string): Promise { + const inputPaths: any = JSON.parse(jsonInput); + for (let i = 0; i < inputPaths.length; ++i) { + const cacheFilePath: string = inputPaths[i].cacheFilePath; + const cacheAbcFilePath: string = changeFileExtension(cacheFilePath, EXTNAME_ABC); + const sourceFile: string = inputPaths[i].sourceFile; + const singleCmd: any = `${cmd} "${cacheFilePath}" -o "${cacheAbcFilePath}" --source-file "${sourceFile}"`; + try { + childProcess.execSync(singleCmd, { windowsHide: true }); + } catch (e) { + process.send({ data: e.toString() }); + process.exit(FAIL); + } + } + + return; +} + +function genAbcByWorkersOfModuleMode(jsonInput: string, cmd: string, workerFileName: string, + cachePath: string): Promise { + const inputPaths: any = JSON.parse(jsonInput); + const filePath: string = path.join(cachePath, workerFileName); + let content: string = ''; + for (let i = 0; i < inputPaths.length; ++i) { + const info: any = inputPaths[i]; + const moduleType: string = info.isCommonJs ? COMMONJS : ESM; + content += `${info.cacheFilePath};${info.recordName};${moduleType};${info.sourceFile};${info.packageName}`; + if (i < inputPaths.length - 1) { + content += '\n'; + } + } + fs.writeFileSync(filePath, content, 'utf-8'); + const singleCmd: any = `${cmd} "${filePath}"`; + try { + childProcess.execSync(singleCmd, { windowsHide: true }); + } catch (e) { + process.send({ data: e.toString() }); + process.exit(FAIL); + } + + return; +} + +process.stderr.write = function(chunk) { + const message = chunk.toString(); + if (message.length !== 0) { + // send only non-empty message. sometimes there will be empty stderr, + // if processed by parent process's logger.error, the gen_abc process will fail + process.send({ + data: message + }); + } + return true; +}; + +if (cluster.isWorker && process.env['inputs'] !== undefined && process.env['cmd'] !== undefined && + process.env['mode'] !== undefined) { + if (process.env['mode'] === JSBUNDLE) { + genAbcByWorkersOfBundleMode(process.env['inputs'], process.env['cmd']); + process.exit(SUCCESS); + } else if (process.env['mode'] === ESMODULE && process.env['workerFileName'] && process.env['cachePath']) { + genAbcByWorkersOfModuleMode(process.env['inputs'], process.env['cmd'], process.env['workerFileName'], + process.env['cachePath']); + process.exit(SUCCESS); + } else { + process.exit(FAIL); + } +} else { + process.send({ + data: 'Failed to invoke worker with uncomplete inputs' + }); + process.exit(FAIL); +} diff --git a/compiler/src/fast_build/ark_compiler/common/process_ark_config.ts b/compiler/src/fast_build/ark_compiler/common/process_ark_config.ts new file mode 100644 index 0000000000000000000000000000000000000000..f9a3a634f6a94017ee1f9b6ee2d46b71c88d199d --- /dev/null +++ b/compiler/src/fast_build/ark_compiler/common/process_ark_config.ts @@ -0,0 +1,149 @@ +/* + * Copyright (c) 2023 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 path from 'path'; +import fs from 'fs'; + +import { + TS2ABC, + ESMODULE, + AOT_FULL, + AOT_PARTIAL, + AOT_TYPE, + AOT_PROFILE_SUFFIX, + NODE_MODULES, + OH_MODULES, + FAIL +} from './ark_define'; +import { isDebug } from '../utils'; +import { + isLinux, + isMac, + isWindows +} from '../../../utils'; +import { getArkBuildDir } from '../../../ark_utils'; +import { checkAotConfig } from '../../../gen_aot'; +import { projectConfig as mainProjectConfig } from '../../../../main'; + +type ArkConfig = { + arkRootPath: string; + ts2abcPath: string; + js2abcPath: string; + mergeAbcPath: string; + es2abcPath: string; + aotCompilerPath: string; + nodePath: string; + isDebug: boolean; +}; + +let arkConfig: ArkConfig = {}; + +export function initArkConfig(projectConfig: any) { + let arkRootPath: string = path.join(__dirname, '..', '..', '..', '..', 'bin', 'ark'); + if (projectConfig.arkFrontendDir) { + arkRootPath = projectConfig.arkFrontendDir; + } + arkConfig.nodePath = 'node'; + if (projectConfig.nodeJs) { + arkConfig.nodePath = projectConfig.nodePath; + } + processPlatformInfo(arkRootPath); + processCompatibleVersion(projectConfig, arkRootPath); + arkConfig.isDebug = isDebug(projectConfig); + arkConfig.arkRootPath = arkRootPath; + + return arkConfig; +} + +export function initArkProjectConfig(share: any) { + let projectConfig: any = share.projectConfig; + let arkProjectConfig: any = {}; + if (projectConfig.aceBuildJson && fs.existsSync(projectConfig.aceBuildJson)) { + const buildJsonInfo = JSON.parse(fs.readFileSync(projectConfig.aceBuildJson).toString()); + arkProjectConfig.projectRootPath = buildJsonInfo.projectRootPath; + arkProjectConfig.modulePathMap = buildJsonInfo.modulePathMap; + arkProjectConfig.isOhosTest = buildJsonInfo.isOhosTest; + if (checkAotConfig(buildJsonInfo, (error: string) => { share.throwArkTsCompilerError(error) })) { + arkProjectConfig.processTs = true; + arkProjectConfig.pandaMode = TS2ABC; + arkProjectConfig.anBuildOutPut = buildJsonInfo.anBuildOutPut; + arkProjectConfig.anBuildMode = buildJsonInfo.anBuildMode; + arkProjectConfig.apPath = buildJsonInfo.apPath; + } else { + arkProjectConfig.processTs = false; + arkProjectConfig.pandaMode = buildJsonInfo.pandaMode; + } + + if (buildJsonInfo.compileMode === ESMODULE) { + arkProjectConfig.nodeModulesPath = buildJsonInfo.nodeModulesPath; + arkProjectConfig.harNameOhmMap = buildJsonInfo.harNameOhmMap; + projectConfig.packageDir = buildJsonInfo.packageManagerType === 'ohpm' ? OH_MODULES : NODE_MODULES; + } + } + if (projectConfig.aceManifestPath && fs.existsSync(projectConfig.aceManifestPath)) { + const manifestJsonInfo = JSON.parse(fs.readFileSync(projectConfig.aceManifestPath).toString()); + if (manifestJsonInfo.minPlatformVersion) { + arkProjectConfig.minPlatformVersion = manifestJsonInfo.minPlatformVersion; + } + } + if (projectConfig.aceModuleJsonPath && fs.existsSync(projectConfig.aceModuleJsonPath)) { + const moduleJsonInfo = JSON.parse(fs.readFileSync(projectConfig.aceModuleJsonPath).toString()); + if (moduleJsonInfo.app.minAPIVersion) { + arkProjectConfig.minPlatformVersion = moduleJsonInfo.app.minAPIVersion; + } + if (moduleJsonInfo.module) { + arkProjectConfig.moduleName = moduleJsonInfo.module.name; + } + if (moduleJsonInfo.app) { + arkProjectConfig.bundleName = moduleJsonInfo.app.bundleName; + } + } + + // Hotreload attributes are initialized by arkui in main.js, just copy them. + arkProjectConfig.hotReload = mainProjectConfig.hotReload; + arkProjectConfig.patchAbcPath = mainProjectConfig.patchAbcPath; + arkProjectConfig.changedFileList = mainProjectConfig.changedFileList; + + return arkProjectConfig; +} + +function processPlatformInfo(arkRootPath: string): void { + const arkPlatformPath: string = getArkBuildDir(arkRootPath); + if (isWindows()) { + arkConfig.es2abcPath = path.join(arkPlatformPath, 'bin', 'es2abc.exe'); + arkConfig.ts2abcPath = path.join(arkPlatformPath, 'src', 'index.js'); + arkConfig.mergeAbcPath = path.join(arkPlatformPath, 'bin', 'merge_abc.exe'); + arkConfig.js2abcPath = path.join(arkPlatformPath, 'bin', 'js2abc.exe'); + arkConfig.aotCompilerPath = path.join(arkPlatformPath, 'bin', 'ark_aot_compiler.exe'); + return; + } + if (isLinux() || isMac()) { + arkConfig.es2abcPath = path.join(arkPlatformPath, 'bin', 'es2abc'); + arkConfig.ts2abcPath = path.join(arkPlatformPath, 'src', 'index.js'); + arkConfig.mergeAbcPath = path.join(arkPlatformPath, 'bin', 'merge_abc'); + arkConfig.js2abcPath = path.join(arkPlatformPath, 'bin', 'js2abc '); + arkConfig.aotCompilerPath = path.join(arkPlatformPath, 'bin', 'ark_aot_compiler'); + return; + } +} + +function processCompatibleVersion(projectConfig: any, arkRootPath: string) { + const platformPath: string = getArkBuildDir(arkRootPath); + if (projectConfig.minPlatformVersion && projectConfig.minPlatformVersion.toString() === '8') { + // use ts2abc to compile apps with 'CompatibleSdkVersion' set to 8 + arkConfig.ts2abcPath = path.join(platformPath, 'legacy_api8', 'src', 'index.js'); + projectConfig.pandaMode = TS2ABC; + } +} \ No newline at end of file diff --git a/compiler/build_parser.js b/compiler/src/fast_build/ark_compiler/generate_bundle_abc.ts similarity index 34% rename from compiler/build_parser.js rename to compiler/src/fast_build/ark_compiler/generate_bundle_abc.ts index fd83200ec341749a810a4c06618868b7b39bdcca..a498f9d5f590dc2a2772a49d42b486c6252d0faf 100644 --- a/compiler/build_parser.js +++ b/compiler/src/fast_build/ark_compiler/generate_bundle_abc.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2023 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 @@ -13,36 +13,30 @@ * limitations under the License. */ -const util = require('util'); -const childProcess = require('child_process'); -const exec = util.promisify(childProcess.exec); -const fs = require('fs'); -const path = require('path'); +import { JSBUNDLE } from './common/ark_define'; +import { BundlePreviewMode } from './bundle/bundle_preview_mode'; +import { BundleBuildMode } from './bundle/bundle_build_mode'; -function generateSyntaxParser(inputFile, nodePath) { - const readDirPath = path.resolve(__dirname, './syntax_parser/src'); - const readDirSubFiles = fs.readdirSync(readDirPath); - const catalogPath = path.resolve(inputFile, '..'); - const catalogSubFiles = fs.readdirSync(catalogPath) - const parserPath = path.resolve(__dirname, './node_modules/pegjs/bin/pegjs'); - - if (catalogSubFiles.includes('dist')) { - exec('rm -rf ' + catalogPath + '/dist/*.js'); - } else { - exec('mkdir ' + catalogPath + '/dist'); +/** + * rollup generatebundle hook + * @param {rollup OutputOptions} options + * @param {rollup [fileName: string]: AssetInfo | ChunkInfo} bundle + * @param {boolean} isWrite + */ +export function generateBundleAbc(options: any, bundle: any, isWrite: boolean) { + if (bundle === null || this.share.projectConfig.compileMode !== JSBUNDLE) { + return; } - ;(async function transJs () { - if (readDirSubFiles.length) { - for (let item of readDirSubFiles) { - let name = path.basename(item, '.peg'); - if (name){ - await exec(nodePath + ' ' + parserPath + ' -o ' + - catalogPath + '/dist/' + name + '.js ' + readDirPath + '/' + item); - } - } - } - })() + generateAbc(this, bundle); } -generateSyntaxParser(process.argv[2], process.argv[0]); +function generateAbc(rollupObject: any, rollupBundleFileSet: any) { + if (rollupObject.share.projectConfig.watchMode === 'true') { + const bundlePreviewMode: BundlePreviewMode = new BundlePreviewMode(rollupObject, rollupBundleFileSet); + bundlePreviewMode.generateAbc(); + } else { + const bundleBuildMode: BundleBuildMode = new BundleBuildMode(rollupObject, rollupBundleFileSet); + bundleBuildMode.generateAbc(); + } +} diff --git a/compiler/src/fast_build/ark_compiler/generate_module_abc.ts b/compiler/src/fast_build/ark_compiler/generate_module_abc.ts new file mode 100644 index 0000000000000000000000000000000000000000..52177a0f77e2b15b77f28aa3b5bc185d1bbc96c8 --- /dev/null +++ b/compiler/src/fast_build/ark_compiler/generate_module_abc.ts @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2023 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 { ESMODULE } from './common/ark_define'; +import { ModuleBuildMode } from './module/module_build_mode'; +import { ModuleHotfixMode } from './module/module_hotfix_mode'; +import { ModuleHotreloadMode } from './module/module_hotreload_mode'; +import { ModulePreviewMode } from './module/module_preview_mode'; +import { ModuleSourceFile } from './module/module_source_file'; + +export async function generateModuleAbc(error) { + if (error) { + // When error thrown in previous plugins, rollup will catch and call buildEnd plugin. + // Stop generate abc if error exists + return; + } + if (this.share.projectConfig.compileMode === ESMODULE) { + await ModuleSourceFile.processModuleSourceFiles(this); + if (this.share.projectConfig.compileHar) { + // compileHar: compile closed source har of project, which convert .ets to .d.ts and js, doesn't emit abc. + return; + } + generateAbc(this); + } +} + +function generateAbc(rollupObject: any) { + if (rollupObject.share.projectConfig.watchMode !== 'true') { + const moduleBuildMode: ModuleBuildMode = new ModuleBuildMode(rollupObject); + moduleBuildMode.generateAbc(rollupObject); + } else if (rollupObject.share.arkProjectConfig.hotReload) { + const moduleHotreloadMode: ModuleHotreloadMode = new ModuleHotreloadMode(rollupObject); + moduleHotreloadMode.generateAbc(rollupObject); + } else if (rollupObject.share.arkProjectConfig.hotFix) { + const moduleHotfixMode: ModuleHotfixMode = new ModuleHotfixMode(rollupObject); + moduleHotfixMode.generateAbc(rollupObject); + } else { + const modulePreviewMode: ModulePreviewMode = new ModulePreviewMode(rollupObject); + modulePreviewMode.generateAbc(rollupObject); + } +} diff --git a/compiler/src/fast_build/ark_compiler/module/module_build_mode.ts b/compiler/src/fast_build/ark_compiler/module/module_build_mode.ts new file mode 100644 index 0000000000000000000000000000000000000000..4d05ca96d9f2d5d055151aed4d2cd930ab053bf0 --- /dev/null +++ b/compiler/src/fast_build/ark_compiler/module/module_build_mode.ts @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2023 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 { ModuleMode } from './module_mode'; +import { isEs2Abc, isTs2Abc } from '../../../ark_utils'; +import { ES2ABC, TS2ABC } from '../common/ark_define'; + +export class ModuleBuildMode extends ModuleMode { + constructor(rollupObject: any) { + super(rollupObject); + } + + generateAbc(rollupObject: any) { + this.collectModuleFileList(rollupObject, rollupObject.getModuleIds()); + this.buildModuleSourceMapInfo(); + this.executeArkCompiler(); + } + + executeArkCompiler() { + if (isEs2Abc(this.projectConfig)) { + this.generateEs2AbcCmd(); + this.generateMergedAbcOfEs2Abc(); + } else if (isTs2Abc(this.projectConfig)) { + this.filterModulesByHashJson(); + const splittedModules: any[] = this.getSplittedModulesByNumber(); + this.invokeTs2AbcWorkersToGenProto(splittedModules); + this.processTs2abcWorkersToGenAbc(); + } else { + this.throwArkTsCompilerError(`Invalid projectConfig.pandaMode for module build, should be either + "${TS2ABC}" or "${ES2ABC}"`); + } + } +} diff --git a/compiler/src/fast_build/ark_compiler/module/module_hotfix_mode.ts b/compiler/src/fast_build/ark_compiler/module/module_hotfix_mode.ts new file mode 100644 index 0000000000000000000000000000000000000000..8cc8617c568b63fb9b0a50eb33228334f199a2a0 --- /dev/null +++ b/compiler/src/fast_build/ark_compiler/module/module_hotfix_mode.ts @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2023 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 path from 'path'; + +import { ModuleMode } from './module_mode'; +import { PATCH_SYMBOL_TABLE } from '../common/ark_define'; +import { getEs2abcFileThreadNumber } from '../utils'; + +export class ModuleHotfixMode extends ModuleMode { + patch: boolean; + inOldSymbolTablePath: string; + enableMap: boolean; + + constructor(rollupObject: any) { + super(rollupObject); + this.patch = false; + this.inOldSymbolTablePath = ''; + this.enableMap = false; + } + + generateAbc(rollupObject: any) { + this.patch = this.projectConfig.patch || false; + this.inOldSymbolTablePath = this.projectConfig.inOldSymbolTablePath || this.projectConfig.projectRootPath; + this.enableMap = this.projectConfig.enableMap || false; + this.collectModuleFileList(rollupObject, rollupObject.getModuleIds()); + this.buildModuleSourceMapInfo(); + + this.generateEs2AbcCmdForHotfix(); + this.generateMergedAbcOfEs2Abc(); + } + + private generateEs2AbcCmdForHotfix() { + const fileThreads = getEs2abcFileThreadNumber(); + this.cmdArgs.push(`"@${this.filesInfoPath}"`); + this.cmdArgs.push('--npm-module-entry-list'); + this.cmdArgs.push(`"${this.npmEntriesInfoPath}"`); + this.cmdArgs.push('--output'); + this.cmdArgs.push(`"${this.moduleAbcPath}"`); + this.cmdArgs.push('--file-threads'); + this.cmdArgs.push(`"${fileThreads}"`); + + if (this.projectConfig.patch) { + const oldHapSymbolTable: string = path.join(this.projectConfig.inOldSymbolTablePath, PATCH_SYMBOL_TABLE); + this.cmdArgs.push('--input-symbol-table'); + this.cmdArgs.push(`"${oldHapSymbolTable}"`); + this.cmdArgs.push('--generate-patch'); + } + + if (!this.projectConfig.enableMap) { + this.cmdArgs.push('--cache-file'); + this.cmdArgs.push(`"${this.cacheFilePath}"`); + } else { + // when generating map, cache is forbiden to avoid uncomplete symbol table + const oldHapSymbolTable: string = path.join(this.projectConfig.inOldSymbolTablePath, PATCH_SYMBOL_TABLE); + this.cmdArgs.push('--dump-symbol-table'); + this.cmdArgs.push(`"${oldHapSymbolTable}"`); + } + + this.cmdArgs.push('--merge-abc'); + } +} diff --git a/compiler/src/fast_build/ark_compiler/module/module_hotreload_mode.ts b/compiler/src/fast_build/ark_compiler/module/module_hotreload_mode.ts new file mode 100644 index 0000000000000000000000000000000000000000..fa76ed7ac2fd5580f15d554ed263b5a7c35bc459 --- /dev/null +++ b/compiler/src/fast_build/ark_compiler/module/module_hotreload_mode.ts @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2023 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 fs from 'fs'; +import path from 'path'; + +import { ModuleMode } from './module_mode'; +import { + blue, + reset, + MODULES_ABC, + SOURCEMAPS +} from '../common/ark_define'; +import { newSourceMaps } from '../transform'; +import { + mkdirsSync, + toUnixPath, + validateFilePathLength +} from '../../../utils'; + +let isFirstBuild: boolean = true; +let hotReloadSourceMap: Object = {}; + +export class ModuleHotreloadMode extends ModuleMode { + constructor(rollupObject: any) { + super(rollupObject); + } + + generateAbc(rollupObject: any) { + if (isFirstBuild) { + this.compileAllFiles(rollupObject); + isFirstBuild = false; + } else { + this.compileChangeListFiles(rollupObject); + } + } + + private compileAllFiles(rollupObject: any) { + this.collectModuleFileList(rollupObject, rollupObject.getModuleIds()); + this.buildModuleSourceMapInfo(); + this.generateAbcByEs2abc(); + } + + private compileChangeListFiles(rollupObject: any) { + if (!fs.existsSync(this.projectConfig.changedFileList)) { + this.logger.debug(blue, `ArkTS: Cannot find file: ${ + this.projectConfig.changedFileList}, skip hot reload build`, reset); + return; + } + + const changedFileListJson: string = fs.readFileSync(this.projectConfig.changedFileList).toString(); + const changedFileList: Array = JSON.parse(changedFileListJson).modifiedFiles; + if (typeof changedFileList === 'undefined' || changedFileList.length === 0) { + this.logger.debug(blue, `ArkTS: No changed files found, skip hot reload build`, reset); + return; + } + + if (!fs.existsSync(this.projectConfig.patchAbcPath)) { + mkdirsSync(this.projectConfig.patchAbcPath); + } + + this.updateSourceMapFromFileList(changedFileList); + let changedFileListInAbsolutePath: Array = changedFileList.map((file) => { + return path.join(this.projectConfig.projectPath, file); + }); + this.collectModuleFileList(rollupObject, changedFileListInAbsolutePath[Symbol.iterator]()); + + const outputABCPath: string = path.join(this.projectConfig.patchAbcPath, MODULES_ABC); + validateFilePathLength(outputABCPath, this.logger); + this.moduleAbcPath = outputABCPath; + + this.generateAbcByEs2abc(); + } + + private updateSourceMapFromFileList(fileList: Array) { + const relativeProjectPath: string = this.projectConfig.projectPath.slice( + this.projectConfig.projectRootPath.length + path.sep.length); + for (const file of fileList) { + const sourceMapPath: string = toUnixPath(path.join(relativeProjectPath, file)); + validateFilePathLength(sourceMapPath, this.logger); + hotReloadSourceMap[sourceMapPath] = newSourceMaps[sourceMapPath]; + } + + const sourceMapFilePath: string = path.join(this.projectConfig.patchAbcPath, SOURCEMAPS); + validateFilePathLength(sourceMapFilePath, this.logger); + fs.writeFileSync(sourceMapFilePath, + JSON.stringify(hotReloadSourceMap, null, 2), 'utf-8'); + } + + private generateAbcByEs2abc() { + this.generateEs2AbcCmd(); + this.generateMergedAbcOfEs2Abc(); + } +} diff --git a/compiler/src/fast_build/ark_compiler/module/module_mode.ts b/compiler/src/fast_build/ark_compiler/module/module_mode.ts new file mode 100644 index 0000000000000000000000000000000000000000..b54d98a63265439cb76e61a965fd486b89131c91 --- /dev/null +++ b/compiler/src/fast_build/ark_compiler/module/module_mode.ts @@ -0,0 +1,557 @@ +/* + * Copyright (c) 2023 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 childProcess from 'child_process'; +import fs from 'fs'; +import path from 'path'; +import cluster from 'cluster'; + +import { + AUXILIARY, + COMMONJS, + ESM, + EXTNAME_CJS, + EXTNAME_ETS, + EXTNAME_JS, + EXTNAME_JSON, + EXTNAME_MJS, + EXTNAME_TS, + FILESINFO_TXT, + MAIN, + MODULES_ABC, + MODULES_CACHE, + NPMENTRIES_TXT, + SOURCEMAPS, + TEMPORARY, + WIDGETS_ABC, + HAP_PACKAGE, + PACKAGES, + PROJECT_PACKAGE +} from '../common/ark_define'; +import { + ESMODULE, + EXTNAME_PROTO_BIN, + EXTNAME_TXT, + FILESINFO, + MAX_WORKER_NUMBER, + NPM_ENTRIES_PROTO_BIN, + PROTOS, + PROTO_FILESINFO_TXT, + FAIL, + red, + reset +} from '../common/ark_define'; +import { + needAotCompiler, + isMasterOrPrimary +} from '../utils'; +import { CommonMode } from '../common/common_mode'; +import { newSourceMaps } from '../transform'; +import { + changeFileExtension, + getEs2abcFileThreadNumber, + isCommonJsPluginVirtualFile, + isCurrentProjectFiles +} from '../utils'; +import { + isPackageModulesFile, + mkdirsSync, + toUnixPath, + toHashData, + validateFilePathLength +} from '../../../utils'; +import { + getPackageInfo, + getOhmUrlByFilepath +} from '../../../ark_utils'; +import { + generateAot, + generateBuiltinAbc, + FaultHandler +} from '../../../gen_aot' + +export class ModuleInfo { + filePath: string; + cacheFilePath: string; + recordName: string; + isCommonJs: boolean; + sourceFile: string; + packageName: string; + + constructor(filePath: string, cacheFilePath: string, isCommonJs: boolean, recordName: string, sourceFile: string, + packageName: string + ) { + this.filePath = filePath; + this.cacheFilePath = cacheFilePath; + this.recordName = recordName; + this.isCommonJs = isCommonJs; + this.sourceFile = sourceFile; + this.packageName = packageName; + } +} + +export class PackageEntryInfo { + // There are two types of modules : node_modules and oh_modules. Only one type exists in a project. + // And there are two types of directories modules placed in: project root directory and entry directory. + // take json5, a node_moduels placed in project root directory, as an example: + // pkgEntryPath will be 'pkg_modules/0/json5', pkgBuildPath will be 'pkg_modules/0/json5/index' + // 'pkg_modules' represents both oh_modules and node_moduels + // '0' represents this module is placed in project root dir, modules placed in entry dir will be '1' + pkgEntryPath: string; + pkgBuildPath: string; + constructor(pkgEntryPath: string, pkgBuildPath: string) { + this.pkgEntryPath = pkgEntryPath; + this.pkgBuildPath = pkgBuildPath; + } +} + +export class ModuleMode extends CommonMode { + moduleInfos: Map; + pkgEntryInfos: Map; + hashJsonObject: any; + filesInfoPath: string; + npmEntriesInfoPath: string; + moduleAbcPath: string; + sourceMapPath: string; + cacheFilePath: string; + workerNumber: number; + npmEntriesProtoFilePath: string; + protoFilePath: string; + filterModuleInfos: Map; + + constructor(rollupObject: any) { + super(rollupObject); + this.moduleInfos = new Map(); + this.pkgEntryInfos = new Map(); + this.hashJsonObject = {}; + this.filesInfoPath = path.join(this.projectConfig.cachePath, FILESINFO_TXT); + this.npmEntriesInfoPath = path.join(this.projectConfig.cachePath, NPMENTRIES_TXT); + const outPutABC: string = this.projectConfig.widgetCompile ? WIDGETS_ABC : MODULES_ABC; + this.moduleAbcPath = path.join(this.projectConfig.aceModuleBuild, outPutABC); + this.sourceMapPath = path.join(this.projectConfig.aceModuleBuild, SOURCEMAPS); + this.cacheFilePath = path.join(this.projectConfig.cachePath, MODULES_CACHE); + this.workerNumber = MAX_WORKER_NUMBER; + this.npmEntriesProtoFilePath = path.join(this.projectConfig.cachePath, PROTOS, NPM_ENTRIES_PROTO_BIN); + this.protoFilePath = path.join(this.projectConfig.cachePath, PROTOS, PROTO_FILESINFO_TXT); + this.hashJsonObject = {}; + this.filterModuleInfos = new Map(); + } + + collectModuleFileList(module: any, fileList: IterableIterator) { + let moduleInfos: Map = new Map(); + let pkgEntryInfos: Map = new Map(); + for (const moduleId of fileList) { + if (isCommonJsPluginVirtualFile(moduleId) || !isCurrentProjectFiles(moduleId, this.projectConfig)) { + continue; + } + const moduleInfo: any = module.getModuleInfo(moduleId); + if (moduleInfo['meta']['isNodeModuleEntryFile']) { + this.getPackageEntryInfo(moduleId, moduleInfo['meta'], pkgEntryInfos); + } + + this.processModuleInfos(moduleId, moduleInfos, moduleInfo['meta']); + } + this.moduleInfos = moduleInfos; + this.pkgEntryInfos = pkgEntryInfos; + } + + private getPackageEntryInfo(filePath: string, metaInfo: any, pkgEntryInfos: Map) { + if (!metaInfo['packageJson']) { + this.logger.debug("Failed to get 'packageJson' from metaInfo. File: ", filePath); + return; + } + const pkgPath: string = metaInfo['packageJson']['pkgPath']; + let originPkgEntryPath: string = toUnixPath(filePath.replace(pkgPath, '')); + if (originPkgEntryPath.startsWith('/')) { + originPkgEntryPath = originPkgEntryPath.slice(1, originPkgEntryPath.length); + } + const pkgEntryPath: string = toUnixPath(this.getPkgModulesFilePkgName(pkgPath)); + let pkgBuildPath: string = path.join(pkgEntryPath, originPkgEntryPath); + pkgBuildPath = toUnixPath(pkgBuildPath.substring(0, pkgBuildPath.lastIndexOf('.'))); + + pkgEntryInfos.set(pkgPath, new PackageEntryInfo(pkgEntryPath, pkgBuildPath)); + } + + private processModuleInfos(moduleId: string, moduleInfos: Map, metaInfo?: any) { + switch (path.extname(moduleId)) { + case EXTNAME_ETS: { + const extName: string = this.projectConfig.processTs ? EXTNAME_TS : EXTNAME_JS; + this.addModuleInfoItem(moduleId, false, extName, metaInfo, moduleInfos); + break; + } + case EXTNAME_TS: { + const extName: string = this.projectConfig.processTs ? '' : EXTNAME_JS; + this.addModuleInfoItem(moduleId, false, extName, metaInfo, moduleInfos); + break; + } + case EXTNAME_JS: + case EXTNAME_MJS: + case EXTNAME_CJS: { + const extName: string = (moduleId.endsWith(EXTNAME_MJS) || moduleId.endsWith(EXTNAME_CJS)) ? EXTNAME_JS : ''; + const isCommonJS: boolean = metaInfo && metaInfo['commonjs'] && metaInfo['commonjs']['isCommonJS']; + this.addModuleInfoItem(moduleId, isCommonJS, extName, metaInfo, moduleInfos); + break; + } + case EXTNAME_JSON: { + this.addModuleInfoItem(moduleId, false, '', metaInfo, moduleInfos); + break; + } + default: + break; + } + } + + private addModuleInfoItem(filePath: string, isCommonJs: boolean, extName: string, metaInfo: any, moduleInfos: any) { + let recordName: string = getOhmUrlByFilepath(filePath, this.projectConfig, this.logger); + let sourceFile: string = filePath.replace(this.projectConfig.projectRootPath + path.sep, ''); + let cacheFilePath: string = ''; + let packageName: string = ''; + if (isPackageModulesFile(filePath, this.projectConfig)) { + cacheFilePath = this.genPkgModulesFileCachePath(filePath, this.projectConfig.cachePath, this.projectConfig); + packageName = this.getPkgModulesFilePkgName(metaInfo['packageJson']['pkgPath']); + } else { + cacheFilePath = this.genFileCachePath(filePath, this.projectConfig.projectPath, this.projectConfig.cachePath); + packageName = getPackageInfo(this.projectConfig.aceModuleJsonPath)[1]; + } + + if (extName.length !== 0) { + cacheFilePath = changeFileExtension(cacheFilePath, extName); + } + + cacheFilePath = toUnixPath(cacheFilePath); + recordName = toUnixPath(recordName); + sourceFile = toUnixPath(sourceFile); + packageName = toUnixPath(packageName); + + moduleInfos.set(filePath, new ModuleInfo(filePath, cacheFilePath, isCommonJs, recordName, sourceFile, packageName)); + } + + buildModuleSourceMapInfo() { + if (!this.arkConfig.isDebug || this.projectConfig.widgetCompile) { + return; + } + mkdirsSync(this.projectConfig.aceModuleBuild); + const sourceMapFilePath: string = path.join(this.projectConfig.aceModuleBuild, SOURCEMAPS); + fs.writeFile(sourceMapFilePath, JSON.stringify(newSourceMaps, null, 2), 'utf-8', (err) => { + if (err) { + this.throwArkTsCompilerError('ArkTS:ERROR failed to write cache sourceMaps json'); + } + }); + } + + generateEs2AbcCmd() { + const fileThreads = getEs2abcFileThreadNumber(); + this.cmdArgs.push(`"@${this.filesInfoPath}"`); + this.cmdArgs.push('--npm-module-entry-list'); + this.cmdArgs.push(`"${this.npmEntriesInfoPath}"`); + this.cmdArgs.push('--output'); + this.cmdArgs.push(`"${this.moduleAbcPath}"`); + this.cmdArgs.push('--file-threads'); + this.cmdArgs.push(`"${fileThreads}"`); + this.cmdArgs.push('--cache-file'); + this.cmdArgs.push(`"${this.cacheFilePath}"`); + this.cmdArgs.push('--merge-abc'); + } + + private generateCompileFilesInfo() { + let filesInfo: string = ''; + this.moduleInfos.forEach((info) => { + const moduleType: string = info.isCommonJs ? COMMONJS : ESM; + filesInfo += `${info.cacheFilePath};${info.recordName};${moduleType};${info.sourceFile};${info.packageName}\n`; + }); + fs.writeFileSync(this.filesInfoPath, filesInfo, 'utf-8'); + } + + private generateNpmEntriesInfo() { + let entriesInfo: string = ''; + for (const value of this.pkgEntryInfos.values()) { + entriesInfo += `${value.pkgEntryPath}:${value.pkgBuildPath}\n`; + } + fs.writeFileSync(this.npmEntriesInfoPath, entriesInfo, 'utf-8'); + } + + private genDescriptionsForMergedEs2abc() { + this.generateCompileFilesInfo(); + this.generateNpmEntriesInfo(); + } + + generateMergedAbcOfEs2Abc() { + // collect data error from subprocess + let errMsg: string = ''; + this.genDescriptionsForMergedEs2abc(); + const genAbcCmd: string = this.cmdArgs.join(' '); + try { + const child = this.triggerAsync(() => { + return childProcess.exec(genAbcCmd, { windowsHide: true }); + }); + child.on('exit', (code: any) => { + if (code === FAIL) { + this.throwArkTsCompilerError('ArkTS:ERROR failed to execute es2abc'); + } + this.triggerEndSignal(); + }); + + child.on('error', (err: any) => { + this.throwArkTsCompilerError(err.toString()); + }); + + child.stderr.on('data', (data: any) => { + errMsg += data.toString(); + }); + + child.stderr.on('end', (data: any) => { + if (errMsg !== undefined && errMsg.length > 0) { + this.logger.error(red, errMsg, reset); + } + }); + } catch (e) { + this.throwArkTsCompilerError('ArkTS:ERROR failed to execute es2abc. Error message: ' + e.toString()); + } + } + + filterModulesByHashJson() { + if (this.hashJsonFilePath.length === 0 || !fs.existsSync(this.hashJsonFilePath)) { + for (const key of this.moduleInfos.keys()) { + this.filterModuleInfos.set(key, this.moduleInfos.get(key)); + } + return; + } + + let updatedJsonObject: any = {}; + let jsonObject: any = {}; + let jsonFile: string = ''; + + if (fs.existsSync(this.hashJsonFilePath)) { + jsonFile = fs.readFileSync(this.hashJsonFilePath).toString(); + jsonObject = JSON.parse(jsonFile); + this.filterModuleInfos = new Map(); + for (const [key, value] of this.moduleInfos) { + const cacheFilePath: string = value.cacheFilePath; + const cacheProtoFilePath: string = changeFileExtension(cacheFilePath, EXTNAME_PROTO_BIN); + if (!fs.existsSync(cacheFilePath)) { + this.throwArkTsCompilerError(`ArkTS:ERROR ${cacheFilePath} is lost`); + } + if (fs.existsSync(cacheProtoFilePath)) { + const hashCacheFileContentData: any = toHashData(cacheFilePath); + const hashProtoFileContentData: any = toHashData(cacheProtoFilePath); + if (jsonObject[cacheFilePath] === hashCacheFileContentData && + jsonObject[cacheProtoFilePath] === hashProtoFileContentData) { + updatedJsonObject[cacheFilePath] = cacheFilePath; + updatedJsonObject[cacheProtoFilePath] = cacheProtoFilePath; + continue; + } + } + this.filterModuleInfos.set(key, value); + } + } + + this.hashJsonObject = updatedJsonObject; + } + + getSplittedModulesByNumber() { + const result: any = []; + if (this.filterModuleInfos.size < this.workerNumber) { + for (const value of this.filterModuleInfos.values()) { + result.push([value]); + } + return result; + } + + for (let i = 0; i < this.workerNumber; ++i) { + result.push([]); + } + + let pos: number = 0; + for (const value of this.filterModuleInfos.values()) { + const chunk = pos % this.workerNumber; + result[chunk].push(value); + pos++; + } + + return result; + } + + invokeTs2AbcWorkersToGenProto(splittedModules) { + let ts2abcCmdArgs: string[] = this.cmdArgs.slice(0); + ts2abcCmdArgs.push('--output-proto'); + ts2abcCmdArgs.push('--merge-abc'); + ts2abcCmdArgs.push('--input-file'); + if (isMasterOrPrimary()) { + this.setupCluster(cluster); + this.workerNumber = splittedModules.length; + for (let i = 0; i < this.workerNumber; ++i) { + const sn: number = i + 1; + const workerFileName: string = `${FILESINFO}_${sn}${EXTNAME_TXT}`; + const workerData: any = { + inputs: JSON.stringify(splittedModules[i]), + cmd: ts2abcCmdArgs.join(' '), + workerFileName: workerFileName, + mode: ESMODULE, + cachePath: this.projectConfig.cachePath + }; + this.triggerAsync(() => { + const worker: any = cluster.fork(workerData); + worker.on('message', (errorMsg) => { + this.logger.error(red, errorMsg.data.toString(), reset); + this.throwArkTsCompilerError('ArkTS:ERROR failed to execute ts2abc'); + }); + }); + } + } + } + + processTs2abcWorkersToGenAbc() { + this.generateNpmEntriesInfo(); + let workerCount: number = 0; + if (isMasterOrPrimary()) { + cluster.on('exit', (worker, code, signal) => { + if (code === FAIL) { + this.throwArkTsCompilerError('ArkTS:ERROR failed to execute ts2abc'); + } + workerCount++; + if (workerCount === this.workerNumber) { + this.generateNpmEntryToGenProto(); + this.generateProtoFilesInfo(); + this.mergeProtoToAbc(); + this.processAotIfNeeded(); + this.afterCompilationProcess(); + } + this.triggerEndSignal(); + }); + if (this.workerNumber == 0) { + // process aot for no source file changed. + this.processAotIfNeeded(); + } + } + } + + private processAotIfNeeded(): void { + if (!needAotCompiler(this.projectConfig)) { + return; + } + let faultHandler: FaultHandler = ((error: string) => { this.throwArkTsCompilerError(error); }) + const builtinAbcPath: string = generateBuiltinAbc(this.arkConfig.arkRootPath, this.cmdArgs, + this.projectConfig.cachePath, this.logger, faultHandler); + generateAot(this.arkConfig.arkRootPath, builtinAbcPath, this.projectConfig, this.logger, faultHandler); + } + + private genFileCachePath(filePath: string, projectPath: string, cachePath: string, + buildInHar: boolean = false): string { + const sufStr: string = filePath.replace(projectPath, ''); + const output: string = path.join(cachePath, buildInHar ? '' : TEMPORARY, sufStr); + return output; + } + + private genPkgModulesFileCachePath(filePath: string, cachePath: string, projectConfig: any, + buildInHar: boolean = false): string { + const packageDir: string = projectConfig.packageDir; + const fakePkgModulesPath: string = toUnixPath(path.join(projectConfig.projectRootPath, packageDir)); + filePath = toUnixPath(filePath); + let output: string = ''; + if (filePath.indexOf(fakePkgModulesPath) === -1) { + const hapPath: string = toUnixPath(projectConfig.projectRootPath); + const tempFilePath: string = filePath.replace(hapPath, ''); + const sufStr: string = tempFilePath.substring(tempFilePath.indexOf(packageDir) + packageDir.length + 1); + output = path.join(cachePath, buildInHar ? '' : TEMPORARY, packageDir, MAIN, sufStr); + } else { + output = filePath.replace(fakePkgModulesPath, + path.join(cachePath, buildInHar ? '' : TEMPORARY, packageDir, AUXILIARY)); + } + return output; + } + + private getPkgModulesFilePkgName(pkgPath: string) { + pkgPath = toUnixPath(pkgPath); + const packageDir: string = this.projectConfig.packageDir; + const projectRootPath = toUnixPath(this.projectConfig.projectRootPath); + const projectPkgModulesPath: string = toUnixPath(path.join(projectRootPath, packageDir)); + let pkgName: string = ''; + if (pkgPath.includes(projectPkgModulesPath)) { + pkgName = path.join(PACKAGES, PROJECT_PACKAGE, pkgPath.replace(projectPkgModulesPath, '')); + } else { + const tempFilePath: string = pkgPath.replace(projectRootPath, ''); + pkgName = path.join(PACKAGES, HAP_PACKAGE, + tempFilePath.substring(tempFilePath.indexOf(packageDir) + packageDir.length + 1)); + } + + return pkgName.replace(packageDir, PACKAGES); + } + + private generateProtoFilesInfo() { + validateFilePathLength(this.protoFilePath, this.logger); + mkdirsSync(path.dirname(this.protoFilePath)); + let protoFilesInfo: string = ''; + const sortModuleInfos: any = new Map([...this.moduleInfos].sort()); + for (const value of sortModuleInfos.values()) { + const cacheProtoPath: string = changeFileExtension(value.cacheFilePath, EXTNAME_PROTO_BIN); + protoFilesInfo += `${toUnixPath(cacheProtoPath)}\n`; + } + if (this.pkgEntryInfos.size > 0) { + protoFilesInfo += `${toUnixPath(this.npmEntriesProtoFilePath)}\n`; + } + fs.writeFileSync(this.protoFilePath, protoFilesInfo, 'utf-8'); + } + + private mergeProtoToAbc() { + mkdirsSync(this.projectConfig.aceModuleBuild); + const cmd: any = `"${this.arkConfig.mergeAbcPath}" --input "@${this.protoFilePath}" --outputFilePath "${ + this.projectConfig.aceModuleBuild}" --output ${MODULES_ABC} --suffix protoBin`; + try { + childProcess.execSync(cmd, { windowsHide: true }); + } catch (e) { + this.throwArkTsCompilerError(`ArkTS:ERROR failed to merge proto file to abc, error message:` + e.toString()); + } + } + + private afterCompilationProcess() { + this.writeHashJson(); + } + + private writeHashJson() { + if (this.hashJsonFilePath.length === 0) { + return; + } + + for (const value of this.filterModuleInfos.values()) { + const cacheFilePath: string = value.cacheFilePath; + const cacheProtoFilePath: string = changeFileExtension(cacheFilePath, EXTNAME_PROTO_BIN); + if (!fs.existsSync(cacheFilePath) || !fs.existsSync(cacheProtoFilePath)) { + this.throwArkTsCompilerError( + `ArkTS:ERROR ${cacheFilePath} or ${cacheProtoFilePath} is lost` + ); + } + const hashCacheFileContentData: any = toHashData(cacheFilePath); + const hashCacheProtoContentData: any = toHashData(cacheProtoFilePath); + this.hashJsonObject[cacheFilePath] = hashCacheFileContentData; + this.hashJsonObject[cacheProtoFilePath] = hashCacheProtoContentData; + } + + fs.writeFileSync(this.hashJsonFilePath, JSON.stringify(this.hashJsonObject)); + } + + private generateNpmEntryToGenProto() { + if (this.pkgEntryInfos.size <= 0) { + return; + } + mkdirsSync(path.dirname(this.npmEntriesProtoFilePath)); + const cmd: string = `"${this.arkConfig.js2abcPath}" --compile-npm-entries "${ + this.npmEntriesInfoPath}" "${this.npmEntriesProtoFilePath}"`; + try { + childProcess.execSync(cmd, { windowsHide: true }); + } catch (e) { + this.throwArkTsCompilerError(`ArkTS:ERROR failed to generate npm proto file to abc. Error message: ` + e.toString()); + } + } +} diff --git a/compiler/src/fast_build/ark_compiler/module/module_preview_mode.ts b/compiler/src/fast_build/ark_compiler/module/module_preview_mode.ts new file mode 100644 index 0000000000000000000000000000000000000000..933bb2814675f71d04be5523e540a0e04ec1c839 --- /dev/null +++ b/compiler/src/fast_build/ark_compiler/module/module_preview_mode.ts @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2023 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 { ModuleMode } from './module_mode'; +import { ES2ABC, TS2ABC } from '../common/ark_define'; +import { isEs2Abc, isTs2Abc } from '../../../ark_utils'; + +export class ModulePreviewMode extends ModuleMode { + constructor(rollupObject: any) { + super(rollupObject); + } + + generateAbc(rollupObject: any) { + this.collectModuleFileList(rollupObject, rollupObject.getModuleIds()); + this.executeArkCompiler(); + } + + executeArkCompiler() { + if (isEs2Abc(this.projectConfig)) { + this.generateEs2AbcCmd(); + this.generateMergedAbcOfEs2Abc(); + } else if (isTs2Abc(this.projectConfig)) { + this.filterModulesByHashJson(); + const splittedModules: any[] = this.getSplittedModulesByNumber(); + this.invokeTs2AbcWorkersToGenProto(splittedModules); + this.processTs2abcWorkersToGenAbc(); + } else { + this.throwArkTsCompilerError(`Invalid projectConfig.pandaMode for module preview, should be either + "${TS2ABC}" or "${ES2ABC}"`); + } + } +} diff --git a/compiler/src/fast_build/ark_compiler/module/module_source_file.ts b/compiler/src/fast_build/ark_compiler/module/module_source_file.ts new file mode 100644 index 0000000000000000000000000000000000000000..934f2af28ac455837d65833dc18e141bbfa1ca50 --- /dev/null +++ b/compiler/src/fast_build/ark_compiler/module/module_source_file.ts @@ -0,0 +1,166 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use rollupObject 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 * as ts from 'typescript'; +import MagicString from 'magic-string'; +import { + GEN_ABC_PLUGIN_NAME, + PACKAGES +} from '../common/ark_define'; +import { getOhmUrlByFilepath, getOhmUrlByHarName } from '../../../ark_utils'; +import { writeFileSyncByNode } from '../../../process_module_files'; +import { + isJsonSourceFile, + isJsSourceFile, + writeFileContentToTempDir +} from '../utils'; + +const ROLLUP_IMPORT_NODE: string = 'ImportDeclaration'; +const ROLLUP_EXPORTNAME_NODE: string = 'ExportNamedDeclaration'; +const ROLLUP_EXPORTALL_NODE: string = 'ExportAllDeclaration'; + +export class ModuleSourceFile { + private static sourceFiles: ModuleSourceFile[] = []; + private moduleId: string; + private source: string | ts.SourceFile; + private isSourceNode: boolean = false; + private static projectConfig: any; + private static logger: any; + + constructor(moduleId: string, source: string | ts.SourceFile) { + this.moduleId = moduleId; + this.source = source; + if (typeof this.source !== 'string') { + this.isSourceNode = true; + } + } + + static newSourceFile(moduleId: string, source: string | ts.SourceFile) { + ModuleSourceFile.sourceFiles.push(new ModuleSourceFile(moduleId, source)); + } + + static async processModuleSourceFiles(rollupObject: any) { + this.initPluginEnv(rollupObject); + await ModuleSourceFile.sourceFiles.forEach((source: ModuleSourceFile) => { + if (!rollupObject.share.projectConfig.compileHar) { + // compileHar: compile closed source har of project, which convert .ets to .d.ts and js, doesn't transform module request. + source.processModuleRequest(rollupObject); + } + source.writeSourceFile(); + }); + ModuleSourceFile.sourceFiles = []; + } + + private writeSourceFile() { + if (this.isSourceNode && !isJsSourceFile(this.moduleId)) { + writeFileSyncByNode(this.source, true, ModuleSourceFile.projectConfig); + } else { + writeFileContentToTempDir(this.moduleId, this.source, ModuleSourceFile.projectConfig, + ModuleSourceFile.logger); + } + } + + private getOhmUrl(moduleRequest: string, filePath: string | undefined): string | undefined { + const harOhmUrl: string | undefined = getOhmUrlByHarName(moduleRequest, ModuleSourceFile.projectConfig); + if (harOhmUrl !== undefined) { + return harOhmUrl; + } + if (filePath) { + const ohmUrl: string = getOhmUrlByFilepath(filePath, ModuleSourceFile.projectConfig, ModuleSourceFile.logger); + return ohmUrl.startsWith(PACKAGES) ? `@package:${ohmUrl}` : `@bundle:${ohmUrl}`; + } + return undefined; + } + + private processJsModuleRequest(rollupObject: any) { + const moduleInfo: any = rollupObject.getModuleInfo(this.moduleId); + const importMap: any = moduleInfo.importedIdMaps; + const REG_DEPENDENCY: RegExp = /(?:import|from)(?:\s*)['"]([^'"]+)['"]/g; + this.source = (this.source).replace(REG_DEPENDENCY, (item, moduleRequest) => { + const ohmUrl: string | undefined = this.getOhmUrl(moduleRequest, importMap[moduleRequest]); + if (ohmUrl !== undefined) { + item = item.replace(/(['"])(?:\S+)['"]/, (_, quotation) => { + return quotation + ohmUrl + quotation; + }); + } + return item; + }); + } + + private processTransformedJsModuleRequest(rollupObject: any) { + const moduleInfo: any = rollupObject.getModuleInfo(this.moduleId); + const importMap: any = moduleInfo.importedIdMaps; + const code: MagicString = new MagicString(this.source); + const ast = moduleInfo.ast; + ast.body.forEach(node => { + if (node.type === ROLLUP_IMPORT_NODE || (node.type === ROLLUP_EXPORTNAME_NODE && node.source) || + node.type === ROLLUP_EXPORTALL_NODE) { + const ohmUrl: string | undefined = this.getOhmUrl(node.source.value, importMap[node.source.value]); + if (ohmUrl !== undefined) { + code.update(node.source.start, node.source.end, `'${ohmUrl}'`); + } + } + }); + this.source = code.toString(); + } + + private processTransformedTsModuleRequest(rollupObject: any) { + const moduleInfo: any = rollupObject.getModuleInfo(this.moduleId); + const importMap: any = moduleInfo.importedIdMaps; + const statements: ts.Statement[] = []; + (this.source)!.forEachChild((childNode: ts.Statement) => { + if (ts.isImportDeclaration(childNode) || (ts.isExportDeclaration(childNode) && childNode.moduleSpecifier)) { + // moduleSpecifier.getText() returns string carrying on quotation marks which the importMap's key does not, + // so we need to remove the quotation marks from moduleRequest. + const moduleRequest: string = childNode.moduleSpecifier.getText().replace(/'|"/g, ''); + const ohmUrl: string | undefined = this.getOhmUrl(moduleRequest, importMap[moduleRequest]); + if (ohmUrl !== undefined) { + if (ts.isImportDeclaration(childNode)) { + childNode = ts.factory.updateImportDeclaration(childNode, childNode.decorators, childNode.modifiers, + childNode.importClause, ts.factory.createStringLiteral(ohmUrl)); + } else { + childNode = ts.factory.updateExportDeclaration(childNode, childNode.decorators, childNode.modifiers, + childNode.isTypeOnly, childNode.exportClause, ts.factory.createStringLiteral(ohmUrl)); + } + } + } + statements.push(childNode); + }); + this.source = ts.factory.updateSourceFile(this.source, statements); + } + + // Replace each module request in source file to a unique representation which is called 'ohmUrl'. + // This 'ohmUrl' will be the same as the record name for each file, to make sure runtime can find the corresponding + // record based on each module request. + processModuleRequest(rollupObject: any) { + if (isJsonSourceFile(this.moduleId)) { + return; + } + if (isJsSourceFile(this.moduleId)) { + this.processJsModuleRequest(rollupObject); + return; + } + + // Only when files were transformed to ts, the corresponding ModuleSourceFile were initialized with sourceFile node, + // if files were transformed to js, ModuleSourceFile were initialized with srouce string. + this.isSourceNode ? this.processTransformedTsModuleRequest(rollupObject) : + this.processTransformedJsModuleRequest(rollupObject); + } + + private static initPluginEnv(rollupObject: any) { + this.projectConfig = Object.assign(rollupObject.share.arkProjectConfig, rollupObject.share.projectConfig); + this.logger = rollupObject.share.getLogger(GEN_ABC_PLUGIN_NAME); + } +} diff --git a/compiler/src/fast_build/ark_compiler/rollup-plugin-gen-abc.ts b/compiler/src/fast_build/ark_compiler/rollup-plugin-gen-abc.ts new file mode 100644 index 0000000000000000000000000000000000000000..4584269a7f53934f12e389b2a80bed5b873c17e7 --- /dev/null +++ b/compiler/src/fast_build/ark_compiler/rollup-plugin-gen-abc.ts @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2023 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 { initArkProjectConfig } from './common/process_ark_config'; +import { generateBundleAbc } from './generate_bundle_abc'; +import { generateModuleAbc } from './generate_module_abc'; +import { transformForModule } from './transform'; + +export function genAbc() { + return { + name: 'genAbc', + buildStart() { + this.share.arkProjectConfig = initArkProjectConfig(this.share); + }, + transform: transformForModule, + buildEnd: generateModuleAbc, + generateBundle: generateBundleAbc + }; +} diff --git a/compiler/src/fast_build/ark_compiler/transform.ts b/compiler/src/fast_build/ark_compiler/transform.ts new file mode 100644 index 0000000000000000000000000000000000000000..3577577f895cb9ff4f4a3677f66fb9b6a9cde85a --- /dev/null +++ b/compiler/src/fast_build/ark_compiler/transform.ts @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2023 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 path from 'path'; + +import { + ESMODULE +} from './common/ark_define'; +import { ModuleSourceFile } from './module/module_source_file'; +import { + isAotMode, + isCommonJsPluginVirtualFile, + isDebug, + isJsonSourceFile, + isJsSourceFile, + isTsOrEtsSourceFile +} from './utils'; +import { toUnixPath } from '../../utils'; + +export let newSourceMaps: Object = {}; + +/** + * rollup transform hook + * @param {string} code: transformed source code of an input file + * @param {string} id: absolute path of an input file + */ +export function transformForModule(code: string, id: string) { + if (this.share.projectConfig.compileMode === ESMODULE) { + const projectConfig: any = Object.assign(this.share.arkProjectConfig, this.share.projectConfig); + if (isTsOrEtsSourceFile(id) && !isAotMode(projectConfig)) { + if (isDebug(projectConfig)) { + preserveSourceMap(id, this.getCombinedSourcemap(), projectConfig); + } + ModuleSourceFile.newSourceFile(id, code); + } + + if (isJsSourceFile(id) || isJsonSourceFile(id)) { + ModuleSourceFile.newSourceFile(id, this.getModuleInfo(id).originalCode); + } + } +} + +function preserveSourceMap(sourceFilePath: string, sourcemap: any, projectConfig: any): void { + if (isCommonJsPluginVirtualFile(sourceFilePath)) { + // skip automatic generated files like 'jsfile.js?commonjs-exports' + return; + } + + const relativeSourceFilePath = toUnixPath(sourceFilePath.replace(projectConfig.projectRootPath + path.sep, '')); + sourcemap['sources'] = [ relativeSourceFilePath ]; + sourcemap['file'] = path.basename(relativeSourceFilePath); + newSourceMaps[relativeSourceFilePath] = sourcemap; +} diff --git a/compiler/src/fast_build/ark_compiler/utils.ts b/compiler/src/fast_build/ark_compiler/utils.ts new file mode 100644 index 0000000000000000000000000000000000000000..3cfc02e7ec2d767398bcef4a182b8b0a4eddcf64 --- /dev/null +++ b/compiler/src/fast_build/ark_compiler/utils.ts @@ -0,0 +1,172 @@ +/* + * Copyright (c) 2023 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 cluster from 'cluster'; +import fs from 'fs'; +import path from 'path'; +import os from 'os'; + +import { + DEBUG, + ESMODULE, + EXTNAME_ETS, + EXTNAME_JS, + EXTNAME_TS, + EXTNAME_JSON, + EXTNAME_CJS, + EXTNAME_MJS, + TEMPORARY +} from './common/ark_define'; +import { + nodeLargeOrEqualTargetVersion, + genTemporaryPath, + mkdirsSync, + validateFilePathLength +} from '../../utils'; +import { + writeMinimizedSourceCode +} from '../../ark_utils'; +import { AOT_FULL, AOT_PARTIAL, AOT_TYPE } from '../../pre_define'; + +export function needAotCompiler(projectConfig: any): boolean { + return projectConfig.compileMode === ESMODULE && (projectConfig.anBuildMode === AOT_FULL || + projectConfig.anBuildMode === AOT_PARTIAL); +} + +export function isAotMode(projectConfig: any): boolean { + return projectConfig.compileMode === ESMODULE && (projectConfig.anBuildMode === AOT_FULL || + projectConfig.anBuildMode === AOT_PARTIAL || projectConfig.anBuildMode === AOT_TYPE); +} + +export function isDebug(projectConfig: any): boolean { + return projectConfig.buildMode.toLowerCase() === DEBUG; +} + +export function isMasterOrPrimary() { + return ((nodeLargeOrEqualTargetVersion(16) && cluster.isPrimary) || + (!nodeLargeOrEqualTargetVersion(16) && cluster.isMaster)); +} + +export function changeFileExtension(file: string, targetExt: string, originExt = ''): string { + let currentExt = originExt.length === 0 ? path.extname(file) : originExt; + let fileWithoutExt = file.substring(0, file.lastIndexOf(currentExt)); + return fileWithoutExt + targetExt; +} + +export function writeFileContentToTempDir(id: string, content: string, projectConfig: any, logger: any) { + if (isCommonJsPluginVirtualFile(id)) { + return; + } + + if (!isCurrentProjectFiles(id, projectConfig)) { + return; + } + + let filePath: string; + if (projectConfig.compileHar) { + // compileShared: compile shared har of project + filePath = genTemporaryPath(id, + projectConfig.compileShared ? projectConfig.projectRootPath : projectConfig.moduleRootPath, + projectConfig.compileShared ? path.resolve(projectConfig.aceModuleBuild, '../etsFortgz'): projectConfig.cachePath, + projectConfig, projectConfig.compileShared); + } else { + filePath = genTemporaryPath(id, projectConfig.projectPath, projectConfig.cachePath, projectConfig); + } + + switch (path.extname(id)) { + case EXTNAME_ETS: + case EXTNAME_TS: + case EXTNAME_JS: + case EXTNAME_MJS: + case EXTNAME_CJS: + writeFileContent(id, filePath, content, projectConfig, logger); + break; + case EXTNAME_JSON: + mkdirsSync(path.dirname(filePath)); + fs.writeFileSync(filePath, content, 'utf-8'); + break; + default: + break; + } +} + +function writeFileContent(sourceFilePath: string, filePath: string, content: string, projectConfig: any, logger: any) { + if (!isSpecifiedExt(sourceFilePath, EXTNAME_JS)) { + filePath = changeFileExtension(filePath, EXTNAME_JS); + } + + mkdirsSync(path.dirname(filePath)); + + if ((projectConfig.compileHar && projectConfig.obfuscateHarType === 'uglify') || !isDebug(projectConfig)) { + writeMinimizedSourceCode(content, filePath, logger); + return; + } + + fs.writeFileSync(filePath, content, 'utf-8'); +} + +export function getEs2abcFileThreadNumber(): number { + const fileThreads : number = os.cpus().length < 16 ? os.cpus().length : 16; + return fileThreads; +} + +export function isCommonJsPluginVirtualFile(filePath: string): boolean { + // rollup uses commonjs plugin to handle commonjs files, + // which will automatic generate files like 'jsfile.js?commonjs-exports' + return filePath.includes('\x00'); +} + +export function isCurrentProjectFiles(filePath: string, projectConfig: any): boolean { + const packageDir: string = projectConfig.packageDir; + let modulePath: string = projectConfig.modulePathMap[projectConfig.moduleName]; + return filePath.indexOf(projectConfig.projectPath) >= 0 || + (projectConfig.moduleRootPath && filePath.indexOf(projectConfig.moduleRootPath) >= 0) || + filePath.indexOf(path.join(projectConfig.projectRootPath, packageDir)) >= 0 || + filePath.indexOf(path.join(modulePath, packageDir)) >= 0; +} + +export function genTemporaryModuleCacheDirectoryForBundle(projectConfig: any) { + const buildDirArr: string[] = projectConfig.aceModuleBuild.split(path.sep); + const abilityDir: string = buildDirArr[buildDirArr.length - 1]; + const temporaryModuleCacheDirPath: string = path.join(projectConfig.cachePath, TEMPORARY, abilityDir); + mkdirsSync(temporaryModuleCacheDirPath); + + return temporaryModuleCacheDirPath; +} + +export function isSpecifiedExt(filePath: string, fileExtendName: string) { + return path.extname(filePath) === fileExtendName; +} + +export function genCachePath(tailName: string, projectConfig: any, logger: any): string { + const pathName: string = projectConfig.cachePath !== undefined ? + path.join(projectConfig.cachePath, TEMPORARY, tailName) : path.join(projectConfig.aceModuleBuild, tailName); + mkdirsSync(path.dirname(pathName)); + + validateFilePathLength(pathName, logger); + return pathName; +} + +export function isTsOrEtsSourceFile(file: string): boolean { + return /(? { - return (node: ts.SourceFile) => { - if (process.env.compiler === BUILD_ON) { - generateSourceFilesToTemporary(node); - return node; - } else { - return node; - } - }; - }; -} +/* + * Copyright (c) 2023 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 { + readAppResource, + projectConfig +} from '../../../main'; +import { + getEntryObj, + workerFile +} from './process_project_config'; + +export function initConfig() { + getEntryObj(); + if (process.env.appResource) { + readAppResource(process.env.appResource); + } + return { + entryObj: projectConfig.entryObj, + cardEntryObj: projectConfig.cardEntryObj, + workerFile: workerFile + }; +} + diff --git a/compiler/src/fast_build/common/process_project_config.ts b/compiler/src/fast_build/common/process_project_config.ts new file mode 100644 index 0000000000000000000000000000000000000000..ac205bf345553223b77408b355f272212e3f33b0 --- /dev/null +++ b/compiler/src/fast_build/common/process_project_config.ts @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2023 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 fs from 'fs'; +import path from 'path'; + +const { + projectConfig, + loadEntryObj, + abilityConfig, + initBuildInfo, + readWorkerFile, + loadWorker, + readPatchConfig, + loadModuleInfo +} = require('../../../main.js'); + +export let workerFile = null; +export function getEntryObj() { + loadEntryObj(projectConfig); + initBuildInfo(); + readPatchConfig(); + loadModuleInfo(projectConfig); + workerFile = readWorkerFile(); + if (!projectConfig.isPreview) { + loadWorker(projectConfig, workerFile); + } + projectConfig.entryObj = Object.keys(projectConfig.entryObj).reduce((newEntry, key) => { + const newKey: string = key.replace(/^\.\//, ''); + newEntry[newKey] = projectConfig.entryObj[key].replace('?entry', ''); + return newEntry; + }, {}); +} + +export function setCopyPluginConfig(projectConfig: any, appResource: string) { + const copyPluginPattrens: object[] = []; + const BUILD_SHARE_PATH: string = '../share'; + copyPluginPattrens.push({ + src: [ + path.resolve(projectConfig.projectPath, '**/*'), + '!**/*.ets', + '!**/*.ts', + '!**/*.js', + `!${projectConfig.buildPath}` + ], + dest: projectConfig.buildPath + }); + const sharePath: string = path.resolve(projectConfig.projectPath, BUILD_SHARE_PATH); + if (fs.existsSync(sharePath)) { + copyPluginPattrens.push({ + src: [ + path.resolve(projectConfig.projectPath, BUILD_SHARE_PATH, '**/*'), + '!**/*.ets', + '!**/*.ts', + '!**/*.js' + ], + dest: path.resolve(projectConfig.buildPath, BUILD_SHARE_PATH), + }); + } + if (abilityConfig.abilityType === 'page') { + if (fs.existsSync(projectConfig.manifestFilePath)) { + copyPluginPattrens.push({ + src: projectConfig.manifestFilePath, + dest: projectConfig.buildPath + }); + } else if (fs.existsSync(projectConfig.aceConfigPath)) { + copyPluginPattrens.push({ + src: projectConfig.aceConfigPath, + dest: projectConfig.buildPath + }); + } + } + if (appResource && fs.existsSync(appResource) && !projectConfig.xtsMode && + projectConfig.isPreview) { + copyPluginPattrens.push({ + src: path.resolve(__dirname, appResource), + dest: path.resolve(__dirname, projectConfig.cachePath) + }); + } + return copyPluginPattrens; +} diff --git a/compiler/src/fast_build/common/rollup-plugin-watch-change.ts b/compiler/src/fast_build/common/rollup-plugin-watch-change.ts new file mode 100644 index 0000000000000000000000000000000000000000..0206b4190446dba55aae79a9eee82de8f84de7c0 --- /dev/null +++ b/compiler/src/fast_build/common/rollup-plugin-watch-change.ts @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2023 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 { + shouldWriteChangedList, + writeFileSync, + getHotReloadFiles +} from '../../utils'; +import { projectConfig } from '../../../main'; +import { + incrementWatchFile, + hotReloadSupportFiles +} from '../../ets_checker'; + +export function watchChangeFiles() { + function addFileToCache(this: any, key: string, id: string) { + let modifiedFiles: string[] = []; + if (this.cache && this.cache.has(key)) { + modifiedFiles = this.cache.get(key); + modifiedFiles.push(id); + } else { + modifiedFiles.push(id); + } + this.cache.set(key, modifiedFiles); + } + return { + name: 'watchChangedFiles', + watchChange(id: string, change: {event: 'create' | 'update' | 'delete'}): void { + if (change.event === 'update') { + addFileToCache.call(this, 'watchModifiedFiles', id); + } + if (['create', 'delete'].includes(change.event)) { + addFileToCache.call(this, 'watchRemovedFiles', id); + } + }, + beforeBuild() { + this.cache.set('watchChangedFilesCache', 'watchChangedFiles'); + const watchModifiedFiles: string[] = this.cache.get('watchModifiedFiles') || []; + const watchRemovedFiles: string[] = this.cache.get('watchRemovedFiles') || []; + if (shouldWriteChangedList(watchModifiedFiles, watchRemovedFiles)) { + writeFileSync(projectConfig.changedFileList, JSON.stringify( + getHotReloadFiles(watchModifiedFiles, watchRemovedFiles, hotReloadSupportFiles))); + } + incrementWatchFile(watchModifiedFiles, watchRemovedFiles); + } + }; +} diff --git a/compiler/src/fast_build/ets_ui/rollup-plugin-ets-checker.ts b/compiler/src/fast_build/ets_ui/rollup-plugin-ets-checker.ts new file mode 100644 index 0000000000000000000000000000000000000000..daf52a9d54eb066becf9f6fa7e04195215864c13 --- /dev/null +++ b/compiler/src/fast_build/ets_ui/rollup-plugin-ets-checker.ts @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2023 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 path from 'path'; + +import { initConfig } from '../common/init_config'; +import { projectConfig } from '../../../main'; +import { + serviceChecker, + watchChecker +} from '../../ets_checker'; + +export function etsChecker() { + let executedOnce: boolean = false; + return { + name: 'etsChecker', + buildStart() { + if (executedOnce) { + return; + } + Object.assign(projectConfig, this.share.projectConfig); + Object.assign(this.share.projectConfig, { + compileHar: projectConfig.compileHar, + compileShared: projectConfig.compileShared, + moduleRootPath: projectConfig.moduleRootPath, + buildPath: projectConfig.buildPath + }); + initConfig(); + const logger = this.share.getLogger('etsChecker'); + const rootFileNames: string[] = []; + Object.values(projectConfig.entryObj).forEach((fileName: string) => { + rootFileNames.push(path.resolve(fileName)); + }); + if (process.env.watchMode === 'true') { + executedOnce = true; + watchChecker(rootFileNames, logger); + } else { + serviceChecker(rootFileNames, logger); + } + } + }; +} + diff --git a/compiler/src/fast_build/ets_ui/rollup-plugin-ets-typescript.ts b/compiler/src/fast_build/ets_ui/rollup-plugin-ets-typescript.ts new file mode 100644 index 0000000000000000000000000000000000000000..9e64ba994aa1ba4865ff70d4b5234429ab7d7163 --- /dev/null +++ b/compiler/src/fast_build/ets_ui/rollup-plugin-ets-typescript.ts @@ -0,0 +1,143 @@ +/* + * Copyright (c) 2023 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 ts from 'typescript'; +import path from 'path'; +import fs from 'fs'; +import { createFilter } from '@rollup/pluginutils'; +import MagicString from 'magic-string'; + +import { + LogInfo, + componentInfo, + emitLogInfo, + getTransformLog, + genTemporaryPath, + writeFileSync +} from '../../utils'; +import { + preprocessExtend, + preprocessNewExtend, + validateUISyntax, + propertyCollection, + linkCollection, + resetComponentCollection +} from '../../validate_ui_syntax'; +import { + processUISyntax, + resetLog, + transformLog +} from '../../process_ui_syntax'; +import { + abilityConfig, + projectConfig, + abilityPagesFullPath +} from '../../../main'; +import { ESMODULE, JSBUNDLE } from '../../pre_define'; +import { parseVisual } from '../../process_visual'; + +const filter:any = createFilter(/(? = new Map(); + return { + name: 'etsTransform', + transform: transform, + moduleParsed(moduleInfo) { + if (projectConfig.compileHar) { + if (moduleInfo.id && !moduleInfo.id.match(/node_modules/)) { + const filePath: string = moduleInfo.id; + const jsCacheFilePath: string = genTemporaryPath(filePath, projectConfig.moduleRootPath, + process.env.cachePath, projectConfig); + const jsBuildFilePath: string = genTemporaryPath(filePath, projectConfig.moduleRootPath, + projectConfig.buildPath, projectConfig, true); + if (filePath.match(/\.e?ts$/)) { + incrementalFileInHar.set(jsCacheFilePath.replace(/\.ets$/, '.d.ets').replace(/\.ts$/, '.d.ts'), + jsBuildFilePath.replace(/\.ets$/, '.d.ets').replace(/\.ts$/, '.d.ts')); + incrementalFileInHar.set(jsCacheFilePath.replace(/\.e?ts$/, '.js'), jsBuildFilePath.replace(/\.e?ts$/, '.js')); + } else { + incrementalFileInHar.set(jsCacheFilePath, jsBuildFilePath); + } + } + } + }, + afterBuildEnd() { + if (projectConfig.compileHar) { + incrementalFileInHar.forEach((jsBuildFilePath, jsCacheFilePath) => { + const sourceCode: string = fs.readFileSync(jsCacheFilePath, 'utf-8'); + writeFileSync(jsBuildFilePath, sourceCode); + }); + } + } + }; +} + +function transform(code: string, id: string) { + if (!filter(id)) { + return null; + } + + if (projectConfig.compileMode === ESMODULE) { + compilerOptions['importsNotUsedAsValues'] = 'remove'; + } + + const logger = this.share.getLogger('etsTransform'); + + const magicString = new MagicString(code); + const newContent: string = preProcess(code, id, this.getModuleInfo(id).isEntry, logger); + + const result: ts.TranspileOutput = ts.transpileModule(newContent, { + compilerOptions: compilerOptions, + fileName: id, + transformers: { before: [ processUISyntax(null) ] } + }); + + resetCollection(); + if (transformLog && transformLog.errors.length) { + emitLogInfo(logger, getTransformLog(transformLog), true, id); + resetLog(); + } + + return { + code: result.outputText, + map: result.sourceMapText ? JSON.parse(result.sourceMapText) : magicString.generateMap() + }; +} + +function preProcess(code: string, id: string, isEntry: boolean, logger: any): string { + if (/\.ets$/.test(id)) { + let content = preprocessExtend(code); + content = preprocessNewExtend(content); + const fileQuery: string = isEntry && !abilityPagesFullPath.includes(id) ? '?entry' : ''; + const log: LogInfo[] = validateUISyntax(code, content, id, fileQuery); + content = parseVisual(id, fileQuery, content, log, code, true); + if (log.length) { + emitLogInfo(logger, log, true, id); + } + return content; + } + return code; +} + +function resetCollection() { + componentInfo.id = 0; + propertyCollection.clear(); + linkCollection.clear(); + resetComponentCollection(); +} diff --git a/compiler/src/fast_build/system_api/rollup-plugin-system-api.ts b/compiler/src/fast_build/system_api/rollup-plugin-system-api.ts new file mode 100644 index 0000000000000000000000000000000000000000..88bf5ed17352394bb7a017a1b42882b6194a2cec --- /dev/null +++ b/compiler/src/fast_build/system_api/rollup-plugin-system-api.ts @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2023 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 MagicString from 'magic-string'; +import { createFilter } from '@rollup/pluginutils'; + +import { + NATIVE_MODULE, + SYSTEM_PLUGIN, + OHOS_PLUGIN +} from '../../pre_define'; +import { + systemModules, + projectConfig +} from '../../../main'; +import { writeUseOSFiles } from '../../utils'; + +const filter: any = createFilter(/(? = new Set(); + return { + name: 'apiTransform', + transform(code: string, id: string) { + const magicString = new MagicString(code); + if (filter(id)) { + code = processSystemApi(code, id); + code = proceseLibso(code, id, useOSFiles); + } + return { + code: code, + map: magicString.generateMap() + }; + }, + buildEnd() { + if (projectConfig.isPreview && projectConfig.aceSoPath && + useOSFiles && useOSFiles.size > 0) { + writeUseOSFiles(useOSFiles); + } + } + }; +} + +function processSystemApi(content: string, sourcePath: string): string { + const REG_SYSTEM: RegExp = + /import\s+(.+)\s+from\s+['"]@(system|ohos)\.(\S+)['"]|import\s+(.+)\s*=\s*require\(\s*['"]@(system|ohos)\.(\S+)['"]\s*\)/g; + return content.replace(REG_SYSTEM, (item, item1, item2, item3, item4, item5, item6) => { + const moduleType: string = item2 || item5; + const systemKey: string = item3 || item6; + const systemValue: string = item1 || item4; + const systemModule: string = `${moduleType}.${systemKey}`; + checkModuleExist(systemModule, sourcePath); + if (NATIVE_MODULE.has(systemModule)) { + item = `var ${systemValue} = globalThis.requireNativeModule('${moduleType}.${systemKey}')`; + } else if (moduleType === SYSTEM_PLUGIN) { + item = `var ${systemValue} = isSystemplugin('${systemKey}', '${SYSTEM_PLUGIN}') ? ` + + `globalThis.systemplugin.${systemKey} : globalThis.requireNapi('${systemKey}')`; + } else if (moduleType === OHOS_PLUGIN) { + item = `var ${systemValue} = globalThis.requireNapi('${systemKey}') || ` + + `(isSystemplugin('${systemKey}', '${OHOS_PLUGIN}') ? ` + + `globalThis.ohosplugin.${systemKey} : isSystemplugin('${systemKey}', '${SYSTEM_PLUGIN}') ` + + `? globalThis.systemplugin.${systemKey} : undefined)`; + } + return item; + }); +} + +function checkModuleExist(systemModule: string, sourcePath: string): void { + const module: string = `@${systemModule.trim()}.d.ts`; + if (/\.js$/.test(sourcePath) && !systemModules.includes(module)) { + const message: string = + `Cannot find module '${module}' or its corresponding type declarations.`; + console.error(`BUILDERROR File: ${sourcePath}\n ${message}`); + } +} + +function proceseLibso(content: string, sourcePath: string, useOSFiles: Set): string { + const REG_LIB_SO: RegExp = + /import\s+(.+)\s+from\s+['"]lib(\S+)\.so['"]|import\s+(.+)\s*=\s*require\(\s*['"]lib(\S+)\.so['"]\s*\)/g; + return content.replace(REG_LIB_SO, (_, item1, item2, item3, item4) => { + useOSFiles.add(sourcePath); + const libSoValue: string = item1 || item3; + const libSoKey: string = item2 || item4; + return projectConfig.bundleName && projectConfig.moduleName + ? `var ${libSoValue} = globalThis.requireNapi("${libSoKey}", true, "${projectConfig.bundleName}/${projectConfig.moduleName}");` + : `var ${libSoValue} = globalThis.requireNapi("${libSoKey}", true);`; + }); +} diff --git a/compiler/src/gen_abc.ts b/compiler/src/gen_abc.ts index 0ba2c0277bf34b9ad6e0d08e8d70c546562ea5e9..ecbe0d8566b754d19441ada4b5bfb55f2d0f0242 100644 --- a/compiler/src/gen_abc.ts +++ b/compiler/src/gen_abc.ts @@ -19,9 +19,7 @@ import cluster from 'cluster'; import { logger } from './compile_info'; import { SUCCESS, - FAIL, - TS2ABC, - ES2ABC + FAIL } from './pre_define'; const red: string = '\u001b[31m'; @@ -33,31 +31,13 @@ function js2abcByWorkers(jsonInput: string, cmd: string): Promise { const input: string = inputPaths[i].path.replace(/\.temp\.js$/, "_.js"); const cacheOutputPath: string = inputPaths[i].cacheOutputPath; const cacheAbcFilePath: string = cacheOutputPath.replace(/\.temp\.js$/, ".abc"); - const singleCmd: any = `${cmd} "${cacheOutputPath}" -o "${cacheAbcFilePath}" --source-file "${input}"`; + const sourceFile: string = inputPaths[i].sourceFile; + const singleCmd: any = `${cmd} "${cacheOutputPath}" -o "${cacheAbcFilePath}" --source-file "${sourceFile}"`; logger.debug('gen abc cmd is: ', singleCmd, ' ,file size is:', inputPaths[i].size, ' byte'); try { childProcess.execSync(singleCmd); } catch (e) { - logger.error(red, `ETS:ERROR Failed to convert file ${input} to abc `, reset); - process.exit(FAIL); - } - } - - return; -} - -function es2abcByWorkers(jsonInput: string, cmd: string): Promise { - const inputPaths: any = JSON.parse(jsonInput); - for (let i = 0; i < inputPaths.length; ++i) { - const input: string = inputPaths[i].path.replace(/\.temp\.js$/, "_.js"); - const cacheOutputPath: string = inputPaths[i].cacheOutputPath; - const cacheAbcFilePath: string = cacheOutputPath.replace(/\.temp\.js$/, ".abc"); - const singleCmd: any = `${cmd} "${cacheOutputPath}" --output "${cacheAbcFilePath}" --source-file "${input}"`; - logger.debug('gen abc cmd is: ', singleCmd, ' ,file size is:', inputPaths[i].size, ' byte'); - try { - childProcess.execSync(singleCmd); - } catch (e) { - logger.error(red, `ETS:ERROR Failed to convert file ${input} to abc `, reset); + logger.debug(red, `ArkTS:ERROR Failed to convert file ${input} to abc. Error message: ${e} `, reset); process.exit(FAIL); } } @@ -69,13 +49,6 @@ logger.debug('worker data is: ', JSON.stringify(process.env)); logger.debug('gen_abc isWorker is: ', cluster.isWorker); if (cluster.isWorker && process.env['inputs'] !== undefined && process.env['cmd'] !== undefined) { logger.debug('==>worker #', cluster.worker.id, 'started!'); - if (process.env.panda === TS2ABC) { - js2abcByWorkers(process.env['inputs'], process.env['cmd']); - } else if (process.env.panda === ES2ABC || process.env.panda === 'undefined' || process.env.panda === undefined) { - es2abcByWorkers(process.env['inputs'], process.env['cmd']); - } else { - logger.error(red, `ETS:ERROR please set panda module`, reset); - process.exit(FAIL); - } + js2abcByWorkers(process.env['inputs'], process.env['cmd']); process.exit(SUCCESS); } diff --git a/compiler/src/gen_abc_plugin.ts b/compiler/src/gen_abc_plugin.ts index 1c258548e2d677e2035477afbcfcad5601e81afd..617e6ae48e315153b247200b059615ddb1a4e4dd 100644 --- a/compiler/src/gen_abc_plugin.ts +++ b/compiler/src/gen_abc_plugin.ts @@ -18,45 +18,80 @@ import * as path from 'path'; import cluster from 'cluster'; import process from 'process'; import os from 'os'; +import events from 'events'; import Compiler from 'webpack/lib/Compiler'; import { logger } from './compile_info'; +import * as childProcess from 'child_process'; import { toUnixPath, toHashData, - genTemporaryPath, - genBuildPath, - genAbcFileName, mkdirsSync, - genSourceMapFileName, - checkNodeModulesFile, - compareNodeVersion, - removeDir + nodeLargeOrEqualTargetVersion, + removeDir, + validateFilePathLength, + unlinkSync, + isPackageModulesFile, + genTemporaryPath } from './utils'; +import { + buildCachePath, + genAbcFileName, + genBuildPath, + genMergeProtoFileName, + genProtoFileName, + getOhmUrlByFilepath, + getPackageInfo, + isEs2Abc, + isTs2Abc, + newSourceMaps, + removeDuplicateInfo +} from './ark_utils'; import { projectConfig } from '../main'; import { ESMODULE, JSBUNDLE, NODE_MODULES, - ENTRY_TXT, + ES2ABC, + EXTNAME_D_ETS, + EXTNAME_D_TS, EXTNAME_ETS, EXTNAME_JS, EXTNAME_TS, EXTNAME_MJS, EXTNAME_CJS, - EXTNAME_D_TS, - FAIL, + EXTNAME_JSON, EXTNAME_JS_MAP, - TS2ABC, - ES2ABC, - TEMPORARY, + FAIL, + MODULELIST_JSON, + MODULES_ABC, + PREBUILDMODE_JSON, SUCCESS, - MODULELIST_JSON + SOURCEMAPS_JSON, + SOURCEMAPS, + TEMPORARY, + TS2ABC, + PROTO_FILESINFO_TXT, + NPMENTRIES_TXT, + EXTNAME_PROTO_BIN, + FILESINFO_TXT, + MANAGE_WORKERS_SCRIPT, + MAX_WORKER_NUMBER, + GEN_ABC_SCRIPT, + GEN_MODULE_ABC_SCRIPT, + AOT_FULL, + AOT_PARTIAL, + PACKAGES } from './pre_define'; -import { getOhmUrlByFilepath } from './resolve_ohm_url'; -import { generateMergedAbc } from './gen_merged_abc'; +import { + generateMergedAbc, + generateNpmEntriesInfo +} from './gen_merged_abc'; +import { + generateAot, + generateBuiltinAbc, + FaultHandler +} from './gen_aot' -const genAbcScript: string = 'gen_abc.js'; -const genModuleAbcScript: string = 'gen_module_abc.js'; let output: string; let isWin: boolean = false; let isMac: boolean = false; @@ -64,11 +99,11 @@ let isDebug: boolean = false; let arkDir: string; let nodeJs: string; -let delayCount = 0; interface File { path: string, size: number, - cacheOutputPath: string + cacheOutputPath: string, + sourceFile: string } let intermediateJsBundle: Array = []; let fileterIntermediateJsBundle: Array = []; @@ -80,7 +115,9 @@ let entryInfos: Map = new Map(); let hashJsonObject = {}; let moduleHashJsonObject = {}; let buildPathInfo: string = ''; -let buildMapFileList: Array = []; +let buildMapFileList: Set = new Set(); +let isHotReloadFirstBuild: boolean = true; +let protoFilePath: string = ''; const red: string = '\u001b[31m'; const reset: string = '\u001b[39m'; @@ -95,26 +132,29 @@ export class ModuleInfo { abcFilePath: string; isCommonJs: boolean; recordName: string; + sourceFile: string; + packageName: string; - constructor(filePath: string, tempFilePath: string, buildFilePath: string, abcFilePath: string, isCommonJs: boolean) { + constructor(filePath: string, tempFilePath: string, buildFilePath: string, + abcFilePath: string, packageName: string, isCommonJs: boolean) { this.filePath = filePath; this.tempFilePath = tempFilePath; this.buildFilePath = buildFilePath; this.abcFilePath = abcFilePath; + this.packageName = packageName; this.isCommonJs = isCommonJs; - this.recordName = getOhmUrlByFilepath(filePath); + this.recordName = getOhmUrlByFilepath(filePath, projectConfig, logger); + this.sourceFile = filePath.replace(projectConfig.projectRootPath + path.sep, ''); } } export class EntryInfo { npmInfo: string; - abcFileName: string; buildPath: string; entry: string; - constructor(npmInfo: string, abcFileName: string, buildPath: string, entry: string) { + constructor(npmInfo: string, buildPath: string, entry: string) { this.npmInfo = npmInfo; - this.abcFileName = abcFileName; this.buildPath = buildPath; this.entry = entry; } @@ -135,7 +175,7 @@ export class GenAbcPlugin { isMac = true; } else { if (!fs.existsSync(path.resolve(arkDir, 'build'))) { - logger.error(red, 'ETS:ERROR find build fail', reset); + logger.error(red, 'ArkTS:ERROR find build fail', reset); process.exitCode = FAIL; return; } @@ -147,17 +187,28 @@ export class GenAbcPlugin { return; } - // case ESMODULE - // | --- es2abc -- debug -- not removeDir - // | --- es2abc -- release -- removeDir - // | --- ts2abc -- removeDir if (projectConfig.compileMode === ESMODULE) { - if ((projectConfig.buildArkMode !== 'debug' && process.env.panda === ES2ABC) || process.env.panda === TS2ABC) { - removeDir(output); - removeDir(projectConfig.nodeModulesPath); + if (projectConfig.cachePath && !projectConfig.xtsMode) { + let cachedJson: any = {}; + const CACHED_BUILDMODE: string = path.join(projectConfig.cachePath, PREBUILDMODE_JSON); + validateFilePathLength(CACHED_BUILDMODE, logger); + cachedJson["buildMode"] = projectConfig.buildArkMode; + fs.writeFile(CACHED_BUILDMODE, JSON.stringify(cachedJson, null, 2), 'utf-8', + (err) => { + if (err) { + logger.error(red, `ArkTS:ERROR Failed to write buildMode.`, reset); + } + }); } + + // clear output dir + removeDir(output); + removeDir(projectConfig.nodeModulesPath); } + // for preview mode max listeners + events.EventEmitter.defaultMaxListeners = 100; + compiler.hooks.compilation.tap('GenAbcPlugin', (compilation) => { if (projectConfig.compileMode === JSBUNDLE || projectConfig.compileMode === undefined) { return; @@ -197,8 +248,17 @@ export class GenAbcPlugin { if (projectConfig.compileMode === ESMODULE) { return; } + if (intermediateJsBundle.length === 0) { + return; + } buildPathInfo = output; - judgeWorkersToGenAbc(invokeWorkersToGenAbc); + if (isTs2Abc(projectConfig) || process.env.minPlatformVersion === "8") { + invokeWorkersToGenAbc(); + } else if (isEs2Abc(projectConfig)){ + generateAbcByEs2AbcOfBundleMode(intermediateJsBundle); + } else { + logger.error(red, `ArkTS:ERROR please set panda module`, reset); + } }); } } @@ -207,69 +267,113 @@ function clearGlobalInfo() { // fix bug of multi trigger if (process.env.watchMode !== 'true') { intermediateJsBundle = []; + moduleInfos = []; + entryInfos = new Map(); } - moduleInfos = []; fileterIntermediateJsBundle = []; filterModuleInfos = []; commonJsModuleInfos = []; ESMModuleInfos = []; - entryInfos = new Map(); hashJsonObject = {}; moduleHashJsonObject = {}; - buildMapFileList = []; + buildMapFileList = new Set(); } -function getEntryInfo(tempFilePath: string, resourceResolveData: any): void { +function getEntryInfo(filePath: string, resourceResolveData: any): string { if (!resourceResolveData.descriptionFilePath) { return; } - const packageName: string = resourceResolveData.descriptionFileData['name']; + + let isEntry: boolean = false; + let mainFileds: Set = getEntryCandidatesFromPackageJson(resourceResolveData); + for (let value of mainFileds.values()) { + if (toUnixPath(filePath) === value) { + isEntry = true; + break; + } + } const packageJsonPath: string = resourceResolveData.descriptionFilePath; let npmInfoPath: string = path.resolve(packageJsonPath, '..'); + + let entry: string = toUnixPath(filePath.replace(npmInfoPath, '')); + if (entry.startsWith('/')) { + entry = entry.slice(1, entry.length); + } + const fakeEntryPath: string = path.resolve(npmInfoPath, 'fake.js'); - const tempFakeEntryPath: string = genTemporaryPath(fakeEntryPath, projectConfig.projectPath, process.env.cachePath); - const buildFakeEntryPath: string = genBuildPath(fakeEntryPath, projectConfig.projectPath, projectConfig.buildPath); + const tempFakeEntryPath: string = genTemporaryPath(fakeEntryPath, projectConfig.projectPath, process.env.cachePath, + projectConfig); + const buildFakeEntryPath: string = genBuildPath(fakeEntryPath, projectConfig.projectPath, projectConfig.buildPath, + projectConfig); npmInfoPath = toUnixPath(path.resolve(tempFakeEntryPath, '..')); const buildNpmInfoPath: string = toUnixPath(path.resolve(buildFakeEntryPath, '..')); - if (entryInfos.has(npmInfoPath)) { - return; + if (!entryInfos.has(npmInfoPath) && isEntry) { + const entryInfo: EntryInfo = new EntryInfo(npmInfoPath, buildNpmInfoPath, entry); + entryInfos.set(npmInfoPath, entryInfo); } - let abcFileName: string = genAbcFileName(tempFilePath); - const abcFilePaths: string[] = abcFileName.split(NODE_MODULES); - abcFileName = [NODE_MODULES, abcFilePaths[abcFilePaths.length - 1]].join(path.sep); - abcFileName = toUnixPath(abcFileName); + return buildNpmInfoPath; +} - const packagePaths: string[] = tempFilePath.split(NODE_MODULES); - const entryPaths: string[] = packagePaths[packagePaths.length - 1].split(packageName); - let entry: string = toUnixPath(entryPaths[entryPaths.length - 1]); - if (entry.startsWith('/')) { - entry = entry.slice(1, entry.length); +function getEntryCandidatesFromPackageJson(resourceResolveData: any): Set{ + let descriptionFileData: any = resourceResolveData.descriptionFileData; + let packagePath: string = path.resolve(resourceResolveData.descriptionFilePath, '..'); + let mainFileds: Set = new Set(); + if (descriptionFileData.browser) { + if (typeof descriptionFileData.browser === 'string') { + mainFileds.add(toUnixPath(path.join(packagePath, descriptionFileData.browser))); + } else { + Object.keys(descriptionFileData.browser).forEach(key => { + if (typeof key === 'string' && typeof descriptionFileData.browser[key] === 'string') { + mainFileds.add(toUnixPath(path.join(packagePath, descriptionFileData.browser[key]))); + } + }); + } + } + if (descriptionFileData.module) { + mainFileds.add(toUnixPath(path.join(packagePath, descriptionFileData.module))); + } + if (descriptionFileData.main) { + mainFileds.add(toUnixPath(path.join(packagePath, descriptionFileData.main))); } - const entryInfo: EntryInfo = new EntryInfo(npmInfoPath, abcFileName, buildNpmInfoPath, entry); - entryInfos.set(npmInfoPath, entryInfo); + if (mainFileds.size === 0) { + mainFileds.add(toUnixPath(path.join(packagePath, 'index.js'))); + mainFileds.add(toUnixPath(path.join(packagePath, 'index.ets'))); + mainFileds.add(toUnixPath(path.join(packagePath, 'index.ts'))); + } + + return mainFileds; } function processNodeModulesFile(filePath: string, tempFilePath: string, buildFilePath: string, abcFilePath: string, nodeModulesFile: Array, module: any): void { - getEntryInfo(tempFilePath, module.resourceResolveData); + let npmPkgPath: string = getEntryInfo(filePath, module.resourceResolveData); + const buildNpmPkgPath: string = npmPkgPath.replace(toUnixPath(projectConfig.nodeModulesPath), ''); + const npmPkgName: string = toUnixPath(path.join(PACKAGES, buildNpmPkgPath)).replace(NODE_MODULES, PACKAGES); + const descriptionFileData: any = module.resourceResolveData.descriptionFileData; if (descriptionFileData && descriptionFileData['type'] && descriptionFileData['type'] === 'module') { - const tempModuleInfo: ModuleInfo = new ModuleInfo(filePath, tempFilePath, buildFilePath, abcFilePath, false); + const tempModuleInfo: ModuleInfo = new ModuleInfo(filePath, tempFilePath, buildFilePath, abcFilePath, npmPkgName, false); moduleInfos.push(tempModuleInfo); nodeModulesFile.push(tempFilePath); } else if (filePath.endsWith(EXTNAME_MJS)) { - const tempModuleInfo: ModuleInfo = new ModuleInfo(filePath, tempFilePath, buildFilePath, abcFilePath, false); + const tempModuleInfo: ModuleInfo = new ModuleInfo(filePath, tempFilePath, buildFilePath, abcFilePath, npmPkgName, false); moduleInfos.push(tempModuleInfo); nodeModulesFile.push(tempFilePath); } else { - const tempModuleInfo: ModuleInfo = new ModuleInfo(filePath, tempFilePath, buildFilePath, abcFilePath, true); + const tempModuleInfo: ModuleInfo = new ModuleInfo(filePath, tempFilePath, buildFilePath, abcFilePath, npmPkgName, true); moduleInfos.push(tempModuleInfo); nodeModulesFile.push(tempFilePath); } - buildMapFileList.push(genSourceMapFileName(buildFilePath)); + if (!filePath.endsWith(EXTNAME_JSON)) { + buildMapFileList.add(toUnixPath(filePath.replace(projectConfig.projectRootPath + path.sep, ''))); + } } function processEtsModule(filePath: string, tempFilePath: string, buildFilePath: string, nodeModulesFile: Array, module: any): void { + // skip declaration modules + if (filePath.endsWith(EXTNAME_D_ETS)) { + return; + } if (projectConfig.processTs === true) { tempFilePath = tempFilePath.replace(/\.ets$/, EXTNAME_TS); buildFilePath = buildFilePath.replace(/\.ets$/, EXTNAME_TS); @@ -278,32 +382,34 @@ function processEtsModule(filePath: string, tempFilePath: string, buildFilePath: buildFilePath = buildFilePath.replace(/\.ets$/, EXTNAME_JS); } const abcFilePath: string = genAbcFileName(tempFilePath); - if (checkNodeModulesFile(filePath, projectConfig.projectPath)) { + if (isPackageModulesFile(filePath, projectConfig)) { processNodeModulesFile(filePath, tempFilePath, buildFilePath, abcFilePath, nodeModulesFile, module); } else { - const tempModuleInfo: ModuleInfo = new ModuleInfo(filePath, tempFilePath, buildFilePath, abcFilePath, false); + const moduleName: string = getPackageInfo(projectConfig.aceModuleJsonPath)[1]; + const tempModuleInfo: ModuleInfo = new ModuleInfo(filePath, tempFilePath, buildFilePath, abcFilePath, moduleName, false); moduleInfos.push(tempModuleInfo); } - buildMapFileList.push(genSourceMapFileName(buildFilePath)); -} - -function processDtsModule(filePath: string, tempFilePath: string, buildFilePath: string, nodeModulesFile: Array, module: any): void { - return; + buildMapFileList.add(toUnixPath(filePath.replace(projectConfig.projectRootPath + path.sep, ''))); } function processTsModule(filePath: string, tempFilePath: string, buildFilePath: string, nodeModulesFile: Array, module: any): void { + // skip declaration modules + if (filePath.endsWith(EXTNAME_D_TS)) { + return; + } if (projectConfig.processTs === false) { tempFilePath = tempFilePath.replace(/\.ts$/, EXTNAME_JS); buildFilePath = buildFilePath.replace(/\.ts$/, EXTNAME_JS); } const abcFilePath: string = genAbcFileName(tempFilePath); - if (checkNodeModulesFile(filePath, projectConfig.projectPath)) { + if (isPackageModulesFile(filePath, projectConfig)) { processNodeModulesFile(filePath, tempFilePath, buildFilePath, abcFilePath, nodeModulesFile, module); } else { - const tempModuleInfo: ModuleInfo = new ModuleInfo(filePath, tempFilePath, buildFilePath, abcFilePath, false); + const moduleName: string = getPackageInfo(projectConfig.aceModuleJsonPath)[1]; + const tempModuleInfo: ModuleInfo = new ModuleInfo(filePath, tempFilePath, buildFilePath, abcFilePath, moduleName, false); moduleInfos.push(tempModuleInfo); } - buildMapFileList.push(genSourceMapFileName(buildFilePath)); + buildMapFileList.add(toUnixPath(filePath.replace(projectConfig.projectRootPath + path.sep, ''))); } function processJsModule(filePath: string, tempFilePath: string, buildFilePath: string, nodeModulesFile: Array, module: any): void { @@ -315,18 +421,45 @@ function processJsModule(filePath: string, tempFilePath: string, buildFilePath: fs.copyFileSync(filePath, tempFilePath); } const abcFilePath: string = genAbcFileName(tempFilePath); - if (checkNodeModulesFile(filePath, projectConfig.projectPath)) { + if (isPackageModulesFile(filePath, projectConfig)) { + processNodeModulesFile(filePath, tempFilePath, buildFilePath, abcFilePath, nodeModulesFile, module); + } else { + const moduleName: string = getPackageInfo(projectConfig.aceModuleJsonPath)[1]; + const tempModuleInfo: ModuleInfo = new ModuleInfo(filePath, tempFilePath, buildFilePath, abcFilePath, moduleName, false); + moduleInfos.push(tempModuleInfo); + } + buildMapFileList.add(toUnixPath(filePath.replace(projectConfig.projectRootPath + path.sep, ''))); +} + +function processJsonModule(filePath: string, tempFilePath: string, buildFilePath: string, nodeModulesFile: Array, module: any): void { + const abcFilePath: string = "NA"; + if (isPackageModulesFile(filePath, projectConfig)) { processNodeModulesFile(filePath, tempFilePath, buildFilePath, abcFilePath, nodeModulesFile, module); } else { - const tempModuleInfo: ModuleInfo = new ModuleInfo(filePath, tempFilePath, buildFilePath, abcFilePath, false); + const moduleName: string = getPackageInfo(projectConfig.aceModuleJsonPath)[1]; + const tempModuleInfo: ModuleInfo = new ModuleInfo(filePath, tempFilePath, buildFilePath, abcFilePath, moduleName, false); moduleInfos.push(tempModuleInfo); } - buildMapFileList.push(genSourceMapFileName(buildFilePath)); } +var cachedSourceMaps: Object; + +function updateCachedSourceMaps(): void { + const CACHED_SOURCEMAPS: string = path.join(process.env.cachePath, SOURCEMAPS_JSON); + validateFilePathLength(CACHED_SOURCEMAPS, logger); + if (!fs.existsSync(CACHED_SOURCEMAPS)) { + cachedSourceMaps = {}; + } else { + cachedSourceMaps = JSON.parse(fs.readFileSync(CACHED_SOURCEMAPS).toString()); + } + Object.keys(newSourceMaps).forEach(key => { + cachedSourceMaps[key] = newSourceMaps[key]; + }); +} function getCachedModuleList(): Array { const CACHED_MODULELIST_FILE: string = path.join(process.env.cachePath, MODULELIST_JSON); + validateFilePathLength(CACHED_MODULELIST_FILE, logger); if (!fs.existsSync(CACHED_MODULELIST_FILE)) { return []; } @@ -337,12 +470,35 @@ function getCachedModuleList(): Array { function updateCachedModuleList(moduleList: Array): void { const CACHED_MODULELIST_FILE: string = path.join(process.env.cachePath, MODULELIST_JSON); + validateFilePathLength(CACHED_MODULELIST_FILE, logger); + const CACHED_SOURCEMAPS: string = path.join(process.env.cachePath, SOURCEMAPS_JSON); + validateFilePathLength(CACHED_SOURCEMAPS, logger); let cachedJson: Object = {}; cachedJson["list"] = moduleList; fs.writeFile(CACHED_MODULELIST_FILE, JSON.stringify(cachedJson, null, 2), 'utf-8', - (err)=>{ + (err) => { + if (err) { + logger.error(red, `ArkTS:ERROR Failed to write module list.`, reset); + } + } + ); + fs.writeFile(CACHED_SOURCEMAPS, JSON.stringify(cachedSourceMaps, null, 2), 'utf-8', + (err) => { if (err) { - logger.error(red, `ETS:ERROR Failed to write module list.`, reset); + logger.error(red, `ArkTS:ERROR Failed to write cache sourceMaps json.`, reset); + } + } + ); +} + +function writeSourceMaps(): void { + mkdirsSync(projectConfig.buildPath); + let sourceMapFilePath: string = path.join(projectConfig.buildPath, SOURCEMAPS); + validateFilePathLength(sourceMapFilePath, logger); + fs.writeFile(sourceMapFilePath, JSON.stringify(cachedSourceMaps, null, 2), 'utf-8', + (err) => { + if (err) { + logger.error(red, `ArkTS:ERROR Failed to write sourceMaps.`, reset); } } ); @@ -353,80 +509,115 @@ function eliminateUnusedFiles(moduleList: Array): void{ if (cachedModuleList.length !== 0) { const eliminateFiles: Array = cachedModuleList.filter(m => !moduleList.includes(m)); eliminateFiles.forEach((file) => { - if (fs.existsSync(file)) { - fs.unlinkSync(file); - } + delete cachedSourceMaps[file]; }); } } -function handleFinishModules(modules, callback): any { +function handleFullModuleFiles(modules, callback): any { const nodeModulesFile: Array = []; modules.forEach(module => { if (module !== undefined && module.resourceResolveData !== undefined) { const filePath: string = module.resourceResolveData.path; - let tempFilePath = genTemporaryPath(filePath, projectConfig.projectPath, process.env.cachePath); + let tempFilePath = genTemporaryPath(filePath, projectConfig.projectPath, process.env.cachePath, projectConfig); if (tempFilePath.length === 0) { return; } - let buildFilePath: string = genBuildPath(filePath, projectConfig.projectPath, projectConfig.buildPath); + validateFilePathLength(tempFilePath, logger); + let buildFilePath: string = genBuildPath(filePath, projectConfig.projectPath, projectConfig.buildPath, + projectConfig); + validateFilePathLength(buildFilePath, logger); tempFilePath = toUnixPath(tempFilePath); buildFilePath = toUnixPath(buildFilePath); - if (filePath.endsWith(EXTNAME_ETS)) { - processEtsModule(filePath, tempFilePath, buildFilePath, nodeModulesFile, module); - } else if (filePath.endsWith(EXTNAME_D_TS)) { - processDtsModule(filePath, tempFilePath, buildFilePath, nodeModulesFile, module); - } else if (filePath.endsWith(EXTNAME_TS)) { - processTsModule(filePath, tempFilePath, buildFilePath, nodeModulesFile, module); - } else if (filePath.endsWith(EXTNAME_JS) || filePath.endsWith(EXTNAME_MJS) || filePath.endsWith(EXTNAME_CJS)) { - processJsModule(filePath, tempFilePath, buildFilePath, nodeModulesFile, module); - } else { - logger.error(red, `ETS:ERROR Cannot find resolve this file path: ${filePath}`, reset); - process.exitCode = FAIL; + + switch (path.extname(filePath)) { + case EXTNAME_ETS: { + processEtsModule(filePath, tempFilePath, buildFilePath, nodeModulesFile, module); + break; + } + case EXTNAME_TS: { + processTsModule(filePath, tempFilePath, buildFilePath, nodeModulesFile, module); + break; + } + case EXTNAME_JS: + case EXTNAME_MJS: + case EXTNAME_CJS: { + processJsModule(filePath, tempFilePath, buildFilePath, nodeModulesFile, module); + break; + } + case EXTNAME_JSON: { + processJsonModule(filePath, tempFilePath, buildFilePath, nodeModulesFile, module); + break; + } + default: { + logger.error(red, `ArkTS:ERROR Cannot find resolve this file path: ${filePath}`, reset); + process.exitCode = FAIL; + } } } }); - if (projectConfig.compileMode === ESMODULE && process.env.panda !== TS2ABC) { - if (projectConfig.buildArkMode === 'debug') { - eliminateUnusedFiles(buildMapFileList); - updateCachedModuleList(buildMapFileList); - } - generateMergedAbc(moduleInfos, entryInfos); + // for mergeabc source maps + if (projectConfig.buildArkMode === 'debug') { + const moduleList: Array = Array.from(buildMapFileList); + updateCachedSourceMaps(); + eliminateUnusedFiles(moduleList); + updateCachedModuleList(moduleList); + writeSourceMaps(); + } + + if (process.env.panda !== TS2ABC) { + const outputABCPath: string = path.join(projectConfig.buildPath, MODULES_ABC); + validateFilePathLength(outputABCPath, logger); + generateMergedAbc(moduleInfos, entryInfos, outputABCPath); clearGlobalInfo(); } else { - judgeModuleWorkersToGenAbc(invokeWorkersModuleToGenAbc); - processEntryToGenAbc(entryInfos); + invokeWorkersModuleToGenAbc(moduleInfos); } } function processEntryToGenAbc(entryInfos: Map): void { - for (const value of entryInfos.values()) { - const tempAbcFilePath: string = toUnixPath(path.resolve(value.npmInfo, ENTRY_TXT)); - const buildAbcFilePath: string = toUnixPath(path.resolve(value.buildPath, ENTRY_TXT)); - fs.writeFileSync(tempAbcFilePath, value.entry, 'utf-8'); - if (!fs.existsSync(buildAbcFilePath)) { - const parent: string = path.join(buildAbcFilePath, '..'); - if (!(fs.existsSync(parent) && fs.statSync(parent).isDirectory())) { - mkDir(parent); - } - } - fs.copyFileSync(tempAbcFilePath, buildAbcFilePath); + if (entryInfos.size <= 0) { + return; + } + generateNpmEntriesInfo(entryInfos); + const npmEntriesInfoPath: string = path.join(process.env.cachePath, NPMENTRIES_TXT); + validateFilePathLength(npmEntriesInfoPath, logger); + let npmEntriesProtoFileName: string = "npm_entries" + EXTNAME_PROTO_BIN; + const npmEntriesProtoFilePath: string = path.join(process.env.cachePath, "protos", "npm_entries", npmEntriesProtoFileName); + validateFilePathLength(npmEntriesProtoFilePath, logger); + mkdirsSync(path.dirname(npmEntriesProtoFilePath)); + let js2Abc: string = path.join(arkDir, 'build', 'bin', 'js2abc'); + if (isWin) { + js2Abc = path.join(arkDir, 'build-win', 'bin', 'js2abc.exe'); + } else if (isMac) { + js2Abc = path.join(arkDir, 'build-mac', 'bin', 'js2abc'); + } + validateFilePathLength(js2Abc, logger); + const singleCmd: any = `"${js2Abc}" --compile-npm-entries "${npmEntriesInfoPath}" "${npmEntriesProtoFilePath}`; + try { + childProcess.execSync(singleCmd); + } catch (e) { + logger.debug(red, `ArkTS:ERROR Failed to generate npm proto file to abc, Error message: ${e}`, reset); } } function writeFileSync(inputString: string, buildPath: string, keyPath: string, jsBundleFile: string): void { let output = path.resolve(buildPath, keyPath); + validateFilePathLength(output, logger); let parent: string = path.join(output, '..'); if (!(fs.existsSync(parent) && fs.statSync(parent).isDirectory())) { mkDir(parent); } let cacheOutputPath: string = ""; if (process.env.cachePath) { - cacheOutputPath = path.join(process.env.cachePath, TEMPORARY, keyPath); + let buildDirArr: string[] = projectConfig.buildPath.split(path.sep); + let abilityDir: string = buildDirArr[buildDirArr.length - 1]; + cacheOutputPath = path.join(process.env.cachePath, TEMPORARY, abilityDir, keyPath); } else { cacheOutputPath = output; } + validateFilePathLength(cacheOutputPath, logger); parent = path.join(cacheOutputPath, '..'); if (!(fs.existsSync(parent) && fs.statSync(parent).isDirectory())) { mkDir(parent); @@ -434,11 +625,18 @@ function writeFileSync(inputString: string, buildPath: string, keyPath: string, fs.writeFileSync(cacheOutputPath, inputString); if (fs.existsSync(cacheOutputPath)) { const fileSize: any = fs.statSync(cacheOutputPath).size; + let sourceFile: string = output.replace(/\.temp\.js$/, "_.js"); + if (!isDebug && projectConfig.projectRootPath) { + sourceFile = toUnixPath(sourceFile.replace(projectConfig.projectRootPath + path.sep, '')); + } else { + sourceFile = toUnixPath(sourceFile); + } output = toUnixPath(output); cacheOutputPath = toUnixPath(cacheOutputPath); - intermediateJsBundle.push({path: output, size: fileSize, cacheOutputPath: cacheOutputPath}); + + intermediateJsBundle.push({path: output, size: fileSize, cacheOutputPath: cacheOutputPath, sourceFile: sourceFile}); } else { - logger.error(red, `ETS:ERROR Failed to convert file ${jsBundleFile} to bin. ${output} is lost`, reset); + logger.debug(red, `ArkTS:ERROR Failed to convert file ${jsBundleFile} to bin. ${output} is lost`, reset); process.exitCode = FAIL; } } @@ -489,18 +687,37 @@ function splitJsBundlesBySize(bundleArray: Array, groupNumber: number): an } function invokeWorkersModuleToGenAbc(moduleInfos: Array): void { - invokeCluterModuleToAbc(); + invokeClusterModuleToAbc(); } export function initAbcEnv() : string[] { let args: string[] = []; - if (process.env.panda === TS2ABC) { + if (process.env.minPlatformVersion === "8") { + process.env.panda = TS2ABC; + let js2abc: string = path.join(arkDir, 'build', 'legacy_api8', 'src', 'index.js'); + if (isWin) { + js2abc = path.join(arkDir, 'build-win', 'legacy_api8', 'src', 'index.js'); + } else if (isMac) { + js2abc = path.join(arkDir, 'build-mac', 'legacy_api8', 'src', 'index.js'); + } + validateFilePathLength(js2abc, logger); + + js2abc = '"' + js2abc + '"'; + args = [ + '--expose-gc', + js2abc + ]; + if (isDebug) { + args.push('--debug'); + } + } else if (process.env.panda === TS2ABC) { let js2abc: string = path.join(arkDir, 'build', 'src', 'index.js'); if (isWin) { js2abc = path.join(arkDir, 'build-win', 'src', 'index.js'); } else if (isMac) { js2abc = path.join(arkDir, 'build-mac', 'src', 'index.js'); } + validateFilePathLength(js2abc, logger); js2abc = '"' + js2abc + '"'; args = [ @@ -517,6 +734,7 @@ export function initAbcEnv() : string[] { } else if (isMac) { es2abc = path.join(arkDir, 'build-mac', 'bin', 'es2abc'); } + validateFilePathLength(es2abc, logger); args = [ '"' + es2abc + '"' @@ -528,95 +746,36 @@ export function initAbcEnv() : string[] { args.push('--merge-abc'); } } else { - logger.error(red, `ETS:ERROR please set panda module`, reset); + logger.error(red, `ArkTS:ERROR please set panda module`, reset); } return args; } -function invokeCluterModuleToAbc(): void { +function invokeClusterModuleToAbc(): void { if (process.env.watchMode === 'true') { process.exitCode = SUCCESS; } filterIntermediateModuleByHashJson(buildPathInfo, moduleInfos); - filterModuleInfos.forEach(moduleInfo => { - if (moduleInfo.isCommonJs) { - commonJsModuleInfos.push(moduleInfo); - } else { - ESMModuleInfos.push(moduleInfo); - } - }); const abcArgs: string[] = initAbcEnv(); - const clusterNewApiVersion: number = 16; - const useNewApi: boolean = compareNodeVersion(clusterNewApiVersion); - - if (useNewApi && cluster.isPrimary || !useNewApi && cluster.isMaster) { - if (useNewApi) { - cluster.setupPrimary({ - exec: path.resolve(__dirname, genModuleAbcScript) - }); - } else { - cluster.setupMaster({ - exec: path.resolve(__dirname, genModuleAbcScript) - }); - } - - let totalWorkerNumber = 0; - let commonJsWorkerNumber: number = invokeClusterByModule(abcArgs, commonJsModuleInfos); - totalWorkerNumber += commonJsWorkerNumber; - - let esmWorkerNumber: number = invokeClusterByModule(abcArgs, ESMModuleInfos, true); - totalWorkerNumber += esmWorkerNumber; - - let count_ = 0; - cluster.on('exit', (worker, code, signal) => { - if (code === FAIL || process.exitCode === FAIL) { - process.exitCode = FAIL; - return; - } - count_++; - if (count_ === totalWorkerNumber) { - writeModuleHashJson(); - clearGlobalInfo(); - if (process.env.watchMode === 'true') { - console.info(blue, 'COMPILE RESULT:SUCCESS ', reset); - } - } - logger.debug(`worker ${worker.process.pid} finished`); - }); - } -} + const splitedModules: any[] = splitModulesByNumber(filterModuleInfos, MAX_WORKER_NUMBER); + let cmdPrefix: string = `${nodeJs} ${abcArgs.join(' ')}`; + const workerNumber: number = MAX_WORKER_NUMBER < splitedModules.length ? MAX_WORKER_NUMBER : splitedModules.length; -function invokeClusterByModule(abcArgs:string[], moduleInfos: Array, isModule: Boolean = false) { - moduleInfos = Array.from(new Set(moduleInfos)); - let workerNumber: number = 0; - if (moduleInfos.length > 0) { - let cmdPrefix: any = ""; - const tempAbcArgs: string[] = abcArgs.slice(0); - if (process.env.panda === TS2ABC) { - workerNumber = 3; - isModule ? tempAbcArgs.push('-m') : tempAbcArgs.push('-c'); - cmdPrefix = `${nodeJs} ${tempAbcArgs.join(' ')}`; - } else if (process.env.panda === ES2ABC || process.env.panda === 'undefined' || process.env.panda === undefined) { - workerNumber = os.cpus().length; - isModule ? tempAbcArgs.push('--module') : tempAbcArgs.push('--commonjs'); - cmdPrefix = `${tempAbcArgs.join(' ')}`; + try { + if (process.env.watchMode === 'true') { + processWorkersOfPreviewMode(splitedModules, cmdPrefix, workerNumber); } else { - logger.error(red, `ETS:ERROR please set panda module`, reset); + processWorkersOfBuildMode(splitedModules, cmdPrefix, workerNumber); } - const splitedModules: any[] = splitModulesByNumber(moduleInfos, workerNumber); - workerNumber = splitedModules.length; - for (let i = 0; i < workerNumber; i++) { - const workerData: any = { - 'inputs': JSON.stringify(splitedModules[i]), - 'cmd': cmdPrefix - }; - cluster.fork(workerData); + } catch (e) { + logger.debug(red, `ArkTS:ERROR failed to generate abc. Error message: ${e}`, reset); + process.env.abcCompileSuccess = 'false'; + if (process.env.watchMode !== 'true') { + process.exit(FAIL); } } - - return workerNumber; } function splitModulesByNumber(moduleInfos: Array, workerNumber: number): any[] { @@ -640,97 +799,34 @@ function splitModulesByNumber(moduleInfos: Array, workerNumber: numb return result; } -function judgeWorkersToGenAbc(callback): void { - const workerNum: number = Object.keys(cluster.workers).length; - if (workerNum === 0) { - callback(); - return; - } else { - delayCount++; - setTimeout(judgeWorkersToGenAbc.bind(null, callback), 50); - } -} - -function judgeModuleWorkersToGenAbc(callback): void { - const workerNum: number = Object.keys(cluster.workers).length; - if (workerNum === 0) { - callback(moduleInfos); - return; - } else { - delayCount++; - setTimeout(judgeModuleWorkersToGenAbc.bind(null, callback), 50); - } -} - function invokeWorkersToGenAbc(): void { if (process.env.watchMode === 'true') { process.exitCode = SUCCESS; } let cmdPrefix: string = ''; - let maxWorkerNumber: number = 3; const abcArgs: string[] = initAbcEnv(); if (process.env.panda === TS2ABC) { cmdPrefix = `${nodeJs} ${abcArgs.join(' ')}`; - } else if (process.env.panda === ES2ABC || process.env.panda === 'undefined' || process.env.panda === undefined) { - maxWorkerNumber = os.cpus().length; - cmdPrefix = `${abcArgs.join(' ')}`; } else { - logger.error(red, `ETS:ERROR please set panda module`, reset); + logger.error(red, `ArkTS:ERROR please set panda module`, reset); } filterIntermediateJsBundleByHashJson(buildPathInfo, intermediateJsBundle); - const splitedBundles: any[] = splitJsBundlesBySize(fileterIntermediateJsBundle, maxWorkerNumber); - const workerNumber: number = maxWorkerNumber < splitedBundles.length ? maxWorkerNumber : splitedBundles.length; - - const clusterNewApiVersion: number = 16; - const currentNodeVersion: number = parseInt(process.version.split('.')[0]); - const useNewApi: boolean = currentNodeVersion >= clusterNewApiVersion; + const splitedBundles: any[] = splitJsBundlesBySize(fileterIntermediateJsBundle, MAX_WORKER_NUMBER); + const workerNumber: number = MAX_WORKER_NUMBER < splitedBundles.length ? MAX_WORKER_NUMBER : splitedBundles.length; - if (useNewApi && cluster.isPrimary || !useNewApi && cluster.isMaster) { - if (useNewApi) { - cluster.setupPrimary({ - exec: path.resolve(__dirname, genAbcScript) - }); + try { + if (process.env.watchMode === 'true') { + processWorkersOfPreviewMode(splitedBundles, cmdPrefix, workerNumber); } else { - cluster.setupMaster({ - exec: path.resolve(__dirname, genAbcScript) - }); + processWorkersOfBuildMode(splitedBundles, cmdPrefix, workerNumber); } - - for (let i = 0; i < workerNumber; ++i) { - const workerData: any = { - 'inputs': JSON.stringify(splitedBundles[i]), - 'cmd': cmdPrefix - }; - cluster.fork(workerData); - } - - let count_ = 0; - cluster.on('exit', (worker, code, signal) => { - if (code === FAIL || process.exitCode === FAIL) { - process.exitCode = FAIL; - return; - } - count_++; - if (count_ === workerNumber) { - // for preview of with incre compile - if (process.env.watchMode === 'true') { - processExtraAssetForBundle(); - console.info(red, 'COMPILE RESULT:SUCCESS ', reset); - } - } - logger.debug(`worker ${worker.process.pid} finished`); - }); - - process.on('exit', (code) => { - // for build options - processExtraAssetForBundle(); - }); - - // for preview of without incre compile - if (workerNumber === 0 && process.env.watchMode === 'true') { - processExtraAssetForBundle(); + } catch (e) { + logger.debug(red, `ArkTS:ERROR failed to generate abc. Error message: ${e}`, reset); + process.env.abcCompileSuccess = 'false'; + if (process.env.watchMode !== 'true') { + process.exit(FAIL); } } } @@ -763,9 +859,9 @@ function filterIntermediateModuleByHashJson(buildPath: string, moduleInfos: Arra filterModuleInfos = []; for (let i = 0; i < moduleInfos.length; ++i) { const input: string = moduleInfos[i].tempFilePath; - let outputPath: string = moduleInfos[i].abcFilePath; + let outputPath: string = genProtoFileName(moduleInfos[i].tempFilePath); if (!fs.existsSync(input)) { - logger.error(red, `ETS:ERROR ${input} is lost`, reset); + logger.debug(red, `ArkTS:ERROR ${input} is lost`, reset); process.exitCode = FAIL; break; } @@ -775,14 +871,6 @@ function filterIntermediateModuleByHashJson(buildPath: string, moduleInfos: Arra if (jsonObject[input] === hashInputContentData && jsonObject[outputPath] === hashAbcContentData) { updateJsonObject[input] = hashInputContentData; updateJsonObject[outputPath] = hashAbcContentData; - mkdirsSync(path.dirname(moduleInfos[i].buildFilePath)); - if (projectConfig.buildArkMode === 'debug' && fs.existsSync(moduleInfos[i].tempFilePath)) { - fs.copyFileSync(moduleInfos[i].tempFilePath, moduleInfos[i].buildFilePath); - } - fs.copyFileSync(genAbcFileName(moduleInfos[i].tempFilePath), genAbcFileName(moduleInfos[i].buildFilePath)); - if (projectConfig.buildArkMode === 'debug' && fs.existsSync(genSourceMapFileName(moduleInfos[i].tempFilePath))) { - fs.copyFileSync(genSourceMapFileName(moduleInfos[i].tempFilePath), genSourceMapFileName(moduleInfos[i].buildFilePath)); - } } else { filterModuleInfos.push(moduleInfos[i]); } @@ -798,46 +886,27 @@ function filterIntermediateModuleByHashJson(buildPath: string, moduleInfos: Arra function writeModuleHashJson(): void { for (let i = 0; i < filterModuleInfos.length; ++i) { const input: string = filterModuleInfos[i].tempFilePath; - let outputPath: string = filterModuleInfos[i].abcFilePath; + let outputPath: string = genProtoFileName(filterModuleInfos[i].tempFilePath);; if (!fs.existsSync(input) || !fs.existsSync(outputPath)) { - logger.error(red, `ETS:ERROR ${input} is lost`, reset); + logger.debug(red, `ArkTS:ERROR ${input} is lost`, reset); process.exitCode = FAIL; break; } const hashInputContentData: any = toHashData(input); - const hashAbcContentData: any = toHashData(outputPath); + const hashOutputContentData: any = toHashData(outputPath); moduleHashJsonObject[input] = hashInputContentData; - moduleHashJsonObject[outputPath] = hashAbcContentData; - mkdirsSync(path.dirname(filterModuleInfos[i].buildFilePath)); - if (projectConfig.buildArkMode === 'debug' && fs.existsSync(filterModuleInfos[i].tempFilePath)) { - fs.copyFileSync(filterModuleInfos[i].tempFilePath, filterModuleInfos[i].buildFilePath); - } - fs.copyFileSync(genAbcFileName(filterModuleInfos[i].tempFilePath), genAbcFileName(filterModuleInfos[i].buildFilePath)); - if (projectConfig.buildArkMode === 'debug' && fs.existsSync(genSourceMapFileName(filterModuleInfos[i].tempFilePath))) { - fs.copyFileSync(genSourceMapFileName(filterModuleInfos[i].tempFilePath), genSourceMapFileName(filterModuleInfos[i].buildFilePath)); - } + moduleHashJsonObject[outputPath] = hashOutputContentData; } const hashFilePath: string = genHashJsonPath(buildPathInfo); if (hashFilePath.length === 0) { return; } // fix bug of multi trigger - if (process.env.watchMode !== 'true' || delayCount < 1) { - fs.writeFileSync(hashFilePath, JSON.stringify(moduleHashJsonObject)); - } + fs.writeFileSync(hashFilePath, JSON.stringify(moduleHashJsonObject)); } function filterIntermediateJsBundleByHashJson(buildPath: string, inputPaths: File[]): void { - const tempInputPaths = Array(); - inputPaths.forEach((item) => { - const check = tempInputPaths.every((newItem) => { - return item.path !== newItem.path; - }); - if (check) { - tempInputPaths.push(item); - } - }); - inputPaths = tempInputPaths; + inputPaths = removeDuplicateInfoOfBundleList(inputPaths); for (let i = 0; i < inputPaths.length; ++i) { fileterIntermediateJsBundle.push(inputPaths[i]); @@ -857,7 +926,7 @@ function filterIntermediateJsBundleByHashJson(buildPath: string, inputPaths: Fil const cacheOutputPath: string = inputPaths[i].cacheOutputPath; const cacheAbcFilePath: string = cacheOutputPath.replace(/\.temp\.js$/, '.abc'); if (!fs.existsSync(cacheOutputPath)) { - logger.error(red, `ETS:ERROR ${cacheOutputPath} is lost`, reset); + logger.debug(red, `ArkTS:ERROR ${cacheOutputPath} is lost`, reset); process.exitCode = FAIL; break; } @@ -884,7 +953,7 @@ function writeHashJson(): void { const cacheOutputPath: string = fileterIntermediateJsBundle[i].cacheOutputPath; const cacheAbcFilePath: string = cacheOutputPath.replace(/\.temp\.js$/, '.abc'); if (!fs.existsSync(cacheOutputPath) || !fs.existsSync(cacheAbcFilePath)) { - logger.error(red, `ETS:ERROR ${cacheOutputPath} is lost`, reset); + logger.debug(red, `ArkTS:ERROR ${cacheOutputPath} is lost`, reset); process.exitCode = FAIL; break; } @@ -897,30 +966,34 @@ function writeHashJson(): void { if (hashFilePath.length === 0) { return; } - // fix bug of multi trigger - if (process.env.watchMode !== 'true' || delayCount < 1) { - fs.writeFileSync(hashFilePath, JSON.stringify(hashJsonObject)); - } + fs.writeFileSync(hashFilePath, JSON.stringify(hashJsonObject)); } function genHashJsonPath(buildPath: string): string { buildPath = toUnixPath(buildPath); if (process.env.cachePath) { if (!fs.existsSync(process.env.cachePath) || !fs.statSync(process.env.cachePath).isDirectory()) { - logger.debug(red, `ETS:ERROR hash path does not exist`, reset); + logger.debug(red, `ArkTS:ERROR hash path does not exist`, reset); return ''; } - return path.join(process.env.cachePath, hashFile); + let buildDirArr: string[] = projectConfig.buildPath.split(path.sep); + let abilityDir: string = buildDirArr[buildDirArr.length - 1]; + let hashJsonPath: string = path.join(process.env.cachePath, TEMPORARY, abilityDir, hashFile); + validateFilePathLength(hashJsonPath, logger) + mkdirsSync(path.dirname(hashJsonPath)); + return hashJsonPath; } else if (buildPath.indexOf(ARK) >= 0) { const dataTmps: string[] = buildPath.split(ARK); const hashPath: string = path.join(dataTmps[0], ARK); if (!fs.existsSync(hashPath) || !fs.statSync(hashPath).isDirectory()) { - logger.debug(red, `ETS:ERROR hash path does not exist`, reset); + logger.debug(red, `ArkTS:ERROR hash path does not exist`, reset); return ''; } - return path.join(hashPath, hashFile); + let hashJsonPath: string = path.join(hashPath, hashFile); + validateFilePathLength(hashJsonPath, logger); + return hashJsonPath; } else { - logger.debug(red, `ETS:ERROR not cache exist`, reset); + logger.debug(red, `ArkTS:ERROR not cache exist`, reset); return ''; } } @@ -934,6 +1007,7 @@ function checkNodeModules() { arkEntryPath = path.join(arkDir, 'build-mac'); } let nodeModulesPath: string = path.join(arkEntryPath, NODE_MODULES); + validateFilePathLength(nodeModulesPath, logger); if (!(fs.existsSync(nodeModulesPath) && fs.statSync(nodeModulesPath).isDirectory())) { logger.error(red, `ERROR: node_modules for ark compiler not found. Please make sure switch to non-root user before runing "npm install" for safity requirements and try re-run "npm install" under ${arkEntryPath}`, reset); @@ -950,7 +1024,8 @@ function copyFileCachePathToBuildPath() { const cacheOutputPath: string = intermediateJsBundle[i].cacheOutputPath; const cacheAbcFilePath: string = intermediateJsBundle[i].cacheOutputPath.replace(/\.temp\.js$/, ".abc"); if (!fs.existsSync(cacheAbcFilePath)) { - logger.error(red, `ETS:ERROR ${cacheAbcFilePath} is lost`, reset); + logger.debug(red, `ArkTS:ERROR ${cacheAbcFilePath} is lost`, reset); + process.exitCode = FAIL; break; } let parent: string = path.join(abcFile, '..'); @@ -967,8 +1042,298 @@ function copyFileCachePathToBuildPath() { } } -function processExtraAssetForBundle() { - writeHashJson(); - copyFileCachePathToBuildPath(); +function processExtraAsset() { + if (projectConfig.compileMode === JSBUNDLE || projectConfig.compileMode === undefined) { + writeHashJson(); + copyFileCachePathToBuildPath(); + } else if (projectConfig.compileMode === ESMODULE) { + processEntryToGenAbc(entryInfos); + writeModuleHashJson(); + copyModuleFileCachePathToBuildPath(); + mergeProtoToAbc(); + } clearGlobalInfo(); } + +function handleHotReloadChangedFiles() { + if (!fs.existsSync(projectConfig.changedFileList)) { + logger.debug(blue, `ArkTS: Cannot find file: ${projectConfig.changedFileList}, skip hot reload build`, reset); + return; + } + + let changedFileListJson: string = fs.readFileSync(projectConfig.changedFileList).toString(); + let changedFileList: Array = JSON.parse(changedFileListJson).modifiedFiles; + if (typeof(changedFileList) == "undefined" || changedFileList.length == 0) { + return; + } + + let relativeProjectPath = projectConfig.projectPath.slice(projectConfig.projectRootPath.length + path.sep.length); + const nodeModulesFile: Array = []; + let hotReloadSourceMap: Object = {}; + moduleInfos = []; + + for (let file of changedFileList) { + let filePath: string = path.join(projectConfig.projectPath, file); + validateFilePathLength(filePath, logger); + let tempFilePath: string = genTemporaryPath(filePath, projectConfig.projectPath, process.env.cachePath, projectConfig); + if (tempFilePath.length === 0) { + return; + } + validateFilePathLength(tempFilePath, logger); + let buildFilePath: string = ""; + tempFilePath = toUnixPath(tempFilePath); + + switch (path.extname(filePath)) { + case EXTNAME_ETS: { + processEtsModule(filePath, tempFilePath, buildFilePath, nodeModulesFile, undefined); + break; + } + case EXTNAME_TS: { + processTsModule(filePath, tempFilePath, buildFilePath, nodeModulesFile, undefined); + break; + } + case EXTNAME_JS: + case EXTNAME_MJS: + case EXTNAME_CJS: { + processJsModule(filePath, tempFilePath, buildFilePath, nodeModulesFile, undefined); + break; + } + case EXTNAME_JSON: { + processJsonModule(filePath, tempFilePath, buildFilePath, nodeModulesFile, undefined); + break; + } + default: { + logger.debug(red, `ArkTS:ERROR Cannot resolve file path: ${filePath}, stop hot reload build`, reset); + return; + } + } + + let sourceMapPath: string = toUnixPath(path.join(relativeProjectPath, file)); + validateFilePathLength(sourceMapPath, logger); + hotReloadSourceMap[sourceMapPath] = newSourceMaps[sourceMapPath]; + } + + if (!fs.existsSync(projectConfig.patchAbcPath)) { + mkdirsSync(projectConfig.patchAbcPath); + } + + const outputABCPath: string = path.join(projectConfig.patchAbcPath, MODULES_ABC); + validateFilePathLength(outputABCPath, logger); + generateMergedAbc(moduleInfos, entryInfos, outputABCPath); + + // write source maps + let sourceMapFilePath: string = path.join(projectConfig.patchAbcPath, SOURCEMAPS); + validateFilePathLength(sourceMapFilePath, logger); + fs.writeFileSync(sourceMapFilePath, + JSON.stringify(hotReloadSourceMap, null, 2), 'utf-8'); +} + +function handleFinishModules(modules, callback) { + if (projectConfig.hotReload && !isHotReloadFirstBuild) { + handleHotReloadChangedFiles(); + return; + } + + handleFullModuleFiles(modules, callback); + + if (projectConfig.hotReload) { + isHotReloadFirstBuild = false; + } +} + +function copyModuleFileCachePathToBuildPath(): void { + protoFilePath = path.join(path.join(process.env.cachePath, "protos", PROTO_FILESINFO_TXT)); + validateFilePathLength(protoFilePath, logger); + mkdirsSync(path.dirname(protoFilePath)); + let entriesInfo: string = ''; + moduleInfos = removeDuplicateInfo(moduleInfos); + moduleInfos.sort((m1: ModuleInfo, m2: ModuleInfo) => { + return m1.tempFilePath < m2.tempFilePath ? 1 : -1; + }); + for (let i = 0; i < moduleInfos.length; ++i) { + let protoTempPath: string = genProtoFileName(moduleInfos[i].tempFilePath); + entriesInfo += `${toUnixPath(protoTempPath)}\n`; + } + if (entryInfos.size > 0) { + let npmEntriesProtoFileName: string = "npm_entries" + EXTNAME_PROTO_BIN; + const npmEntriesProtoFilePath: string = path.join(process.env.cachePath, "protos", "npm_entries", npmEntriesProtoFileName); + entriesInfo += `${toUnixPath(npmEntriesProtoFilePath)}\n`; + } + fs.writeFileSync(protoFilePath, entriesInfo, 'utf-8'); +} + +function mergeProtoToAbc(): void { + let mergeAbc: string = path.join(arkDir, 'build', 'bin', 'merge_abc'); + if (isWin) { + mergeAbc = path.join(arkDir, 'build-win', 'bin', 'merge_abc.exe'); + } else if (isMac) { + mergeAbc = path.join(arkDir, 'build-mac', 'bin', 'merge_abc'); + } + mkdirsSync(projectConfig.buildPath); + const singleCmd: any = `"${mergeAbc}" --input "@${protoFilePath}" --outputFilePath "${projectConfig.buildPath}" --output ${MODULES_ABC} --suffix protoBin`; + try { + childProcess.execSync(singleCmd); + } catch (e) { + logger.debug(red, `ArkTS:ERROR Failed to merge proto file to abc. Error message: ${e}`, reset); + } +} + +function generateAbcByEs2AbcOfBundleMode(inputPaths: File[]) { + filterIntermediateJsBundleByHashJson(buildPathInfo, inputPaths); + if (fileterIntermediateJsBundle.length === 0) { + processExtraAsset(); + return; + } + let filesInfoPath = generateFileOfBundle(fileterIntermediateJsBundle); + const fileThreads = os.cpus().length < 16 ? os.cpus().length : 16; + let genAbcCmd: string = + `${initAbcEnv().join(' ')} "@${filesInfoPath}" --file-threads "${fileThreads}"`; + logger.debug('gen abc cmd is: ', genAbcCmd); + try { + if (process.env.watchMode === 'true') { + childProcess.execSync(genAbcCmd); + processExtraAsset(); + } else { + const child = childProcess.exec(genAbcCmd); + child.on('exit', (code: any) => { + if (code === FAIL) { + logger.debug(red, "ArkTS:ERROR failed to execute es2abc", reset); + process.exit(FAIL); + } + if (process.env.cachePath === undefined) { + unlinkSync(filesInfoPath); + } + processExtraAsset(); + }); + + child.on('error', (err: any) => { + logger.debug(red, err.toString(), reset); + process.exit(FAIL); + }); + + child.stderr.on('data', (data: any) => { + logger.error(red, data.toString(), reset); + }); + } + } catch (e) { + logger.debug(red, `ArkTS:ERROR failed to generate abc with filesInfo ${filesInfoPath}. Error message: ${e} `, reset); + process.env.abcCompileSuccess = 'false'; + if (process.env.watchMode !== 'true') { + process.exit(FAIL); + } + } finally { + if (process.env.watchMode === 'true') { + if (process.env.cachePath === undefined) { + unlinkSync(filesInfoPath); + } + } + } +} + +function generateFileOfBundle(inputPaths: File[]): string { + let filesInfoPath: string = buildCachePath(FILESINFO_TXT, projectConfig, logger); + inputPaths = removeDuplicateInfoOfBundleList(inputPaths); + + let filesInfo: string = ''; + inputPaths.forEach(info => { + const cacheOutputPath: string = info.cacheOutputPath; + const recordName: string = 'null_recordName'; + const moduleType: string = 'script'; + const sourceFile: string = info.sourceFile; + const abcFilePath: string = cacheOutputPath.replace(/\.temp\.js$/, ".abc"); + filesInfo += `${cacheOutputPath};${recordName};${moduleType};${sourceFile};${abcFilePath}\n`; + }); + fs.writeFileSync(filesInfoPath, filesInfo, 'utf-8'); + + return filesInfoPath; +} + +function removeDuplicateInfoOfBundleList(inputPaths: File[]) { + const tempInputPaths = Array(); + inputPaths.forEach((item) => { + const check = tempInputPaths.every((newItem) => { + return item.path !== newItem.path; + }); + if (check) { + tempInputPaths.push(item); + } + }); + inputPaths = tempInputPaths; + + return inputPaths; +} + +function processWorkersOfPreviewMode(splittedData: any, cmdPrefix: string, workerNumber: number) { + let processEnv: any = Object.assign({}, process.env); + let arkEnvParams: any = { + 'splittedData': JSON.stringify(splittedData), + 'cmdPrefix': cmdPrefix, + 'workerNumber': workerNumber.toString(), + }; + if (projectConfig.compileMode === JSBUNDLE || projectConfig.compileMode === undefined) { + arkEnvParams['mode'] = JSBUNDLE; + } else if (projectConfig.compileMode === ESMODULE) { + arkEnvParams['cachePath'] = process.env.cachePath; + arkEnvParams['mode'] = ESMODULE; + } + processEnv.arkEnvParams = JSON.stringify(arkEnvParams); + + let genAbcCmd: string = `${nodeJs} "${path.resolve(__dirname, MANAGE_WORKERS_SCRIPT)}"`; + childProcess.execSync(genAbcCmd, {env: processEnv}); + processExtraAsset(); +} + +function processWorkersOfBuildMode(splittedData: any, cmdPrefix: string, workerNumber: number) { + const useNewApi: boolean = nodeLargeOrEqualTargetVersion(16); + + if (useNewApi && cluster.isPrimary || !useNewApi && cluster.isMaster) { + let genAbcScript: string = GEN_ABC_SCRIPT; + if (projectConfig.compileMode === ESMODULE) { + genAbcScript = GEN_MODULE_ABC_SCRIPT; + } + if (useNewApi) { + cluster.setupPrimary({ + exec: path.resolve(__dirname, genAbcScript) + }); + } else { + cluster.setupMaster({ + exec: path.resolve(__dirname, genAbcScript) + }); + } + + for (let i = 0; i < workerNumber; ++i) { + let workerData: any = { + 'inputs': JSON.stringify(splittedData[i]), + 'cmd': cmdPrefix + }; + if (projectConfig.compileMode === ESMODULE) { + let sn: number = i + 1; + let workerFileName: string = `filesInfo_${sn}.txt`; + workerData['workerFileName'] = workerFileName; + workerData['cachePath'] = process.env.cachePath; + } + cluster.fork(workerData); + } + + cluster.on('exit', (worker, code, signal) => { + if (code === FAIL) { + process.exitCode = FAIL; + } + logger.debug(`worker ${worker.process.pid} finished`); + }); + + process.on('exit', (code) => { + if (process.exitCode !== FAIL && process.env.watchMode !== 'true') { + processExtraAsset(); + if (projectConfig.compileMode === ESMODULE && + (projectConfig.anBuildMode === AOT_FULL || projectConfig.anBuildMode === AOT_PARTIAL)) { + let faultHandler: FaultHandler = (error) => { logger.error(error); process.exit(FAIL); } + let abcArgs: string[] = initAbcEnv(); + abcArgs.unshift(nodeJs); + const builtinAbcPath: string = generateBuiltinAbc(arkDir, abcArgs, process.env.cachePath, logger, faultHandler); + generateAot(arkDir, builtinAbcPath, projectConfig, logger, faultHandler); + } + } + }); + } +} diff --git a/compiler/src/gen_aot.ts b/compiler/src/gen_aot.ts new file mode 100644 index 0000000000000000000000000000000000000000..985097a85a35c87368b51a4a078cb11d1f9217fc --- /dev/null +++ b/compiler/src/gen_aot.ts @@ -0,0 +1,168 @@ +/* + * Copyright (c) 2023 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 * as childProcess from 'child_process'; +import * as process from 'process'; +import * as fs from 'fs'; +import * as path from 'path'; +import { + MODULES_ABC, + TEMPORARY, + ESMODULE, + AOT_FULL, + AOT_TYPE, + AOT_PARTIAL, + AOT_PROFILE_SUFFIX +} from './pre_define'; +import { + isWindows, + mkdirsSync, + toUnixPath, + validateFilePathLength, + validateFilePathLengths +} from './utils'; +import { + getArkBuildDir, + getBuildBinDir +} from './ark_utils'; + +const red: string = '\u001b[31m'; +const reset: string = '\u001b[39m'; + +export interface FaultHandler { + (error: string): void +} + +function checkAotPartialConfig(buildJsonInfo: any, faultHandler: FaultHandler): boolean { + if (buildJsonInfo.anBuildMode !== AOT_PARTIAL && !buildJsonInfo.apPath) { + return false; + } + if (buildJsonInfo.compileMode !== ESMODULE) { + faultHandler(`ArkTS:ERROR Aot's partial mode must config compileMode with esmodule.`); + } + if (buildJsonInfo.anBuildMode !== AOT_PARTIAL) { + faultHandler(`ArkTS:ERROR Aot's partial mode must config aotBuildMode with partial.`); + } + if (!buildJsonInfo.apPath) { + faultHandler(`ArkTS:ERROR Aot's partial mode must config a valid apPath.`); + } + if (path.extname(buildJsonInfo.apPath) !== AOT_PROFILE_SUFFIX) { + faultHandler(`ArkTS:ERROR apPath for Aot's partial mode must with suffix "${AOT_PROFILE_SUFFIX}".`); + } + if (!fs.existsSync(buildJsonInfo.apPath)) { + faultHandler(`ArkTS:ERROR apPath for Aot's partial mode is not found in "${buildJsonInfo.apPath}".`); + } + if (!buildJsonInfo.anBuildOutPut) { + faultHandler(`ArkTS:ERROR Aot's partial mode need anBuildOutPut.`); + } + // Aot compiler's partial mode. + return true; +} + +function checkAotFullConfig(buildJsonInfo: any, faultHandler: FaultHandler): boolean { + if (buildJsonInfo.anBuildMode !== AOT_FULL) { + return false; + } + if (buildJsonInfo.compileMode !== ESMODULE) { + faultHandler(`ArkTS:ERROR Aot's full mode must config compileMode with esmodule.`); + } + if (buildJsonInfo.apPath) { + faultHandler(`ArkTS:ERROR Aot's full mode do not need apPath.`); + } + if (!buildJsonInfo.anBuildOutPut) { + faultHandler(`ArkTS:ERROR Aot's full mode need anBuildOutPut.`); + } + // Aot compiler's full mode. + return true; +} + +function checkAotTypeConfig(buildJsonInfo: any, faultHandler: FaultHandler): boolean { + if (buildJsonInfo.anBuildMode !== AOT_TYPE) { + return false; + } + if (buildJsonInfo.compileMode !== ESMODULE) { + faultHandler(`ArkTS:ERROR Aot's type mode must config compileMode with esmodule.`); + } + if (buildJsonInfo.apPath) { + faultHandler(`ArkTS:ERROR Aot's type mode do not need apPath.`); + } + // Aot compiler's type mode. + return true; +} + +export function checkAotConfig(buildJsonInfo: any, faultHandler: FaultHandler): boolean { + return checkAotTypeConfig(buildJsonInfo, faultHandler) || + checkAotFullConfig(buildJsonInfo, faultHandler) || checkAotPartialConfig(buildJsonInfo, faultHandler); +} + +export function generateAot(arkDir: string, builtinAbcPath: string, projectConfig: any, logger: any, faultHandler: FaultHandler): void { + let aotCompiler: string = path.join(getBuildBinDir(arkDir), isWindows() ? "ark_aot_compiler.exe" : "ark_aot_compiler"); + const appAbc: string = path.join(projectConfig.buildPath, MODULES_ABC); + const appAot: string = path.join(projectConfig.anBuildOutPut, projectConfig.moduleName); + + if (!validateFilePathLengths([aotCompiler, appAbc, builtinAbcPath, appAot], logger)) { + faultHandler(`ArkTS:ERROR generateAot failed. Invalid file path.`); + } + if (!fs.existsSync(appAbc)) { + faultHandler(`ArkTS:ERROR generateAot failed. AppAbc not found in "${appAbc}"`); + } + const singleCmdPrefix: string = `"${aotCompiler}" --builtins-dts="${builtinAbcPath}" ` + + `--aot-file="${appAot}" --target-triple=aarch64-unknown-linux-gnu `; + let singleCmd: string = ""; + if (projectConfig.anBuildMode === AOT_FULL) { + singleCmd = singleCmdPrefix + ` "${appAbc}"`; + } else if (projectConfig.anBuildMode === AOT_PARTIAL) { + const profile: string = projectConfig.apPath; + if (!validateFilePathLength(profile, logger)) { + faultHandler(`ArkTS:ERROR generateAot failed. Invalid profile file path.`); + } + if (!fs.existsSync(profile)) { + faultHandler(`ArkTS:ERROR generateAot failed. Partial mode lost profile in "${profile}"`); + } + singleCmd = singleCmdPrefix + ` --enable-pgo-profiler=true --pgo-profiler-path="${profile}" "${appAbc}"`; + } else { + faultHandler(`ArkTS:ERROR generateAot failed. unknown anBuildMode: ${projectConfig.anBuildMode}`); + } + try { + logger.debug(`generateAot cmd: ${singleCmd}`); + mkdirsSync(projectConfig.anBuildOutPut); + childProcess.execSync(singleCmd, { windowsHide: true }); + } catch (e) { + faultHandler(`ArkTS:ERROR Failed to generate aot file. Error message: ${e}`); + } +} + +export function generateBuiltinAbc(arkDir: string, abcArgs: string[], cachePath: string, + logger: any, faultHandler: FaultHandler): string { + const builtinFilePath: string = path.join(getArkBuildDir(arkDir), "aot", "src", "lib_ark_builtins.d.ts"); + const builtinAbcPath: string = path.join(cachePath, TEMPORARY, "aot", "lib_ark_builtins.d.abc"); + if (fs.existsSync(builtinAbcPath)) { + logger.debug(`builtin.d.abc already exists, no need to rebuild again`); + return builtinAbcPath; + } + mkdirsSync(path.dirname(builtinAbcPath)); + if (!validateFilePathLengths([builtinFilePath, builtinAbcPath], logger)) { + faultHandler(`ArkTS:ERROR generateBuiltinAbc failed. Invalid file path.`); + } + const tempAbcArgs: string[] = abcArgs.slice(0); + let singleCmd: string = `${tempAbcArgs.join(' ')} "${toUnixPath(builtinFilePath)}" -q -b -m --merge-abc -o "${builtinAbcPath}"`; + try { + logger.debug(`generateBuiltinAbc cmd: ${singleCmd}`); + childProcess.execSync(singleCmd, { windowsHide: true }); + } catch (e) { + faultHandler(`ArkTS:ERROR Failed to generate builtin to abc. Error message: ${e}`); + } + return builtinAbcPath; +} diff --git a/compiler/src/gen_merged_abc.ts b/compiler/src/gen_merged_abc.ts index 14d5ffe9ad46457bbdecff0c49079e420062c01a..99f37b893cec9336b1e492022f9726cace027179 100644 --- a/compiler/src/gen_merged_abc.ts +++ b/compiler/src/gen_merged_abc.ts @@ -23,13 +23,22 @@ import { projectConfig } from '../main'; import { FAIL, FILESINFO_TXT, - MODULES_ABC, MODULES_CACHE, NPMENTRIES_TXT, - NODE_MODULES + NODE_MODULES, + PACKAGES, + PATCH_SYMBOL_TABLE } from './pre_define'; -import { EntryInfo, ModuleInfo, initAbcEnv } from './gen_abc_plugin'; -import { mkdirsSync, toUnixPath } from './utils'; +import { + EntryInfo, + ModuleInfo, + initAbcEnv +} from './gen_abc_plugin'; +import { + mkdirsSync, + toUnixPath, + validateFilePathLength +} from './utils'; const red: string = '\u001b[31m'; const reset: string = '\u001b[39m'; @@ -47,53 +56,94 @@ function generateCompileFilesInfo(moduleInfos: Array) { moduleInfos = tempModuleInfos; const filesInfoPath: string = path.join(process.env.cachePath, FILESINFO_TXT); + validateFilePathLength(filesInfoPath, logger); let filesInfo: string = ''; moduleInfos.forEach(info => { - const moduleType: string = info.isCommonJs ? 'cjs' : 'esm'; - filesInfo += `${info.tempFilePath};${info.recordName};${moduleType}\n`; + const moduleType: string = info.isCommonJs ? 'commonjs' : 'esm'; + const sourceFile: string = info.filePath.replace(projectConfig.projectRootPath + path.sep, ''); + filesInfo += `${info.tempFilePath};${info.recordName};${moduleType};${toUnixPath(sourceFile)};${info.packageName}\n`; }); fs.writeFileSync(filesInfoPath, filesInfo, 'utf-8'); } -function generateNpmEntriesInfo(entryInfos: Map) { +export function generateNpmEntriesInfo(entryInfos: Map) { const npmEntriesInfoPath: string = path.join(process.env.cachePath, NPMENTRIES_TXT); + validateFilePathLength(npmEntriesInfoPath, logger); let entriesInfo: string = ''; for (const value of entryInfos.values()) { - const buildPath: string = value.buildPath.replace(toUnixPath(projectConfig.nodeModulesPath), ''); + const buildPath: string = + value.buildPath.replace(toUnixPath(projectConfig.nodeModulesPath), '').replace(NODE_MODULES, PACKAGES); const entryFile: string = toUnixPath(path.join(buildPath, value.entry)); - const entry: string = entryFile.substring(0, entryFile.lastIndexOf('.')); + const entry: string = entryFile.substring(0, entryFile.lastIndexOf('.')).replace(NODE_MODULES, PACKAGES); entriesInfo += - `${toUnixPath(path.join(NODE_MODULES, buildPath))}:${toUnixPath(path.join(NODE_MODULES, entry))}\n`; + `${toUnixPath(path.join(PACKAGES, buildPath))}:${toUnixPath(path.join(PACKAGES, entry))}\n`; } fs.writeFileSync(npmEntriesInfoPath, entriesInfo, 'utf-8'); } -export function generateMergedAbc(moduleInfos: Array, entryInfos: Map) { +export function generateMergedAbc(moduleInfos: Array, entryInfos: Map, outputABCPath: string) { generateCompileFilesInfo(moduleInfos); generateNpmEntriesInfo(entryInfos); const filesInfoPath: string = path.join(process.env.cachePath, FILESINFO_TXT); const npmEntriesInfoPath: string = path.join(process.env.cachePath, NPMENTRIES_TXT); const cacheFilePath: string = path.join(process.env.cachePath, MODULES_CACHE); - const outputABCPath: string = path.join(projectConfig.buildPath, MODULES_ABC); + validateFilePathLength(cacheFilePath, logger); const fileThreads = os.cpus().length < 16 ? os.cpus().length : 16; mkdirsSync(projectConfig.buildPath); - const gen_abc_cmd: string = - `${initAbcEnv().join(' ')} "@${filesInfoPath}" --npm-module-entry-list "${npmEntriesInfoPath}" --cache-file "${cacheFilePath}" --output "${outputABCPath}" --file-threads "${fileThreads}"`; - logger.debug('gen abc cmd is: ', gen_abc_cmd); + let genAbcCmd: string = + `${initAbcEnv().join(' ')} "@${filesInfoPath}" --npm-module-entry-list "${npmEntriesInfoPath}" --output "${outputABCPath}" --file-threads "${fileThreads}"`; + + projectConfig.patch = projectConfig.patch || false; + projectConfig.enableMap = projectConfig.enableMap || false; + projectConfig.inOldSymbolTablePath = projectConfig.inOldSymbolTablePath || projectConfig.projectRootPath; + + if (projectConfig.patch) { + let oldHapSymbolTable = path.join(projectConfig.inOldSymbolTablePath, PATCH_SYMBOL_TABLE); + genAbcCmd += ` --input-symbol-table "${oldHapSymbolTable}" --generate-patch`; + } + + if (!projectConfig.enableMap) { + genAbcCmd += ` --cache-file "${cacheFilePath}"`; + } else { + // when generating map, cache is forbiden to avoid uncomplete symbol table + let oldHapSymbolTable = path.join(projectConfig.inOldSymbolTablePath, PATCH_SYMBOL_TABLE); + genAbcCmd += ` --dump-symbol-table "${oldHapSymbolTable}"`; + } + + logger.debug('gen abc cmd is: ', genAbcCmd); try { - const child = childProcess.exec(gen_abc_cmd); - child.on('exit', (code: any) => { + if (process.env.watchMode === 'true') { + childProcess.execSync(genAbcCmd); + } else { + const child = childProcess.exec(genAbcCmd); + child.on('exit', (code: any) => { if (code === 1) { - logger.error(red, "ETS:ERROR failed to execute es2abc", reset); + logger.debug(red, "ArkTS:ERROR failed to execute es2abc", reset); + process.exit(FAIL); } - }); + }); - child.on('error', (err: any) => { - logger.error(red, err.toString(), reset); - }); + child.on('error', (err: any) => { + logger.debug(red, err.toString(), reset); + process.exit(FAIL); + }); + + child.stderr.on('data', (data: any) => { + if (projectConfig.patch) { + let patchErr :string[] = + data.split(os.EOL).filter(line => line.includes("[Patch]") || line.includes("Error:")); + logger.error(red, patchErr.join(os.EOL), reset); + } else { + logger.error(red, data.toString(), reset); + } + }); + } } catch (e) { - logger.error(red, `ETS:ERROR failed to generate abc with filesInfo ${filesInfoPath} `, reset); - process.exit(FAIL); + logger.debug(red, `ArkTS:ERROR failed to generate abc with filesInfo ${filesInfoPath}. Error message: ${e}`, reset); + process.env.abcCompileSuccess = 'false'; + if (process.env.watchMode !== 'true') { + process.exit(FAIL); + } } -} \ No newline at end of file +} diff --git a/compiler/src/gen_module_abc.ts b/compiler/src/gen_module_abc.ts index 1426cee667c469f365d8b6f672d6390358cb5390..9b910f368fca3133348259819eb48515e3930413 100644 --- a/compiler/src/gen_module_abc.ts +++ b/compiler/src/gen_module_abc.ts @@ -15,77 +15,53 @@ import * as childProcess from 'child_process'; import * as process from 'process'; +import * as fs from 'fs'; +import * as path from 'path'; import cluster from 'cluster'; import { logger } from './compile_info'; import { SUCCESS, - FAIL, - TS2ABC, - ES2ABC + FAIL } from './pre_define'; +import { + toUnixPath +} from './utils'; const red: string = '\u001b[31m'; const reset: string = '\u001b[39m'; -function js2abcByWorkers(jsonInput: string, cmd: string): Promise { - const inputPaths: any = JSON.parse(jsonInput); - const result: any[] = []; - const chunkSize = 5; - for (let i = 0; i < inputPaths.length; i += chunkSize) { - result.push(inputPaths.slice(i, i + chunkSize)); - } - - for (let i = 0; i < result.length; i++) { - const inputs = []; - for (let j = 0; j < result[i].length; j++) { - const input: string = result[i][j].tempFilePath; - inputs.push('"' + input + '"'); - } - const inputsStr: string = inputs.join(' '); - const singleCmd: any = `${cmd} ${inputsStr}`; - logger.debug('gen abc cmd is: ', singleCmd); - try { - childProcess.execSync(singleCmd); - } catch (e) { - logger.error(red, `ETS:ERROR Failed to convert file ${inputsStr} to abc `, reset); - process.exit(FAIL); - } - } - - return; -} - -function es2abcByWorkers(jsonInput: string, cmd: string): Promise { +function js2abcByWorkers(jsonInput: string, cmd: string, workerFileName: string): Promise { const inputPaths: any = JSON.parse(jsonInput); + // cmd `${cmd} --input-file xx --output-proto --merge-abc` + let filePath: string = path.join(process.env.cachePath, workerFileName); + let content: string = ""; for (let i = 0; i < inputPaths.length; ++i) { - const input: string = inputPaths[i].tempFilePath; - const abcFile: string = input.replace(/\.js$/, '.abc'); - const singleCmd: any = `${cmd} "${input}" --output "${abcFile}" --source-file "${input}"`; - logger.debug('gen abc cmd is: ', singleCmd); - try { - childProcess.execSync(singleCmd); - } catch (e) { - logger.error(red, `ETS:ERROR Failed to convert file ${input} to abc `, reset); - process.exit(FAIL); + let info: any = inputPaths[i]; + const moduleType: string = info.isCommonJs ? 'commonjs' : 'esm'; + content += + `${info.tempFilePath};${info.recordName};${moduleType};${toUnixPath(info.sourceFile)};${info.packageName}`; + if (i < inputPaths.length - 1) { + content += "\n" } } + fs.writeFileSync(filePath, content, "utf-8"); + const singleCmd: any = `${cmd} --input-file "${filePath}" --output-proto --merge-abc`; + logger.debug('gen abc cmd is: ', singleCmd); + try { + childProcess.execSync(singleCmd); + } catch (e) { + logger.debug(red, `ArkTS:ERROR Failed to convert file to proto `, reset); + process.exit(FAIL); + } return; } - logger.debug('worker data is: ', JSON.stringify(process.env)); logger.debug('gen_abc isWorker is: ', cluster.isWorker); -if (cluster.isWorker && process.env['inputs'] !== undefined && process.env['cmd'] !== undefined) { +if (cluster.isWorker && process.env['inputs'] !== undefined && process.env['cmd'] !== undefined + && process.env['workerFileName'] !== undefined && process.env['cachePath'] !== undefined) { logger.debug('==>worker #', cluster.worker.id, 'started!'); - - if (process.env.panda === TS2ABC) { - js2abcByWorkers(process.env['inputs'], process.env['cmd']); - } else if (process.env.panda === ES2ABC || process.env.panda === 'undefined' || process.env.panda === undefined) { - es2abcByWorkers(process.env['inputs'], process.env['cmd']); - } else { - logger.error(red, `ETS:ERROR please set panda module`, reset); - process.exit(FAIL); - } + js2abcByWorkers(process.env['inputs'], process.env['cmd'], process.env['workerFileName']); process.exit(SUCCESS); } diff --git a/compiler/src/manage_workers.ts b/compiler/src/manage_workers.ts new file mode 100644 index 0000000000000000000000000000000000000000..a12c1bebbaa58154cc60cf66abe54f4ebebca4f4 --- /dev/null +++ b/compiler/src/manage_workers.ts @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2022 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 * as path from "path"; +import cluster from "cluster"; +import process from "process"; +import { + ESMODULE, + FAIL, + GEN_ABC_SCRIPT, + GEN_MODULE_ABC_SCRIPT, + JSBUNDLE +} from "./pre_define"; + +if (process.env['arkEnvParams'] === undefined) { + process.exit(FAIL); +} + +let arkEnvParams = JSON.parse(process.env.arkEnvParams); +if (arkEnvParams['mode'] !== JSBUNDLE && arkEnvParams['mode'] !== ESMODULE) { + process.exit(FAIL); +} + +if (arkEnvParams['workerNumber'] !== undefined && + arkEnvParams['splittedData'] !== undefined && + arkEnvParams['cmdPrefix'] !== undefined) { + let workerNumber: number = parseInt(arkEnvParams['workerNumber']); + let splittedData: any = JSON.parse(arkEnvParams['splittedData']); + let cmdPrefix: string = arkEnvParams['cmdPrefix']; + + const clusterNewApiVersion: number = 16; + const currentNodeVersion: number = parseInt(process.version.split('.')[0]); + const useNewApi: boolean = currentNodeVersion >= clusterNewApiVersion; + + if ((useNewApi && cluster.isPrimary) || (!useNewApi && cluster.isMaster)) { + let genAbcScript: string = GEN_ABC_SCRIPT; + if (arkEnvParams['mode'] === ESMODULE) { + genAbcScript = GEN_MODULE_ABC_SCRIPT; + } + if (useNewApi) { + cluster.setupPrimary({ + exec: path.resolve(__dirname, genAbcScript) + }); + } else { + cluster.setupMaster({ + exec: path.resolve(__dirname, genAbcScript) + }); + } + + for (let i = 0; i < workerNumber; ++i) { + let workerData: any = { + 'inputs': JSON.stringify(splittedData[i]), + 'cmd': cmdPrefix + }; + if (arkEnvParams['mode'] === ESMODULE) { + let sn: number = i + 1; + let workerFileName: string = `filesInfo_${sn}.txt`; + workerData['workerFileName'] = workerFileName; + workerData['cachePath'] = arkEnvParams['cachePath']; + } + cluster.fork(workerData); + } + + cluster.on("exit", (worker, code, signal) => { + if (code === FAIL) { + process.exit(FAIL); + } + }); + } +} diff --git a/compiler/src/pre_define.ts b/compiler/src/pre_define.ts index e7aa6ee44bb3554ef3b226595fbf9cb929316aef..07f2d0edda73e7ed276eec4a90ba557406ffccd8 100644 --- a/compiler/src/pre_define.ts +++ b/compiler/src/pre_define.ts @@ -39,6 +39,7 @@ export const COMPONENT_WATCH_DECORATOR: string = '@Watch'; export const COMPONENT_BUILDERPARAM_DECORATOR: string = '@BuilderParam'; export const COMPONENT_LOCAL_STORAGE_LINK_DECORATOR: string = '@LocalStorageLink'; export const COMPONENT_LOCAL_STORAGE_PROP_DECORATOR: string = '@LocalStorageProp'; +export const COMPONENT_CUSTOM_DECORATOR: string = 'COMPONENT_CUSTOM_DECORATOR'; export const COMPONENT_DECORATORS_PARAMS: Set = new Set([COMPONENT_CONSUME_DECORATOR, COMPONENT_STORAGE_PROP_DECORATOR, COMPONENT_STORAGE_LINK_DECORATOR, COMPONENT_PROVIDE_DECORATOR, @@ -55,6 +56,7 @@ export const COMPONENT_OBSERVED_DECORATOR: string = '@Observed'; export const COMPONENT_BUILDER_DECORATOR: string = '@Builder'; export const COMPONENT_EXTEND_DECORATOR: string = '@Extend'; export const COMPONENT_STYLES_DECORATOR: string = '@Styles'; +export const COMPONENT_CONCURRENT_DECORATOR: string = '@Concurrent'; export const CHECK_COMPONENT_EXTEND_DECORATOR: string = 'Extend'; export const OBSERVED_PROPERTY_SIMPLE: string = 'ObservedPropertySimple'; @@ -77,6 +79,8 @@ export const PREVIEW_COMPONENT_FUNCTION_NAME: string = 'previewComponent'; export const GET_PREVIEW_FLAG_FUNCTION_NAME: string = 'getPreviewComponentFlag'; export const COMPONENT_DECORATOR_NAME_COMPONENT: string = 'Component'; +export const XCOMPONENT_SINGLE_QUOTATION: string = `'component'`; +export const XCOMPONENT_DOUBLE_QUOTATION: string = `"component"`; export const COMPONENT_DECORATOR_NAME_CUSTOMDIALOG: string = 'CustomDialog'; export const CUSTOM_DECORATOR_NAME: Set = new Set([ COMPONENT_DECORATOR_NAME_COMPONENT, COMPONENT_DECORATOR_NAME_CUSTOMDIALOG @@ -84,7 +88,9 @@ export const CUSTOM_DECORATOR_NAME: Set = new Set([ export const EXTNAME_ETS: string = '.ets'; export const NODE_MODULES: string = 'node_modules'; +export const PACKAGES: string = 'pkg_modules'; export const INDEX_ETS: string = 'index.ets'; +export const INDEX_TS: string = 'index.ts'; export const PACKAGE_JSON: string = 'package.json'; export const CUSTOM_COMPONENT_DEFAULT: string = 'default'; @@ -111,6 +117,12 @@ export const ATTRIBUTE_ANIMATION: string = 'animation'; export const ATTRIBUTE_ANIMATETO: string = 'animateTo'; export const ATTRIBUTE_STATESTYLES: string = 'stateStyles'; export const ATTRIBUTE_ID: string = 'id'; +export const TRUE: string = 'true'; +export const FALSE: string = 'false'; +export const NULL: string = 'null'; +export const FOREACH_LAZYFOREACH: Set = new Set([ + COMPONENT_FOREACH, COMPONENT_LAZYFOREACH +]); export const COMPONENT_CONSTRUCTOR_ID: string = 'compilerAssignedUniqueChildId'; export const COMPONENT_CONSTRUCTOR_PARENT: string = 'parent'; @@ -123,6 +135,9 @@ export const COMPONENT_SET_AND_PROP: string = 'setAndProp'; export const BUILD_ON: string = 'on'; export const BUILD_OFF: string = 'off'; +export const START: string = 'start'; +export const END: string = 'end'; + export const COMPONENT_CREATE_FUNCTION: string = 'create'; export const COMPONENT_CREATE_LABEL_FUNCTION: string = 'createWithLabel'; export const COMPONENT_CREATE_CHILD_FUNCTION: string = 'createWithChild'; @@ -200,6 +215,7 @@ export const GEOMETRY_VIEW: string = 'GeometryView'; export const MODULE_SHARE_PATH: string = 'src' + path.sep + 'main' + path.sep + 'ets' + path.sep + 'share'; export const BUILD_SHARE_PATH: string = '../share'; export const MODULE_ETS_PATH: string = 'src' + path.sep + 'main' + path.sep + 'ets'; +export const MODULE_VISUAL_PATH: string = 'src' + path.sep + 'main' + path.sep + 'supervisual'; export const THIS: string = 'this'; export const STYLES: string = 'Styles'; @@ -209,6 +225,14 @@ export const VIEW_STACK_PROCESSOR: string = 'ViewStackProcessor'; export const BIND_POPUP: string = 'bindPopup'; export const BIND_POPUP_SET: Set = new Set(['bindPopup']); export const BIND_DRAG_SET: Set = new Set(['onDragStart', 'onItemDragStart']); +export const BIND_OBJECT_PROPERTY: Map> = new Map([ + ['Navigation', new Set(['title'])], + ['NavDestination', new Set(['title'])], + ['ListItem', new Set(['swipeAction'])] +]); +export const CREATE_BIND_COMPONENT: Set = new Set(['ListItemGroup']); +export const HEADER: string = 'header'; +export const FOOTER: string = 'footer'; export const CHECKED: string = 'checked'; export const RADIO: string = 'Radio'; @@ -242,12 +266,19 @@ export const COMPONENT_TOGGLE: string = 'Toggle'; export const TTOGGLE_CHECKBOX: string = 'Checkbox'; export const TOGGLE_SWITCH: string = 'Switch'; -export const ENTRY_TXT: string = 'entry.txt'; export const FILESINFO_TXT: string = 'filesInfo.txt'; export const NPMENTRIES_TXT: string = 'npmEntries.txt'; export const MODULES_CACHE: string = 'modules.cache'; export const MODULES_ABC: string = 'modules.abc'; export const MODULELIST_JSON: string = 'moduleList.json'; +export const PREBUILDMODE_JSON: string = 'preBuildMode.json'; +export const SOURCEMAPS_JSON: string = 'sourceMaps.json'; +export const SOURCEMAPS: string = 'sourceMaps.map'; +export const PROTO_FILESINFO_TXT: string = 'protoFilesInfo.txt'; +export const AOT_FULL: string = 'full'; +export const AOT_TYPE: string = 'type'; +export const AOT_PARTIAL: string = 'partial'; +export const AOT_PROFILE_SUFFIX: string = '.ap'; export const ESMODULE: string = 'esmodule'; export const JSBUNDLE: string = 'jsbundle'; @@ -264,8 +295,14 @@ export const EXTNAME_TS_MAP: string = '.ts.map'; export const EXTNAME_MJS: string = '.mjs'; export const EXTNAME_CJS: string = '.cjs'; export const EXTNAME_D_TS: string = '.d.ts'; +export const EXTNAME_D_ETS: string = '.d.ets'; +export const EXTNAME_JSON: string = '.json'; export const EXTNAME_ABC: string = '.abc'; export const EXTNAME_PROTO_BIN: string = '.protoBin'; +export const PATCH_SYMBOL_TABLE: string = "symbol.txt"; +export const MANAGE_WORKERS_SCRIPT: string = 'manage_workers.js'; +export const GEN_ABC_SCRIPT: string = "gen_abc.js"; +export const GEN_MODULE_ABC_SCRIPT: string = "gen_module_abc.js"; export const SUCCESS: number = 0; export const FAIL: number = 1; @@ -273,10 +310,13 @@ export const FAIL: number = 1; export const TS2ABC: string = 'ts2abc'; export const ES2ABC: string = 'es2abc'; +export const MAX_WORKER_NUMBER: number = 3; + export const GENERATE_ID = 'generateId'; export const _GENERATE_ID = '__generate__Id'; export const COMPONENT_CONSTRUCTOR_INITIAL_PARAMS: string = 'setInitiallyProvidedValue'; +export const COMPONENT_UPDATE_STATE_VARS: string = 'updateStateVars'; export const COMPONENT_RERENDER_FUNCTION: string = 'rerender'; export const COMPONENT_CONSTRUCTOR_PURGE_VARIABLE_DEP: string = 'purgeVariableDependenciesOnElmtId'; export const MARKDEPENDENTELEMENTSDIRTY: string = 'markDependentElementsDirty'; @@ -293,6 +333,7 @@ export const ISINITIALRENDER: string = 'isInitialRender'; export const ELMTID: string = 'elmtId'; export const STARTGETACCESSRECORDINGFOR: string = 'StartGetAccessRecordingFor'; export const STOPGETACCESSRECORDING: string = 'StopGetAccessRecording'; +export const UPDATE_STATE_VARS_OF_CHIND_BY_ELMTID: string = 'updateStateVarsOfChildByElmtId'; export const VIEWSTACKPROCESSOR: string = 'ViewStackProcessor'; export const OBSERVECOMPONENTCREATION: string = 'observeComponentCreation'; export const ISLAZYCREATE: string = 'isLazyCreate'; @@ -313,15 +354,39 @@ export const COMPONENT_INITIAl_RENDER_FUNCTION: string = 'initialRender'; export const GRID_COMPONENT: string = 'Grid'; export const GRIDITEM_COMPONENT: string = 'GridItem'; export const WILLUSEPROXY: string = 'willUseProxy'; -export const TABCONTENT_COMPONENT: string = 'TabContent'; export const BASE_COMPONENT_NAME_PU: string = 'ViewPU'; export const GLOBAL_THIS: string = 'globalThis'; export const OBSERVED_PROPERTY_SIMPLE_PU: string = 'ObservedPropertySimplePU'; export const OBSERVED_PROPERTY_OBJECT_PU: string = 'ObservedPropertyObjectPU'; export const SYNCHED_PROPERTY_SIMPLE_ONE_WAY_PU: string = 'SynchedPropertySimpleOneWayPU'; +export const SYNCHED_PROPERTY_OBJECT_ONE_WAY_PU: string = 'SynchedPropertyObjectOneWayPU'; export const SYNCHED_PROPERTY_SIMPLE_TWO_WAY_PU: string = 'SynchedPropertySimpleTwoWayPU'; export const SYNCHED_PROPERTY_OBJECT_TWO_WAY_PU: string = 'SynchedPropertyObjectTwoWayPU'; export const SYNCHED_PROPERTY_NESED_OBJECT_PU: string = 'SynchedPropertyNesedObjectPU'; export const OBSERVED_PROPERTY_ABSTRACT_PU:string = 'ObservedPropertyAbstractPU'; export const COMPONENT_CONSTRUCTOR_LOCALSTORAGE_PU: string = '__localStorage'; export const COMPONENT_CONSTRUCTOR_LOCALSTORAGE_TYPE_PU: string = 'LocalStorage'; +export const IFELSEBRANCHUPDATEFUNCTION = 'ifElseBranchUpdateFunction'; +export const CREATE_STORAGE_LINK = 'createStorageLink'; +export const CREATE_STORAGE_PROP = 'createStorageProp'; +export const CREATE_LOCAL_STORAGE_LINK = 'createLocalStorageLink'; +export const CREATE_LOCAL_STORAGE_PROP = 'createLocalStorageProp'; + +export const CARD_ENTRY_FUNCTION_NAME: string = 'loadEtsCard'; +export const CARD_ENABLE_DECORATORS: Set = new Set([ + '@StorageLink', '@StorageProp', '@LocalStorageLink', '@LocalStorageProp' +]); +export const CARD_ENABLE_COMPONENTS: Set = new Set([ + 'AbilityComponent', 'PluginComponent', 'FormComponent', 'RemoteWindow', + 'XComponent', 'Web', 'RichText' +]); +export const TabContentAndNavDestination: Set = new Set(['TabContent', + 'NavDestination']); +export const CARD_LOG_TYPE_DECORATORS = 1; +export const CARD_LOG_TYPE_COMPONENTS = 2; +export const CARD_LOG_TYPE_IMPORT = 3; + +export const CALL = 'call'; +export const RESERT = 'reset'; + +export const TS_NOCHECK: string = '// @ts-nocheck'; diff --git a/compiler/src/pre_process.ts b/compiler/src/pre_process.ts index b42751de3f562cb022dfec42154922ecf4d618a6..4e9b936b651e66d6f8262edd1a04c59f953fa15c 100644 --- a/compiler/src/pre_process.ts +++ b/compiler/src/pre_process.ts @@ -13,34 +13,18 @@ * limitations under the License. */ -import ts from 'typescript'; -import fs from 'fs'; -import path from 'path'; -import { SourceMapGenerator } from 'source-map'; - import { - ReplaceResult, - sourceReplace, validateUISyntax, processSystemApi, - componentCollection + ReplaceResult, + sourceReplace, } from './validate_ui_syntax'; import { - LogType, LogInfo, emitLogInfo, - mkDir } from './utils'; -import { - BUILD_ON, - SUPERVISUAL, - SUPERVISUAL_SOURCEMAP_EXT -} from './pre_define'; -import { projectConfig } from '../main.js'; -import { genETS } from '../codegen/codegen_ets.js'; - -const visualMap: Map = new Map(); -const slotMap: Map = new Map(); +import { BUILD_ON } from './pre_define'; +import { parseVisual } from './process_visual'; function preProcess(source: string): string { process.env.compiler = BUILD_ON; @@ -59,233 +43,4 @@ function preProcess(source: string): string { } } -function parseVisual(resourcePath: string, resourceQuery: string, content: string, - log: LogInfo[], source: string): string { - if (!componentCollection.entryComponent || !projectConfig.aceSuperVisualPath) { - return content; - } - const visualPath: string = findVisualFile(resourcePath); - if (!visualPath || !fs.existsSync(visualPath)) { - return content; - } - const visualContent: any = getVisualContent(visualPath, log); - if (!visualContent) { - return content; - } - visualMap.clear(); - slotMap.clear(); - const compilerOptions = ts.readConfigFile( - path.resolve(__dirname, '../tsconfig.json'), ts.sys.readFile).config.compilerOptions; - Object.assign(compilerOptions, { - 'sourceMap': false - }); - const sourceFile: ts.SourceFile = ts.createSourceFile(resourcePath, content, - ts.ScriptTarget.Latest, true, ts.ScriptKind.ETS, compilerOptions); - let newContent: string = content; - if (sourceFile.statements) { - sourceFile.statements.forEach(statement => { - newContent = parseStatement(statement, newContent, log, visualContent); - }); - } - const result: ReplaceResult = sourceReplace(newContent, resourcePath); - newContent = result.content; - const resultLog: LogInfo[] = result.log.concat(validateUISyntax(source, newContent, - resourcePath, resourceQuery)); - log.concat(resultLog); - if (!log.length) { - generateSourceMapForNewAndOriEtsFile(resourcePath, source); - } - return newContent; -} - -function parseStatement(statement: ts.Statement, content: string, log: LogInfo[], - visualContent: any): string { - if (statement.kind === ts.SyntaxKind.StructDeclaration && - statement.name && statement.name.getText() === componentCollection.entryComponent) { - if (statement.members) { - statement.members.forEach(member => { - if (member.kind && member.kind === ts.SyntaxKind.MethodDeclaration) { - content = parseMember(statement, member, content, log, visualContent); - } - }); - } - } - return content; -} - -function parseMember(statement: ts.Statement, member: ts.MethodDeclaration, content: string, - log: LogInfo[], visualContent: any): string { - let newContent: string = content; - if (member.name && member.name.getText() === 'build') { - const buildBody: string = member.getText(); - if (buildBody.replace(/\ +/g, '').replace(/[\r\n]/g, '') === 'build(){}') { - newContent = insertVisualCode(statement, member, visualContent, newContent); - } else { - log.push({ - type: LogType.ERROR, - message: `when the corresponding visual file exists,` + - ` the build function of the entry component must be empty.`, - pos: member.pos - }); - } - } - return newContent; -} - -function insertVisualCode(statement: ts.Statement, member: ts.MethodDeclaration, - visualContent: any, content: string): string { - let newContent: string = content; - newContent = insertImport(visualContent, newContent); - newContent = insertVarAndFunc(member, visualContent, newContent, content); - newContent = insertBuild(member, visualContent, newContent, content); - newContent = insertAboutToAppear(statement, member, visualContent, newContent, content); - return newContent; -} - -function insertImport(visualContent: any, content: string): string { - if (!visualContent.etsImport) { - return content; - } - const mediaQueryImport: string = visualContent.etsImport + '\n'; - const newContent: string = mediaQueryImport + content; - slotMap.set(0, mediaQueryImport.length); - visualMap.set(0, mediaQueryImport.split('\n').length - 1); - return newContent; -} - -function insertVarAndFunc(build: ts.MethodDeclaration, visualContent: any, - content: string, oriContent: string): string { - const visualVarAndFunc: string = (visualContent.etsVariable ? visualContent.etsVariable : '') + - (visualContent.etsFunction ? visualContent.etsFunction : ''); - return visualVarAndFunc ? insertVisualCodeBeforePos(build, '\n' + visualVarAndFunc, content, - oriContent) : content; -} - -function insertBuild(build: ts.MethodDeclaration, visualContent: any, content: string, - oriContent: string): string { - return visualContent.build ? insertVisualCodeAfterPos(build.body, - '\n' + visualContent.build + '\n', content, oriContent) : content; -} - -function insertAboutToAppear(statement: ts.Statement, build: ts.MethodDeclaration, - visualContent: any, content: string, oriContent: string): string { - if (!visualContent.aboutToAppear) { - return content; - } - for (const member of statement.members) { - const hasAboutToAppear: boolean = member.kind && member.kind === ts.SyntaxKind.MethodDeclaration - && member.name && member.name.getText() === 'aboutToAppear'; - if (hasAboutToAppear) { - return insertVisualCodeAfterPos(member.body, '\n' + visualContent.aboutToAppear, content, - oriContent); - } - } - - const aboutToAppearFunc: string = '\n aboutToAppear() {\n' + visualContent.aboutToAppear + - ' }\n'; - return insertVisualCodeBeforePos(build, aboutToAppearFunc, content, oriContent); -} - -function insertVisualCodeAfterPos(member: ts.Block, visualContent: string, content: string, - oriContent: string): string { - const contentBeforePos: string = oriContent.substring(0, member.getStart() + 1); - const originEtsFileLineNumber: number = contentBeforePos.split('\n').length; - const visualLines: number = visualContent.split('\n').length - 1; - const insertedLineNumbers: number = visualMap.get(originEtsFileLineNumber); - visualMap.set(originEtsFileLineNumber, insertedLineNumbers ? insertedLineNumbers + visualLines : - visualLines); - - let newPos: number = member.getStart() + 1; - for (const [key, value] of slotMap) { - if (member.getStart() >= key) { - newPos += value; - } - } - - const newContent: string = content.substring(0, newPos) + visualContent + - content.substring(newPos); - slotMap.set(member.getStart(), visualContent.length); - return newContent; -} - -function insertVisualCodeBeforePos(member: ts.MethodDeclaration, visualContent: string, - content: string, oriContent: string): string { - const contentBeforePos: string = oriContent.substring(0, member.pos); - const originEtsFileLineNumber: number = contentBeforePos.split('\n').length; - const visualLines: number = visualContent.split('\n').length - 1; - const insertedLineNumbers: number = visualMap.get(originEtsFileLineNumber); - visualMap.set(originEtsFileLineNumber, insertedLineNumbers ? insertedLineNumbers + visualLines : - visualLines); - let newPos: number = member.pos; - for (const [key, value] of slotMap) { - if (member.pos >= key) { - newPos += value; - } - } - const newContent: string = content.substring(0, newPos) + visualContent + - content.substring(newPos); - slotMap.set(member.pos, visualContent.length); - return newContent; -} - -function generateSourceMapForNewAndOriEtsFile(resourcePath: string, content: string) { - if (!process.env.cachePath) { - return; - } - const sourcemap: SourceMapGenerator = new SourceMapGenerator({ - file: resourcePath - }); - const lines: Array = content.split('\n'); - const originEtsFileLines: number = lines.length; - for (let l: number = 1; l <= originEtsFileLines; l++) { - let newEtsFileLineNumber: number = l; - for (const [originEtsFileLineNumber, visualLines] of visualMap) { - if (l > originEtsFileLineNumber) { - newEtsFileLineNumber += visualLines; - } - } - sourcemap.addMapping({ - generated: { - line: newEtsFileLineNumber, - column: 0 - }, - source: resourcePath, - original: { - line: l, - column: 0 - } - }); - } - const visualMapName: string = path.parse(resourcePath).name + SUPERVISUAL_SOURCEMAP_EXT; - const visualDirPath: string = path.parse(resourcePath).dir; - const etsDirPath: string = path.parse(projectConfig.projectPath).dir; - const visualMapDirPath: string = path.resolve(process.env.cachePath, SUPERVISUAL + - visualDirPath.replace(etsDirPath, '')); - if (!(fs.existsSync(visualMapDirPath) && fs.statSync(visualMapDirPath).isDirectory())) { - mkDir(visualMapDirPath); - } - fs.writeFile(path.resolve(visualMapDirPath, visualMapName), sourcemap.toString(), (err) => { - if (err) { - return console.error('ERROR: Failed to write visual.js.map'); - } - }); -} - -function findVisualFile(filePath: string): string { - const visualPath: string = filePath.replace(projectConfig.projectPath, - projectConfig.aceSuperVisualPath).replace('.ets', '.visual'); - return visualPath; -} - -function getVisualContent(visualPath: string, log: LogInfo[]): any { - const parseContent: any = genETS(fs.readFileSync(visualPath, 'utf-8')); - if (parseContent && parseContent.errorType && parseContent.errorType !== '') { - log.push({ - type: LogType.ERROR, - message: parseContent.message - }); - } - return parseContent ? parseContent.ets : null; -} - module.exports = preProcess; diff --git a/compiler/src/process_component_build.ts b/compiler/src/process_component_build.ts index f74c70e7e2129785463cbe72068f75060315248d..c0a5997ad34c3954f88a4ff9c8fa9341fd325835 100644 --- a/compiler/src/process_component_build.ts +++ b/compiler/src/process_component_build.ts @@ -84,8 +84,24 @@ import { GRIDITEM_COMPONENT, GRID_COMPONENT, WILLUSEPROXY, - TABCONTENT_COMPONENT, - GLOBAL_THIS + GLOBAL_THIS, + IFELSEBRANCHUPDATEFUNCTION, + CARD_ENABLE_COMPONENTS, + CARD_LOG_TYPE_COMPONENTS, + COMPONENT_CONSTRUCTOR_PARENT, + RESOURCE_NAME_TYPE, + XCOMPONENT_SINGLE_QUOTATION, + XCOMPONENT_DOUBLE_QUOTATION, + BIND_OBJECT_PROPERTY, + TRUE, + FALSE, + HEADER, + FOOTER, + CALL, + CREATE_BIND_COMPONENT, + TabContentAndNavDestination, + START, + END } from './pre_define'; import { INNER_COMPONENT_NAMES, @@ -107,19 +123,28 @@ import { import { componentCollection, builderParamObjectCollection, - checkAllNode + checkAllNode, + getObservedPropertyCollection } from './validate_ui_syntax'; -import { processCustomComponent } from './process_custom_component'; +import { + processCustomComponent, + createConditionParent +} from './process_custom_component'; import { LogType, LogInfo, - componentInfo, - createFunction + componentInfo } from './utils'; -import { partialUpdateConfig, projectConfig } from '../main'; -import { transformLog, contextGlobal } from './process_ui_syntax'; +import { + partialUpdateConfig, + projectConfig +} from '../main'; +import { transformLog, contextGlobal, validatorCard } from './process_ui_syntax'; import { props } from './compile_info'; -import { CUSTOM_COMPONENT } from '../lib/pre_define'; + +const checkComponents: Set = new Set([ + "TextArea", "TextInput", "GridContainer" +]); export function processComponentBuild(node: ts.MethodDeclaration, log: LogInfo[]): ts.MethodDeclaration { @@ -144,17 +169,26 @@ export function processComponentBuild(node: ts.MethodDeclaration, } export function processComponentBlock(node: ts.Block, isLazy: boolean, log: LogInfo[], - isTransition: boolean = false, isInnerBuilder: boolean = false, parent: string = undefined): ts.Block { + isTransition: boolean = false, isBuilder: boolean = false, parent: string = undefined, + forEachParameters: ts.NodeArray = undefined, isGlobalBuilder: boolean = false): ts.Block { const newStatements: ts.Statement[] = []; - processComponentChild(node, newStatements, log, - {isAcceleratePreview: false, line: 0, column: 0, fileName: ''}, isInnerBuilder, parent); + processComponentChild(node, newStatements, log, {isAcceleratePreview: false, line: 0, column: 0, fileName: ''}, + isBuilder, parent, forEachParameters, isGlobalBuilder, isTransition); if (isLazy && !partialUpdateConfig.partialUpdateMode) { newStatements.unshift(createRenderingInProgress(true)); } if (isTransition) { - newStatements.unshift(ts.factory.createExpressionStatement( - createFunction(ts.factory.createIdentifier(COMPONENT_TRANSITION_NAME), - ts.factory.createIdentifier(COMPONENT_CREATE_FUNCTION), null))); + if (!partialUpdateConfig.partialUpdateMode) { + newStatements.unshift(ts.factory.createExpressionStatement( + createFunction(ts.factory.createIdentifier(COMPONENT_TRANSITION_NAME), + ts.factory.createIdentifier(COMPONENT_CREATE_FUNCTION), null))); + } else { + newStatements.unshift(createComponentCreationStatement(ts.factory.createExpressionStatement( + createFunction(ts.factory.createIdentifier(COMPONENT_TRANSITION_NAME), + ts.factory.createIdentifier(COMPONENT_POP_FUNCTION), null)), [ts.factory.createExpressionStatement( + createFunction(ts.factory.createIdentifier(COMPONENT_TRANSITION_NAME), + ts.factory.createIdentifier(COMPONENT_CREATE_FUNCTION), null))], false, isTransition)); + } newStatements.push(ts.factory.createExpressionStatement( createFunction(ts.factory.createIdentifier(COMPONENT_TRANSITION_NAME), ts.factory.createIdentifier(COMPONENT_POP_FUNCTION), null))); @@ -197,9 +231,9 @@ function validateFirstNode(node: ts.Statement): boolean { function validateContainerComponent(node: ts.Statement): boolean { if (ts.isExpressionStatement(node) && node.expression && (ts.isEtsComponentExpression(node.expression) || ts.isCallExpression(node.expression))) { - const nameResult: NameResult = { name: null }; + const nameResult: NameResult = { name: null, node: null }; validateEtsComponentNode(node.expression, nameResult); - if (nameResult.name && BUILDIN_CONTAINER_COMPONENT.has(nameResult.name)) { + if (nameResult.name && checkContainer(nameResult.name, nameResult.node)) { return true; } } @@ -221,7 +255,8 @@ let newsupplement: supplementType = { }; type NameResult = { - name: string + name: string, + node?: ts.Node } function validateEtsComponentNode(node: ts.CallExpression | ts.EtsComponentExpression, result?: NameResult) { @@ -234,6 +269,7 @@ function validateEtsComponentNode(node: ts.CallExpression | ts.EtsComponentExpre if (ts.isEtsComponentExpression(childNode)) { if (ts.isIdentifier(childNode.expression)) { result.name = childNode.expression.getText(); + result.node = childNode; } return true; } else { @@ -245,7 +281,9 @@ let sourceNode: ts.SourceFile; export function processComponentChild(node: ts.Block | ts.SourceFile, newStatements: ts.Statement[], log: LogInfo[], supplement: supplementType = {isAcceleratePreview: false, line: 0, column: 0, fileName: ''}, - isInnerBuilder: boolean = false, parent: string = undefined): void { + isBuilder: boolean = false, parent: string = undefined, + forEachParameters: ts.NodeArray = undefined, isGlobalBuilder: boolean = false, + isTransition: boolean = false): void { if (supplement.isAcceleratePreview) { newsupplement = supplement; const compilerOptions = ts.readConfigFile( @@ -260,13 +298,16 @@ export function processComponentChild(node: ts.Block | ts.SourceFile, newStateme if (ts.isExpressionStatement(item)) { checkEtsComponent(item, log); const name: string = getName(item); - switch (getComponentType(item, log, name, parent)) { + if (CARD_ENABLE_COMPONENTS.has(name)) { + validatorCard(log, CARD_LOG_TYPE_COMPONENTS, item.getStart(), name); + } + switch (getComponentType(item, log, name, parent, forEachParameters)) { case ComponentType.innerComponent: const etsExpression: ts.EtsComponentExpression = getEtsComponentExpression(item); if (ts.isIdentifier(etsExpression.expression)) { parent = etsExpression.expression.escapedText.toString(); } - processInnerComponent(item, newStatements, log, parent); + processInnerComponent(item, newStatements, log, parent, isGlobalBuilder, isTransition); break; case ComponentType.customComponent: parent = undefined; @@ -278,21 +319,22 @@ export function processComponentChild(node: ts.Block | ts.SourceFile, newStateme item = expressionResult; } } - processCustomComponent(item as ts.ExpressionStatement, newStatements, log, name, isInnerBuilder); + processCustomComponent(item as ts.ExpressionStatement, newStatements, log, name, + isBuilder, isGlobalBuilder); } break; case ComponentType.forEachComponent: parent = undefined; if (!partialUpdateConfig.partialUpdateMode) { - processForEachComponent(item, newStatements, log, isInnerBuilder); + processForEachComponent(item, newStatements, log, isBuilder, isGlobalBuilder); } else { - processForEachComponentNew(item, newStatements, log); + processForEachComponentNew(item, newStatements, log, isGlobalBuilder); } break; case ComponentType.customBuilderMethod: parent = undefined; if (CUSTOM_BUILDER_METHOD.has(name)) { - newStatements.push(addInnerBuilderParameter(item)); + newStatements.push(addInnerBuilderParameter(item, isGlobalBuilder)); } else { newStatements.push(item); } @@ -307,7 +349,7 @@ export function processComponentChild(node: ts.Block | ts.SourceFile, newStateme break; } } else if (ts.isIfStatement(item)) { - processIfStatement(item, newStatements, log, isInnerBuilder); + processIfStatement(item, newStatements, log, isBuilder, isGlobalBuilder); } else if (!ts.isBlock(item)) { log.push({ type: LogType.ERROR, @@ -317,17 +359,20 @@ export function processComponentChild(node: ts.Block | ts.SourceFile, newStateme } }); } - newsupplement = { - isAcceleratePreview: false, - line: 0, - column: 0, - fileName: '' - }; + if (supplement.isAcceleratePreview) { + newsupplement = { + isAcceleratePreview: false, + line: 0, + column: 0, + fileName: '' + }; + } } -function addInnerBuilderParameter(node: ts.ExpressionStatement): ts.ExpressionStatement { +function addInnerBuilderParameter(node: ts.ExpressionStatement, + isGlobalBuilder: boolean = false): ts.ExpressionStatement { if (node.expression && ts.isCallExpression(node.expression) && node.expression.arguments) { - node.expression.arguments.push(ts.factory.createThis()); + node.expression.arguments.push(isGlobalBuilder ? parentConditionalExpression() : ts.factory.createThis()); return ts.factory.createExpressionStatement(ts.factory.updateCallExpression(node.expression, node.expression.expression, node.expression.typeArguments, node.expression.arguments)); } else { @@ -408,23 +453,26 @@ function parseEtsComponentExpression(node: ts.ExpressionStatement): EtsComponent } function processInnerComponent(node: ts.ExpressionStatement, innerCompStatements: ts.Statement[], - log: LogInfo[], parent: string = undefined): void { + log: LogInfo[], parent: string = undefined, isGlobalBuilder: boolean = false, + isTransition: boolean = false): void { const newStatements: ts.Statement[] = []; const res: CreateResult = createComponent(node, COMPONENT_CREATE_FUNCTION); newStatements.push(res.newNode); const nameResult: NameResult = { name: null }; validateEtsComponentNode(node.expression as ts.EtsComponentExpression, nameResult); if (partialUpdateConfig.partialUpdateMode && ItemComponents.includes(nameResult.name)) { - processItemComponent(node, nameResult, innerCompStatements, log); - } else if (partialUpdateConfig.partialUpdateMode && TABCONTENT_COMPONENT.includes(nameResult.name)) { - processTabContent(node, innerCompStatements, log); + processItemComponent(node, nameResult, innerCompStatements, log, isGlobalBuilder); + } else if (partialUpdateConfig.partialUpdateMode && TabContentAndNavDestination.has(nameResult.name)) { + processTabAndNav(node, innerCompStatements, nameResult.name, log, isGlobalBuilder); } else { - processNormalComponent(node, nameResult, innerCompStatements, log, parent); + processNormalComponent(node, nameResult, innerCompStatements, log, parent, isGlobalBuilder, + isTransition); } } function processNormalComponent(node: ts.ExpressionStatement, nameResult: NameResult, - innerCompStatements: ts.Statement[], log: LogInfo[], parent: string = undefined): void { + innerCompStatements: ts.Statement[], log: LogInfo[], parent: string = undefined, + isGlobalBuilder: boolean = false, isTransition: boolean = false): void { const newStatements: ts.Statement[] = []; const res: CreateResult = createComponent(node, COMPONENT_CREATE_FUNCTION); newStatements.push(res.newNode); @@ -447,12 +495,12 @@ function processNormalComponent(node: ts.ExpressionStatement, nameResult: NameRe if (etsComponentResult.hasAttr) { bindComponentAttr(node, res.identifierNode, newStatements, log); } - processInnerCompStatements(innerCompStatements, newStatements, node); + processInnerCompStatements(innerCompStatements, newStatements, node, isGlobalBuilder, isTransition); processComponentChild(etsComponentResult.etsComponentNode.body, innerCompStatements, log, - {isAcceleratePreview: false, line: 0, column: 0, fileName: ''}, false, parent); + {isAcceleratePreview: false, line: 0, column: 0, fileName: ''}, false, parent, undefined, isGlobalBuilder, false); } else { bindComponentAttr(node, res.identifierNode, newStatements, log); - processInnerCompStatements(innerCompStatements, newStatements, node); + processInnerCompStatements(innerCompStatements, newStatements, node, isGlobalBuilder, isTransition); } if (res.isContainerComponent || res.needPop) { innerCompStatements.push(createComponent(node, COMPONENT_POP_FUNCTION).newNode); @@ -466,10 +514,10 @@ function processDebug(node: ts.Statement, nameResult: NameResult, newStatements: let line: number = 1; let col: number = 1; if (sourceNode && newsupplement.isAcceleratePreview) { - posOfNode = sourceNode.getLineAndCharacterOfPosition(getRealNodePos(node)); + posOfNode = sourceNode.getLineAndCharacterOfPosition(getRealNodePos(node) - 22); curFileName = newsupplement.fileName; if (posOfNode.line === 0) { - col = newsupplement.column - 15; + col = newsupplement.column - 1; } line = newsupplement.line; } else { @@ -490,20 +538,31 @@ function processDebug(node: ts.Statement, nameResult: NameResult, newStatements: function processInnerCompStatements( innerCompStatements: ts.Statement[], newStatements: ts.Statement[], - node: ts.Statement + node: ts.Statement, + isGlobalBuilder: boolean = false, + isTransition: boolean = false ): void { if (!partialUpdateConfig.partialUpdateMode) { innerCompStatements.push(...newStatements); } else { - innerCompStatements.push(createComponentCreationStatement(node, newStatements)); + innerCompStatements.push(createComponentCreationStatement(node, newStatements, isGlobalBuilder, + isTransition)); } } -function createComponentCreationStatement(node: ts.Statement, innerStatements: ts.Statement[]): ts.Statement { +export function createComponentCreationStatement(node: ts.Statement, innerStatements: ts.Statement[], + isGlobalBuilder: boolean = false, isTransition: boolean = false): ts.Statement { + const blockArr: ts.Node[] = [ + createViewStackProcessorStatement(STARTGETACCESSRECORDINGFOR, ELMTID), + ...innerStatements + ]; + if (!isTransition) { + blockArr.push(createInitRenderStatement(node)); + } + blockArr.push(createViewStackProcessorStatement(STOPGETACCESSRECORDING)); return ts.factory.createExpressionStatement( ts.factory.createCallExpression( - ts.factory.createPropertyAccessExpression( - ts.factory.createThis(), + ts.factory.createPropertyAccessExpression(createConditionParent(isGlobalBuilder), ts.factory.createIdentifier(OBSERVECOMPONENTCREATION) ), undefined, [ts.factory.createArrowFunction(undefined, undefined, @@ -514,15 +573,7 @@ function createComponentCreationStatement(node: ts.Statement, innerStatements: t ts.factory.createIdentifier(ISINITIALRENDER), undefined, undefined, undefined) ], undefined, ts.factory.createToken(ts.SyntaxKind.EqualsGreaterThanToken), - ts.factory.createBlock( - [ - createViewStackProcessorStatement(STARTGETACCESSRECORDINGFOR, ELMTID), - ...innerStatements, - createInitRenderStatement(node), - createViewStackProcessorStatement(STOPGETACCESSRECORDING) - ], - true - ) + ts.factory.createBlock(blockArr, true) )] ) ); @@ -558,7 +609,7 @@ function createInitRenderStatement(node: ts.Statement): ts.Statement { } function processItemComponent(node: ts.ExpressionStatement, nameResult: NameResult, innerCompStatements: ts.Statement[], - log: LogInfo[]): void { + log: LogInfo[], isGlobalBuilder: boolean = false): void { const itemRenderInnerStatements: ts.Statement[] = []; const deepItemRenderInnerStatements: ts.Statement[] = []; const res: CreateResult = createComponent(node, COMPONENT_CREATE_FUNCTION); @@ -570,7 +621,8 @@ function processItemComponent(node: ts.ExpressionStatement, nameResult: NameResu if (etsComponentResult.hasAttr) { bindComponentAttr(node, res.identifierNode, itemRenderInnerStatements, log); } - processComponentChild(etsComponentResult.etsComponentNode.body, deepItemRenderInnerStatements, log); + processComponentChild(etsComponentResult.etsComponentNode.body, deepItemRenderInnerStatements, log, + {isAcceleratePreview: false, line: 0, column: 0, fileName: ''}, false, undefined, undefined, isGlobalBuilder, false); } else { bindComponentAttr(node, res.identifierNode, itemRenderInnerStatements, log); } @@ -838,12 +890,13 @@ function createObservedDeepRender( ); } -function processTabContent(node: ts.ExpressionStatement, innerCompStatements: ts.Statement[], log: LogInfo[]): void { +function processTabAndNav(node: ts.ExpressionStatement, innerCompStatements: ts.Statement[], + name: string, log: LogInfo[], isGlobalBuilder: boolean = false): void { const TabContentComp: ts.EtsComponentExpression = getEtsComponentExpression(node); const TabContentBody: ts.Block = TabContentComp.body; let tabContentCreation: ts.Statement; const tabContentPop: ts.Statement = ts.factory.createExpressionStatement(ts.factory.createCallExpression( - ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier(TABCONTENT_COMPONENT), + ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier(name), ts.factory.createIdentifier(COMPONENT_POP_FUNCTION)), undefined, [])); const tabAttrs: ts.Statement[] = []; if (TabContentBody && TabContentBody.statements.length) { @@ -851,18 +904,18 @@ function processTabContent(node: ts.ExpressionStatement, innerCompStatements: ts processComponentChild(TabContentBody, newTabContentChildren, log); tabContentCreation = ts.factory.createExpressionStatement( ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression( - ts.factory.createIdentifier(TABCONTENT_COMPONENT), ts.factory.createIdentifier(COMPONENT_CREATE_FUNCTION)), + ts.factory.createIdentifier(name), ts.factory.createIdentifier(COMPONENT_CREATE_FUNCTION)), undefined, [ts.factory.createArrowFunction(undefined, undefined, [], undefined, ts.factory.createToken(ts.SyntaxKind.EqualsGreaterThanToken), ts.factory.createBlock([...newTabContentChildren], true))])); - bindComponentAttr(node, ts.factory.createIdentifier(TABCONTENT_COMPONENT), tabAttrs, log); - processInnerCompStatements(innerCompStatements, [tabContentCreation, ...tabAttrs], node); + bindComponentAttr(node, ts.factory.createIdentifier(name), tabAttrs, log); + processInnerCompStatements(innerCompStatements, [tabContentCreation, ...tabAttrs], node, isGlobalBuilder); } else { tabContentCreation = ts.factory.createExpressionStatement(ts.factory.createCallExpression( - ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier(TABCONTENT_COMPONENT), + ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier(name), ts.factory.createIdentifier(COMPONENT_CREATE_FUNCTION)), undefined, [])); - bindComponentAttr(node, ts.factory.createIdentifier(TABCONTENT_COMPONENT), tabAttrs, log); - processInnerCompStatements(innerCompStatements, [tabContentCreation, ...tabAttrs], node); + bindComponentAttr(node, ts.factory.createIdentifier(name), tabAttrs, log); + processInnerCompStatements(innerCompStatements, [tabContentCreation, ...tabAttrs], node, isGlobalBuilder); } innerCompStatements.push(tabContentPop); } @@ -878,7 +931,7 @@ function getRealNodePos(node: ts.Node): number { } function processForEachComponent(node: ts.ExpressionStatement, newStatements: ts.Statement[], - log: LogInfo[], isInnerBuilder: boolean = false): void { + log: LogInfo[], isBuilder: boolean = false, isGlobalBuilder: boolean = false): void { const popNode: ts.ExpressionStatement = ts.factory.createExpressionStatement(createFunction( // @ts-ignore node.expression.expression as ts.Identifier, @@ -897,18 +950,18 @@ function processForEachComponent(node: ts.ExpressionStatement, newStatements: ts } argumentsArray.splice(0, 1, arrayObserveredObject); const newArrowNode: ts.ArrowFunction = - processForEachBlock(node.expression, log, isInnerBuilder) as ts.ArrowFunction; + processForEachBlock(node.expression, log, isBuilder) as ts.ArrowFunction; if (newArrowNode) { argumentsArray.splice(1, 1, newArrowNode); } node = addForEachId(ts.factory.updateExpressionStatement(node, ts.factory.updateCallExpression( - node.expression, propertyNode, node.expression.typeArguments, argumentsArray))); + node.expression, propertyNode, node.expression.typeArguments, argumentsArray)), isGlobalBuilder); } newStatements.push(node, popNode); } function processForEachComponentNew(node: ts.ExpressionStatement, newStatements: ts.Statement[], - log: LogInfo[]): void { + log: LogInfo[], isGlobalBuilder: boolean = false): void { const newForEachStatements: ts.Statement[] = []; const popNode: ts.ExpressionStatement = ts.factory.createExpressionStatement(createFunction( (node.expression as ts.CallExpression).expression as ts.Identifier, @@ -920,19 +973,15 @@ function processForEachComponentNew(node: ts.ExpressionStatement, newStatements: node.expression.expression as ts.Identifier, ts.factory.createIdentifier(COMPONENT_CREATE_FUNCTION)), undefined, [])); const newArrowNode: ts.NodeArray = - processForEachBlock(node.expression, log) as ts.NodeArray; + processForEachBlock(node.expression, log, false, isGlobalBuilder) as ts.NodeArray; const itemGenFunctionStatement: ts.VariableStatement = createItemGenFunctionStatement(node.expression, argumentsArray, newArrowNode); const itemIdFuncStatement: ts.VariableStatement = createItemIdFuncStatement(node.expression, argumentsArray); - const updateFunctionStatement: ts.ExpressionStatement = createUpdateFunctionStatement(argumentsArray); + const updateFunctionStatement: ts.ExpressionStatement = createUpdateFunctionStatement(argumentsArray, isGlobalBuilder); const lazyForEachStatement: ts.ExpressionStatement = createLazyForEachStatement(argumentsArray); if (node.expression.expression.getText() === COMPONENT_FOREACH) { - if (argumentsArray[2]) { - newForEachStatements.push(propertyNode, itemGenFunctionStatement, itemIdFuncStatement, updateFunctionStatement); - } else { - newForEachStatements.push(propertyNode, itemGenFunctionStatement, updateFunctionStatement); - } - newStatements.push(createComponentCreationStatement(node, newForEachStatements), popNode); + newForEachStatements.push(propertyNode, itemGenFunctionStatement, updateFunctionStatement); + newStatements.push(createComponentCreationStatement(node, newForEachStatements, isGlobalBuilder), popNode); } else { if (argumentsArray[2]) { newStatements.push(ts.factory.createBlock([itemGenFunctionStatement, itemIdFuncStatement, lazyForEachStatement, @@ -959,25 +1008,13 @@ function createItemGenFunctionStatement( undefined, undefined, ts.factory.createArrowFunction( undefined, undefined, - [ts.factory.createParameterDeclaration( - undefined, undefined, undefined, ts.factory.createIdentifier(_ITEM))], + argumentsArray[1].parameters && argumentsArray[1].parameters.length >= 1 ? + getParameters(argumentsArray[1]) : [], undefined, ts.factory.createToken(ts.SyntaxKind.EqualsGreaterThanToken), ts.factory.createBlock( - [ts.factory.createVariableStatement( - undefined, - ts.factory.createVariableDeclarationList( - [ts.factory.createVariableDeclaration( - ts.factory.createIdentifier( - argumentsArray[1].parameters[0] && argumentsArray[1].parameters[0].name.getText()), - undefined, - undefined, - ts.factory.createIdentifier(_ITEM) - )], - ts.NodeFlags.Const - ) - ), - ...newArrowNode - ], + argumentsArray[1].parameters && argumentsArray[1].parameters.length >= 1 ? + isForEachItemGeneratorParam(argumentsArray, newArrowNode) : + [...newArrowNode], true ) ) @@ -989,6 +1026,36 @@ function createItemGenFunctionStatement( } } +function isForEachItemGeneratorParam(argumentsArray: ts.Expression[], newArrowNode: ts.NodeArray): ts.Statement[] { + return [ + ts.factory.createVariableStatement( + undefined, + ts.factory.createVariableDeclarationList( + [ts.factory.createVariableDeclaration( + ts.factory.createIdentifier( + argumentsArray[1].parameters[0] && argumentsArray[1].parameters[0].name.getText()), + undefined, + undefined, + ts.factory.createIdentifier(_ITEM) + )], + ts.NodeFlags.Const + ) + ), + ...newArrowNode + ]; +} + +function getParameters(node: ts.ArrowFunction): ts.ParameterDeclaration[] { + const parameterArr: ts.ParameterDeclaration[] = [ + ts.factory.createParameterDeclaration( + undefined, undefined, undefined, ts.factory.createIdentifier(_ITEM)) + ]; + if (node.parameters && node.parameters.length > 1) { + parameterArr.push(node.parameters[1]); + } + return parameterArr; +} + function createItemIdFuncStatement( node: ts.CallExpression, argumentsArray: ts.Expression[] @@ -1000,16 +1067,7 @@ function createItemIdFuncStatement( [ts.factory.createVariableDeclaration( ts.factory.createIdentifier(node.expression.getText() === COMPONENT_FOREACH ? FOREACHITEMIDFUNC : __LAZYFOREACHITEMIDFUNC), undefined, undefined, - ts.factory.createArrowFunction( - undefined, undefined, - [ts.factory.createParameterDeclaration(undefined, undefined, undefined, - ts.factory.createIdentifier( - argumentsArray[2].parameters[0] ? argumentsArray[2].parameters[0].name.escapedText : '' - ) - )], undefined, - ts.factory.createToken(ts.SyntaxKind.EqualsGreaterThanToken), - ts.factory.createIdentifier(argumentsArray[2].body ? argumentsArray[2].body.getText() : '') - ) + argumentsArray[2] )], ts.NodeFlags.Const ) @@ -1017,11 +1075,12 @@ function createItemIdFuncStatement( } } -function createUpdateFunctionStatement(argumentsArray: ts.Expression[]): ts.ExpressionStatement { +function createUpdateFunctionStatement(argumentsArray: ts.Expression[], + isGlobalBuilder: boolean = false): ts.ExpressionStatement { return ts.factory.createExpressionStatement( ts.factory.createCallExpression( ts.factory.createPropertyAccessExpression( - ts.factory.createThis(), + isGlobalBuilder ? parentConditionalExpression() : ts.factory.createThis(), ts.factory.createIdentifier(FOREACHUPDATEFUNCTION) ), undefined, @@ -1030,20 +1089,47 @@ function createUpdateFunctionStatement(argumentsArray: ts.Expression[]): ts.Expr ); } -function addForEachIdFuncParameter(argumentsArray: ts.Expression[]): ts.Identifier[] { - const addForEachIdFuncParameterArr: ts.Identifier[] = []; +function addForEachIdFuncParameter(argumentsArray: ts.Expression[]): ts.Expression[] { + const addForEachIdFuncParameterArr: ts.Expression[] = []; addForEachIdFuncParameterArr.push( ts.factory.createIdentifier(ELMTID), - ts.factory.createIdentifier(argumentsArray[0] && argumentsArray[0].getText()) + argumentsArray[0], + ts.factory.createIdentifier(FOREACHITEMGENFUNCTION) ); - addForEachIdFuncParameterArr.push(ts.factory.createIdentifier(FOREACHITEMGENFUNCTION)); - if (argumentsArray[2]) { - addForEachIdFuncParameterArr.push(ts.factory.createIdentifier(FOREACHITEMIDFUNC)); + // @ts-ignore + if (argumentsArray[1] && argumentsArray[1].parameters[1]) { + if (!argumentsArray[2]) { + addForEachIdFuncParameterArr.push(...addForEachParameter(ts.factory.createIdentifier(COMPONENT_IF_UNDEFINED), TRUE, FALSE)); + } else { + // @ts-ignore + argumentsArray[2].parameters[1] ? addForEachIdFuncParameterArr.push(...addForEachParameter(argumentsArray[2], TRUE, TRUE)) : + addForEachIdFuncParameterArr.push(...addForEachParameter(argumentsArray[2], TRUE, FALSE)); + } + } + // @ts-ignore + if (argumentsArray[1] && !argumentsArray[1].parameters[1] && argumentsArray[2]) { + // @ts-ignore + argumentsArray[2].parameters[1] ? addForEachIdFuncParameterArr.push(...addForEachParameter(argumentsArray[2], FALSE, TRUE)) : + addForEachIdFuncParameterArr.push(...addForEachParameter(argumentsArray[2], FALSE, FALSE)); } return addForEachIdFuncParameterArr; } +function addForEachParameter(forEachItemIdContent: ts.Expression, forEachItemGen: string, forEachItemId: string): ts.Expression[] { + return [forEachItemIdContent, ts.factory.createIdentifier(forEachItemGen), + ts.factory.createIdentifier(forEachItemId)]; +} + function createLazyForEachStatement(argumentsArray: ts.Expression[]): ts.ExpressionStatement { + const parameterList: ts.Expression[] = [ + ts.factory.createStringLiteral(componentInfo.id.toString()), + ts.factory.createThis(), + argumentsArray[0], + ts.factory.createIdentifier(__LAZYFOREACHITEMGENFUNCTION) + ]; + if (argumentsArray.length >= 3 && argumentsArray[2]) { + parameterList.push(ts.factory.createIdentifier(__LAZYFOREACHITEMIDFUNC)); + } return ts.factory.createExpressionStatement( ts.factory.createCallExpression( ts.factory.createPropertyAccessExpression( @@ -1051,26 +1137,31 @@ function createLazyForEachStatement(argumentsArray: ts.Expression[]): ts.Express ts.factory.createIdentifier(COMPONENT_CREATE_FUNCTION) ), undefined, - [ts.factory.createStringLiteral(componentInfo.id.toString()), - ts.factory.createThis(), - argumentsArray[0], - ts.factory.createIdentifier(__LAZYFOREACHITEMGENFUNCTION), - ts.factory.createIdentifier(__LAZYFOREACHITEMIDFUNC) - ] + parameterList ) ); } -function addForEachId(node: ts.ExpressionStatement): ts.ExpressionStatement { +function addForEachId(node: ts.ExpressionStatement, isGlobalBuilder: boolean = false): ts.ExpressionStatement { const forEachComponent: ts.CallExpression = node.expression as ts.CallExpression; return ts.factory.updateExpressionStatement(node, ts.factory.updateCallExpression( forEachComponent, forEachComponent.expression, forEachComponent.typeArguments, - [ts.factory.createStringLiteral((++componentInfo.id).toString()), ts.factory.createThis(), + [ts.factory.createStringLiteral((++componentInfo.id).toString()), + isGlobalBuilder ? parentConditionalExpression() : ts.factory.createThis(), ...forEachComponent.arguments])); } +export function parentConditionalExpression(): ts.ConditionalExpression { + return ts.factory.createConditionalExpression( + ts.factory.createIdentifier(COMPONENT_CONSTRUCTOR_PARENT), + ts.factory.createToken(ts.SyntaxKind.QuestionToken), + ts.factory.createIdentifier(COMPONENT_CONSTRUCTOR_PARENT), + ts.factory.createToken(ts.SyntaxKind.ColonToken), + ts.factory.createThis()); +} + function processForEachBlock(node: ts.CallExpression, log: LogInfo[], - isInnerBuilder: boolean = false): ts.NodeArray | ts.ArrowFunction { + isBuilder: boolean = false, isGlobalBuilder: boolean = false): ts.NodeArray | ts.ArrowFunction { if (node.arguments.length > 1 && ts.isArrowFunction(node.arguments[1])) { const isLazy: boolean = node.expression.getText() === COMPONENT_LAZYFOREACH; const arrowNode: ts.ArrowFunction = node.arguments[1] as ts.ArrowFunction; @@ -1089,18 +1180,20 @@ function processForEachBlock(node: ts.CallExpression, log: LogInfo[], if (!partialUpdateConfig.partialUpdateMode) { return ts.factory.updateArrowFunction( arrowNode, arrowNode.modifiers, arrowNode.typeParameters, arrowNode.parameters, - arrowNode.type, arrowNode.equalsGreaterThanToken, processComponentBlock(blockNode, isLazy, log)); + arrowNode.type, arrowNode.equalsGreaterThanToken, + processComponentBlock(blockNode, isLazy, log, false, false, undefined, + arrowNode.parameters, isGlobalBuilder)); } else { - return processComponentBlock(blockNode, isLazy, log).statements; + return processComponentBlock(blockNode, isLazy, log, false, false, undefined, arrowNode.parameters).statements; } } else { if (!partialUpdateConfig.partialUpdateMode) { return ts.factory.updateArrowFunction( arrowNode, arrowNode.modifiers, arrowNode.typeParameters, arrowNode.parameters, arrowNode.type, arrowNode.equalsGreaterThanToken, - processComponentBlock(body, isLazy, log, false, isInnerBuilder)); + processComponentBlock(body, isLazy, log, false, isBuilder, undefined, arrowNode.parameters)); } else { - return processComponentBlock(body, isLazy, log).statements; + return processComponentBlock(body, isLazy, log, false, false, undefined, arrowNode.parameters, isGlobalBuilder).statements; } } } @@ -1119,19 +1212,19 @@ function createRenderingInProgress(isTrue: boolean): ts.ExpressionStatement { } function processIfStatement(node: ts.IfStatement, newStatements: ts.Statement[], - log: LogInfo[], isInnerBuilder: boolean = false): void { + log: LogInfo[], isBuilder: boolean = false, isGlobalBuilder: boolean = false): void { const ifCreate: ts.ExpressionStatement = createIfCreate(); - const newIfNode: ts.IfStatement = processInnerIfStatement(node, 0, log, isInnerBuilder); + const newIfNode: ts.IfStatement = processInnerIfStatement(node, 0, log, isBuilder, isGlobalBuilder); const ifPop: ts.ExpressionStatement = createIfPop(); if (!partialUpdateConfig.partialUpdateMode) { newStatements.push(ifCreate, newIfNode, ifPop); } else { - newStatements.push(createComponentCreationStatement(node, [ifCreate, newIfNode]), ifPop); + newStatements.push(createComponentCreationStatement(node, [ifCreate, newIfNode], isGlobalBuilder), ifPop); } } function processInnerIfStatement(node: ts.IfStatement, id: number, log: LogInfo[], - isInnerBuilder: boolean = false): ts.IfStatement { + isBuilder: boolean = false, isGlobalBuilder: boolean = false): ts.IfStatement { if (ts.isIdentifier(node.expression) && node.expression.originalKeywordKind === undefined && !node.expression.escapedText) { log.push({ @@ -1142,15 +1235,15 @@ function processInnerIfStatement(node: ts.IfStatement, id: number, log: LogInfo[ node = ts.factory.updateIfStatement(node, ts.factory.createIdentifier(COMPONENT_IF_UNDEFINED), node.thenStatement, node.elseStatement); } - const newThenStatement: ts.Statement = processThenStatement(node.thenStatement, id, log, isInnerBuilder); - const newElseStatement: ts.Statement = processElseStatement(node.elseStatement, id, log, isInnerBuilder); + const newThenStatement: ts.Statement = processThenStatement(node.thenStatement, id, log, isBuilder, isGlobalBuilder); + const newElseStatement: ts.Statement = processElseStatement(node.elseStatement, id, log, isBuilder, isGlobalBuilder); const newIfNode: ts.IfStatement = ts.factory.updateIfStatement( node, node.expression, newThenStatement, newElseStatement); return newIfNode; } function processThenStatement(thenStatement: ts.Statement, id: number, - log: LogInfo[], isInnerBuilder: boolean = false): ts.Statement { + log: LogInfo[], isBuilder: boolean = false, isGlobalBuilder: boolean = false): ts.Statement { if (ts.isExpressionStatement(thenStatement) && ts.isIdentifier(thenStatement.expression) && thenStatement.expression.originalKeywordKind === undefined && !thenStatement.expression.escapedText) { @@ -1162,40 +1255,68 @@ function processThenStatement(thenStatement: ts.Statement, id: number, } if (thenStatement) { if (ts.isBlock(thenStatement)) { - thenStatement = processIfBlock(thenStatement, id, log, isInnerBuilder); + thenStatement = processIfBlock(thenStatement, id, log, isBuilder, isGlobalBuilder); } else if (ts.isIfStatement(thenStatement)) { - thenStatement = processInnerIfStatement(thenStatement, 0, log, isInnerBuilder); + thenStatement = processInnerIfStatement(thenStatement, 0, log, isBuilder, isGlobalBuilder); thenStatement = ts.factory.createBlock( - [createIfCreate(), createIfBranchId(id), thenStatement, createIfPop()], true); + partialUpdateConfig.partialUpdateMode + ? [createIfCreate(), createIfBranchFunc(id, [thenStatement], isGlobalBuilder), createIfPop()] + : [createIfCreate(), createIfBranchId(id), thenStatement, createIfPop()], + true + ); } else { thenStatement = ts.factory.createBlock([thenStatement], true); - thenStatement = processIfBlock(thenStatement as ts.Block, id, log, isInnerBuilder); + thenStatement = processIfBlock(thenStatement as ts.Block, id, log, isBuilder, isGlobalBuilder); } } return thenStatement; } function processElseStatement(elseStatement: ts.Statement, id: number, - log: LogInfo[], isInnerBuilder: boolean = false): ts.Statement { + log: LogInfo[], isBuilder: boolean = false, isGlobalBuilder: boolean = false): ts.Statement { if (elseStatement) { if (ts.isBlock(elseStatement)) { elseStatement = processIfBlock(elseStatement, id + 1, log); } else if (ts.isIfStatement(elseStatement)) { - elseStatement = processInnerIfStatement(elseStatement, id + 1, log, isInnerBuilder); + elseStatement = processInnerIfStatement(elseStatement, id + 1, log, isBuilder, isGlobalBuilder); } else { elseStatement = ts.factory.createBlock([elseStatement], true); - elseStatement = processIfBlock(elseStatement as ts.Block, id + 1, log, isInnerBuilder); + elseStatement = processIfBlock(elseStatement as ts.Block, id + 1, log, isBuilder, isGlobalBuilder); } + } else if (partialUpdateConfig.partialUpdateMode && id === 0) { + elseStatement = ts.factory.createBlock( + [ + ts.factory.createExpressionStatement( + ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression( + ts.factory.createIdentifier(COMPONENT_IF), + ts.factory.createIdentifier(COMPONENT_IF_BRANCH_ID_FUNCTION) + ), + undefined, + [ts.factory.createNumericLiteral(++id)] + ) + ), + ], + true + ); } return elseStatement; } -function processIfBlock(block: ts.Block, id: number, log: LogInfo[], isInnerBuilder: boolean = false): ts.Block { - return addIfBranchId(id, processComponentBlock(block, false, log, false, isInnerBuilder)); +function processIfBlock(block: ts.Block, id: number, log: LogInfo[], isBuilder: boolean = false, + isGlobalBuilder: boolean = false): ts.Block { + return addIfBranchId(id, isGlobalBuilder, + processComponentBlock(block, false, log, false, isBuilder, undefined, undefined, isGlobalBuilder)); } -function addIfBranchId(id: number, container: ts.Block): ts.Block { - return ts.factory.updateBlock(container, [createIfBranchId(id), ...container.statements]); +function addIfBranchId(id: number, isGlobalBuilder: boolean = false, container: ts.Block): ts.Block { + let containerStatements: ts.Statement[]; + if (partialUpdateConfig.partialUpdateMode) { + containerStatements = [createIfBranchFunc(id, [...container.statements], isGlobalBuilder)]; + } else { + containerStatements = [createIfBranchId(id), ...container.statements]; + } + return ts.factory.updateBlock(container, containerStatements); } function createIf(): ts.Identifier { @@ -1218,6 +1339,15 @@ function createIfBranchId(id: number): ts.ExpressionStatement { ts.factory.createNodeArray([ts.factory.createNumericLiteral(id)]))); } +function createIfBranchFunc(id: number, innerStatements: ts.Statement[], + isGlobalBuilder: boolean = false): ts.ExpressionStatement { + return ts.factory.createExpressionStatement(ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression( + isGlobalBuilder ? parentConditionalExpression() : ts.factory.createThis(), + ts.factory.createIdentifier(IFELSEBRANCHUPDATEFUNCTION)), undefined, + [ts.factory.createNumericLiteral(id), ts.factory.createArrowFunction(undefined, undefined, [], undefined, + ts.factory.createToken(ts.SyntaxKind.EqualsGreaterThanToken), ts.factory.createBlock(innerStatements, true))])); +} + interface CreateResult { newNode: ts.ExpressionStatement; identifierNode: ts.Identifier; @@ -1250,19 +1380,48 @@ function createComponent(node: ts.ExpressionStatement, type: string): CreateResu if (NEEDPOP_COMPONENT.has(temp.getText())) { res.needPop = true; } - if (BUILDIN_CONTAINER_COMPONENT.has(temp.getText())) { + if (checkContainer(temp.getText(), temp.parent)) { res.isContainerComponent = true; } res.newNode = type === COMPONENT_POP_FUNCTION ? ts.factory.updateExpressionStatement(node, createFunction(temp, identifierNode, null)) : ts.factory.updateExpressionStatement(node, - createFunction(temp, identifierNode, temp.parent.arguments)); + createFunction(temp, identifierNode, checkArguments(temp, type))); res.identifierNode = temp; } return res; } +function checkArguments(temp: ts.Identifier, type: string): ts.NodeArray { + return temp.getText() === 'XComponent' && type === COMPONENT_CREATE_FUNCTION && + projectConfig.moduleName && projectConfig.bundleName ? + // @ts-ignore + temp.parent.arguments.concat([ + ts.factory.createStringLiteral(`${projectConfig.bundleName}/${projectConfig.moduleName}`) + ]) : temp.parent.arguments +} + +function checkContainer(name: string, node: ts.Node): boolean { + return BUILDIN_CONTAINER_COMPONENT.has(name) && (name !== 'XComponent' || + (node && node.arguments && node.arguments.length && + ts.isObjectLiteralExpression(node.arguments[0]) && node.arguments[0].properties && + checkComponentType(node.arguments[0].properties))); +} + +function checkComponentType(properties: ts.PropertyAssignment[]): boolean { + let flag: boolean = false; + properties.forEach(item => { + if (item.name && ts.isIdentifier(item.name) && item.name.getText() === RESOURCE_NAME_TYPE && + item.initializer && ts.isStringLiteral(item.initializer) && + (item.initializer.getText() == XCOMPONENT_SINGLE_QUOTATION || + item.initializer.getText() == XCOMPONENT_DOUBLE_QUOTATION)) { + flag = true; + } + }) + return flag; +} + interface AnimationInfo { statement: ts.Statement, kind: boolean @@ -1270,7 +1429,7 @@ interface AnimationInfo { export function bindComponentAttr(node: ts.ExpressionStatement, identifierNode: ts.Identifier, newStatements: ts.Statement[], log: LogInfo[], reverse: boolean = true, - isStylesAttr: boolean = false, isGlobalStyles: boolean = false): void { + isStylesAttr: boolean = false): void { let temp: any = node.expression; const statements: ts.Statement[] = []; const lastStatement: AnimationInfo = { statement: null, kind: false }; @@ -1299,7 +1458,7 @@ export function bindComponentAttr(node: ts.ExpressionStatement, identifierNode: temp = processDragStartBuilder(temp); break; default: - temp = processCustomBuilderProperty(temp); + temp = processCustomBuilderProperty(temp, identifierNode, propertyName); } flag = true; } @@ -1307,7 +1466,7 @@ export function bindComponentAttr(node: ts.ExpressionStatement, identifierNode: temp.expression.name && ts.isIdentifier(temp.expression.name) && !componentCollection.customComponents.has(temp.expression.name.getText())) { addComponentAttr(temp, temp.expression.name, lastStatement, statements, identifierNode, log, - isStylesAttr, isGlobalStyles); + isStylesAttr); temp = temp.expression.expression; flag = true; } else if (ts.isIdentifier(temp.expression)) { @@ -1315,7 +1474,7 @@ export function bindComponentAttr(node: ts.ExpressionStatement, identifierNode: !GESTURE_TYPE_NAMES.has(temp.expression.getText()) && !componentCollection.customComponents.has(temp.expression.getText())) { addComponentAttr(temp, temp.expression, lastStatement, statements, identifierNode, log, - isStylesAttr, isGlobalStyles); + isStylesAttr); } break; } @@ -1331,10 +1490,11 @@ export function bindComponentAttr(node: ts.ExpressionStatement, identifierNode: } } -function processCustomBuilderProperty(node: ts.CallExpression): ts.CallExpression { +function processCustomBuilderProperty(node: ts.CallExpression, identifierNode: ts.Identifier, + propertyName: string): ts.CallExpression { const newArguments: ts.Expression[] = []; node.arguments.forEach((argument: ts.Expression | ts.Identifier, index: number) => { - if (index === 0 && isBuilderChangeNode(argument)) { + if (index === 0 && isBuilderChangeNode(argument, identifierNode, propertyName)) { newArguments.push(parseBuilderNode(argument)); } else { newArguments.push(argument); @@ -1344,13 +1504,17 @@ function processCustomBuilderProperty(node: ts.CallExpression): ts.CallExpressio return node; } -function isBuilderChangeNode(argument: ts.Node): boolean { +function isBuilderChangeNode(argument: ts.Node, identifierNode: ts.Identifier, propertyName: string): boolean { return ts.isPropertyAccessExpression(argument) && argument.name && ts.isIdentifier(argument.name) && CUSTOM_BUILDER_METHOD.has(argument.name.getText()) || ts.isCallExpression(argument) && argument.expression && argument.expression.name && ts.isIdentifier(argument.expression.name) && CUSTOM_BUILDER_METHOD.has(argument.expression.name.getText()) || ts.isIdentifier(argument) && - argument.escapedText && CUSTOM_BUILDER_METHOD.has(argument.escapedText.toString()); + argument.escapedText && CUSTOM_BUILDER_METHOD.has(argument.escapedText.toString()) || + ts.isObjectLiteralExpression(argument) && BIND_OBJECT_PROPERTY.get(identifierNode.escapedText.toString()) && + BIND_OBJECT_PROPERTY.get(identifierNode.escapedText.toString()).has(propertyName) || + ts.isCallExpression(argument) && argument.expression && ts.isIdentifier(argument.expression) && + CUSTOM_BUILDER_METHOD.has(argument.expression.escapedText.toString()); } function parseBuilderNode(node: ts.Node): ts.ObjectLiteralExpression { @@ -1360,9 +1524,61 @@ function parseBuilderNode(node: ts.Node): ts.ObjectLiteralExpression { return processIdentifierBuilder(node); } else if (ts.isCallExpression(node)) { return getParsedBuilderAttrArgumentWithParams(node); + } else if (ts.isObjectLiteralExpression(node)) { + return processObjectPropertyBuilder(node); } } +export function processObjectPropertyBuilder(node: ts.ObjectLiteralExpression): ts.ObjectLiteralExpression { + const newProperties: ts.PropertyAssignment[] = []; + node.properties.forEach((property: ts.PropertyAssignment) => { + if (property.name && ts.isIdentifier(property.name) && + [CUSTOM_DIALOG_CONTROLLER_BUILDER, HEADER, FOOTER, START, END].includes( + property.name.escapedText.toString()) && property.initializer) { + if (isPropertyAccessExpressionNode(property.initializer)) { + newProperties.push(ts.factory.updatePropertyAssignment(property, property.name, + ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression( + property.initializer, + ts.factory.createIdentifier(BUILDER_ATTR_BIND) + ), + undefined, + [ts.factory.createThis()] + ))); + } else if (isGlobalBuilderCallExpressionNode(property.initializer) || + isInnerBuilderCallExpressionNode(property.initializer)) { + newProperties.push(transformBuilderCallExpression(property)); + } else { + newProperties.push(property); + } + } else { + newProperties.push(property); + } + }); + return ts.factory.updateObjectLiteralExpression(node, newProperties); +} + +function transformBuilderCallExpression(property: ts.PropertyAssignment): ts.PropertyAssignment { + return ts.factory.updatePropertyAssignment(property, property.name, + ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression( + property.initializer.expression, + ts.factory.createIdentifier(BUILDER_ATTR_BIND) + ), + undefined, + [ts.factory.createThis(), ...(property.initializer.arguments || [])] + )) +} + +function isInnerBuilderCallExpressionNode(node: ts.Node): boolean { + return ts.isCallExpression(node) && node.expression && isPropertyAccessExpressionNode(node.expression); +} + +function isGlobalBuilderCallExpressionNode(node: ts.Node): boolean { + return ts.isCallExpression(node) && node.expression && ts.isIdentifier(node.expression) && + CUSTOM_BUILDER_METHOD.has(node.expression.escapedText.toString()); +} + function isPropertyAccessExpressionNode(node: ts.Node): boolean { return ts.isPropertyAccessExpression(node) && node.expression && node.expression.kind === ts.SyntaxKind.ThisKeyword && node.name && ts.isIdentifier(node.name) && @@ -1474,7 +1690,10 @@ function processIdentifierBuilder(node: ts.Identifier): ts.ObjectLiteralExpressi return ts.factory.createObjectLiteralExpression([ ts.factory.createPropertyAssignment( ts.factory.createIdentifier(BUILDER_ATTR_NAME), - node + ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression(node, ts.factory.createIdentifier(BUILDER_ATTR_BIND)), + undefined, [ts.factory.createThis()] + ) ) ]); } @@ -1491,7 +1710,9 @@ function getParsedBuilderAttrArgumentWithParams(node: ts.CallExpression): undefined, ts.factory.createToken(ts.SyntaxKind.EqualsGreaterThanToken), ts.factory.createBlock( - [ts.factory.createExpressionStatement(node)], + [ts.factory.createExpressionStatement(ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression(node.expression, ts.factory.createIdentifier(CALL) + ), undefined, [ts.factory.createThis(), ...node.arguments]))], true ) ) @@ -1580,20 +1801,21 @@ function verifyComponentId(temp: any, node: ts.Identifier, propName: string, function addComponentAttr(temp: any, node: ts.Identifier, lastStatement: any, statements: ts.Statement[], identifierNode: ts.Identifier, log: LogInfo[], - isStylesAttr: boolean, isGlobalStyles: boolean): void { + isStylesAttr: boolean): void { const propName: string = node.getText(); verifyComponentId(temp, node, propName, log); if (propName === ATTRIBUTE_ANIMATION) { + const animationNullNode: ts.ExpressionStatement = ts.factory.createExpressionStatement( + createFunction(ts.factory.createIdentifier(GLOBAL_CONTEXT), node, + // @ts-ignore + [ts.factory.createNull()])); if (!lastStatement.statement) { if (!(temp.arguments.length === 1 && temp.arguments[0].kind === ts.SyntaxKind.NullKeyword)) { - statements.push(ts.factory.createExpressionStatement(createFunction( - ts.factory.createIdentifier(GLOBAL_CONTEXT), node, - // @ts-ignore - [ts.factory.createNull()]))); + statements.push(animationNullNode); } } else { - statements.push(lastStatement.statement); + statements.push(lastStatement.statement, animationNullNode); } lastStatement.statement = ts.factory.createExpressionStatement(createFunction( ts.factory.createIdentifier(GLOBAL_CONTEXT), node, temp.arguments)); @@ -1602,6 +1824,13 @@ function addComponentAttr(temp: any, node: ts.Identifier, lastStatement: any, parseGesture(temp, propName, statements, log); lastStatement.kind = true; } else if (isExtendFunctionNode(identifierNode, propName)) { + if (newsupplement.isAcceleratePreview) { + log.push({ + type: LogType.ERROR, + message: `Doesn't support Extend function now`, + pos: temp.getStart() + }) + } statements.push(ts.factory.createExpressionStatement(ts.factory.createCallExpression( ts.factory.createIdentifier(`__${identifierNode.escapedText.toString()}__${propName}`), undefined, temp.arguments))); @@ -1617,13 +1846,8 @@ function addComponentAttr(temp: any, node: ts.Identifier, lastStatement: any, } else if (GLOBAL_STYLE_FUNCTION.has(propName) || INNER_STYLE_FUNCTION.has(propName)) { const styleBlock: ts.Block = GLOBAL_STYLE_FUNCTION.get(propName) || INNER_STYLE_FUNCTION.get(propName); - if (GLOBAL_STYLE_FUNCTION.has(propName)) { - bindComponentAttr(styleBlock.statements[0] as ts.ExpressionStatement, identifierNode, - statements, log, false, true, true); - } else { - bindComponentAttr(styleBlock.statements[0] as ts.ExpressionStatement, identifierNode, - statements, log, false, true, false); - } + bindComponentAttr(styleBlock.statements[0] as ts.ExpressionStatement, identifierNode, + statements, log, false, true); lastStatement.kind = true; } else if (isDoubleDollarToChange(isStylesAttr, identifierNode, propName, temp)) { const argumentsArr: ts.Expression[] = []; @@ -1637,7 +1861,7 @@ function addComponentAttr(temp: any, node: ts.Identifier, lastStatement: any, validateStateStyleSyntax(temp, log); } } - temp = loopEtscomponent(temp, isStylesAttr, isGlobalStyles); + temp = loopEtscomponent(temp, isStylesAttr); statements.push(ts.factory.createExpressionStatement( createFunction(identifierNode, node, temp.arguments))); lastStatement.kind = true; @@ -1675,15 +1899,13 @@ function isHaveDoubleDollar(param: ts.PropertyAssignment, name: string): boolean param.initializer.getText().startsWith($$); } -function loopEtscomponent(node: any, isStylesAttr: boolean, isGlobalStyles: boolean): ts.Node { +function loopEtscomponent(node: any, isStylesAttr: boolean): ts.Node { node.arguments.forEach((item: ts.Node, index: number) => { - if (isStylesAttr && isGlobalStyles) { - node.arguments[index] = traverseStylesAttr(item); - } if (ts.isEtsComponentExpression(item)) { node.arguments[index] = ts.factory.createCallExpression( item.expression, undefined, item.arguments); - } else if (ts.isCallExpression(item) || ts.isNewExpression(item)) { + } else if ((ts.isCallExpression(item) || ts.isNewExpression(item)) && + !newsupplement.isAcceleratePreview) { node.arguments[index] = ts.visitEachChild(item, changeEtsComponentKind, contextGlobal); } @@ -1712,15 +1934,6 @@ function classifyArgumentsNum(args: any, argumentsArr: ts.Expression[], propName } } -function traverseStylesAttr(node: ts.Node): ts.Node { - if (ts.isStringLiteral(node)) { - node = ts.factory.createStringLiteral(node.text); - } else if (ts.isNumericLiteral(node)) { - node = ts.factory.createNumericLiteral(node.text); - } - return ts.visitEachChild(node, childNode => traverseStylesAttr(childNode), contextGlobal); -} - function generateObjectFor$$(varExp: ts.Expression): ts.ObjectLiteralExpression { return ts.factory.createObjectLiteralExpression( [ @@ -1928,8 +2141,24 @@ function isEtsComponent(node: ts.ExpressionStatement): boolean { return isEtsComponent; } -function getComponentType(node: ts.ExpressionStatement, log: LogInfo[], - name: string, parent: string): ComponentType { +function isSomeName(forEachParameters: ts.NodeArray, name: string): boolean { + return Array.isArray(forEachParameters) && + forEachParameters.some((item)=>{ + return ts.isIdentifier(item.name) ? item.name.escapedText.toString() === name : false; + }); +} + +function isParamFunction(node: ts.ExpressionStatement): boolean { + return node.expression && ts.isCallExpression(node.expression) && + node.expression.expression && ts.isIdentifier(node.expression.expression); +} + +function getComponentType(node: ts.ExpressionStatement, log: LogInfo[], name: string, + parent: string, forEachParameters: ts.NodeArray = undefined): ComponentType { + let isBuilderName: boolean = true; + if(forEachParameters && isSomeName(forEachParameters, name) && isParamFunction(node)) { + isBuilderName = false; + } if (isEtsComponent(node)) { if (componentCollection.customComponents.has(name)) { return ComponentType.customComponent; @@ -1940,12 +2169,12 @@ function getComponentType(node: ts.ExpressionStatement, log: LogInfo[], return ComponentType.customComponent; } else if (name === COMPONENT_FOREACH || name === COMPONENT_LAZYFOREACH) { return ComponentType.forEachComponent; - } else if (CUSTOM_BUILDER_METHOD.has(name)) { + } else if (CUSTOM_BUILDER_METHOD.has(name) && isBuilderName) { return ComponentType.customBuilderMethod; } else if (builderParamObjectCollection.get(componentCollection.currentClassName) && builderParamObjectCollection.get(componentCollection.currentClassName).has(name)) { return ComponentType.builderParamMethod; - } else if ((['Column', 'XComponent'].includes(parent) || CUSTOM_BUILDER_METHOD.has(parent)) && + } else if ((['XComponent'].includes(parent) || CUSTOM_BUILDER_METHOD.has(parent)) && ts.isCallExpression(node.expression) && ts.isIdentifier(node.expression.expression)) { return ComponentType.function; } else if (!isAttributeNode(node)) { @@ -2028,3 +2257,48 @@ function createIsLazyWithValue(value: boolean): ts.VariableStatement { undefined, undefined, ts.factory.createFalse())], ts.NodeFlags.Const)); } } + +export function createFunction(node: ts.Identifier, attrNode: ts.Identifier, + argumentsArr: ts.NodeArray): ts.CallExpression { + if (argumentsArr && argumentsArr.length) { + if (checkCreateArgumentBuilder(node, attrNode)) { + argumentsArr = transformBuilder(argumentsArr); + } + } else { + //@ts-ignore + argumentsArr = []; + } + return ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression( + node, + attrNode + ), + undefined, + argumentsArr + ); +} + +function checkCreateArgumentBuilder(node: ts.Identifier, attrNode: ts.Identifier): boolean { + if (attrNode.escapedText.toString() === COMPONENT_CREATE_FUNCTION && + CREATE_BIND_COMPONENT.has(node.escapedText.toString())) { + return true; + } + return false; +} + +function transformBuilder(argumentsArr: ts.NodeArray): ts.NodeArray { + const newArguments: ts.Expression[] = []; + argumentsArr.forEach((argument: ts.Expression) => { + newArguments.push(parseCreateParameterBuilder(argument)); + }) + //@ts-ignore + return newArguments; +} + +function parseCreateParameterBuilder(argument: ts.Expression):ts.Expression { + if (ts.isObjectLiteralExpression(argument)) { + return processObjectPropertyBuilder(argument); + } else { + return argument; + } +} diff --git a/compiler/src/process_component_class.ts b/compiler/src/process_component_class.ts index eef49ba5d434a8247b002f79007f111b1ef7612d..becb0a672cd4999e78d9dfe0203ee024ecd1d5e4 100644 --- a/compiler/src/process_component_class.ts +++ b/compiler/src/process_component_class.ts @@ -60,7 +60,7 @@ import { COMPONENT_CONSTRUCTOR_UNDEFINED, CUSTOM_COMPONENT, COMPONENT_CONSTRUCTOR_PARENT, - COMPONENT_IF_UNDEFINED, + NULL, INNER_COMPONENT_MEMBER_DECORATORS, COMPONENT_RERENDER_FUNCTION, RMELMTID, @@ -73,7 +73,11 @@ import { SYNCHED_PROPERTY_SIMPLE_TWO_WAY_PU, SYNCHED_PROPERTY_SIMPLE_ONE_WAY_PU, SYNCHED_PROPERTY_NESED_OBJECT_PU, - OBSERVED_PROPERTY_ABSTRACT_PU + OBSERVED_PROPERTY_ABSTRACT_PU, + CREATE_LOCAL_STORAGE_LINK, + CREATE_LOCAL_STORAGE_PROP, + COMPONENT_UPDATE_STATE_VARS, + COMPONENT_WATCH_DECORATOR } from './pre_define'; import { BUILDIN_STYLE_NAMES, @@ -147,6 +151,7 @@ function processMembers(members: ts.NodeArray, parentComponentN const newMembers: ts.ClassElement[] = []; const watchMap: Map = new Map(); const updateParamsStatements: ts.Statement[] = []; + const stateVarsStatements: ts.Statement[] = []; const purgeVariableDepStatements: ts.Statement[] = []; const rerenderStatements: ts.Statement[] = []; const deleteParamsStatements: ts.PropertyDeclaration[] = []; @@ -181,13 +186,16 @@ function processMembers(members: ts.NodeArray, parentComponentN if (result.getUpdateParams()) { updateParamsStatements.push(result.getUpdateParams()); } + if (result.getStateVarsParams()) { + stateVarsStatements.push(result.getStateVarsParams()); + } if (result.isDeleteParams()) { deleteParamsStatements.push(item); } if (result.getControllerSet()) { newMembers.push(result.getControllerSet()); } - processPropertyUnchanged(result, purgeVariableDepStatements, rerenderStatements); + processPropertyUnchanged(result, purgeVariableDepStatements); } } if (ts.isMethodDeclaration(item) && item.name) { @@ -203,8 +211,9 @@ function processMembers(members: ts.NodeArray, parentComponentN validateHasController(parentComponentName, checkController, log); newMembers.unshift(addDeleteParamsFunc(deleteParamsStatements)); addIntoNewMembers(newMembers, parentComponentName, updateParamsStatements, - purgeVariableDepStatements, rerenderStatements); + purgeVariableDepStatements, rerenderStatements, stateVarsStatements); newMembers.unshift(addConstructor(ctorNode, watchMap, parentComponentName)); + curPropMap.clear(); return newMembers; } @@ -225,16 +234,12 @@ function validateDecorators(item: ts.ClassElement, log: LogInfo[]): void { function processPropertyUnchanged( result: UpdateResult, - purgeVariableDepStatements: ts.Statement[], - rerenderStatements: ts.Statement[] + purgeVariableDepStatements: ts.Statement[] ): void { if (partialUpdateConfig.partialUpdateMode) { if(result.getPurgeVariableDepStatement()) { purgeVariableDepStatements.push(result.getPurgeVariableDepStatement()); } - if(result.getRerenderStatement()) { - rerenderStatements.push(result.getRerenderStatement()); - } } } @@ -243,13 +248,15 @@ function addIntoNewMembers( parentComponentName: ts.Identifier, updateParamsStatements: ts.Statement[], purgeVariableDepStatements: ts.Statement[], - rerenderStatements: ts.Statement[] + rerenderStatements: ts.Statement[], + stateVarsStatements: ts.Statement[] ): void { if (partialUpdateConfig.partialUpdateMode) { newMembers.unshift( addInitialParamsFunc(updateParamsStatements, parentComponentName), + addUpdateStateVarsFunc(stateVarsStatements, parentComponentName), addPurgeVariableDepFunc(purgeVariableDepStatements) - ); + ); newMembers.push(addRerenderFunc(rerenderStatements)); } else { newMembers.unshift(addUpdateParamsFunc(updateParamsStatements, parentComponentName)); @@ -281,12 +288,18 @@ function addPropertyMember(item: ts.ClassElement, newMembers: ts.ClassElement[], ) { isLocalStorage = true; } - updatePropertyItem = createPropertyDeclaration(propertyItem, newType, false, - isLocalStorage, parentComponentName); - if (updatePropertyItem) { - newMembers.push(updatePropertyItem); + const newUpdatePropertyItem = createPropertyDeclaration( + propertyItem, newType, false, isLocalStorage, parentComponentName); + if (!updatePropertyItem) { + updatePropertyItem = newUpdatePropertyItem; + } else if (INNER_COMPONENT_MEMBER_DECORATORS.has(decoratorName) && + decoratorName !== COMPONENT_WATCH_DECORATOR) { + updatePropertyItem = newUpdatePropertyItem; } } + if (updatePropertyItem) { + newMembers.push(updatePropertyItem); + } } } @@ -312,23 +325,33 @@ function createLocalStroageCallExpression(node: ts.PropertyDeclaration, name: st parentComponentName: string): ts.CallExpression { const localStorageLink: Set = localStorageLinkCollection.get(parentComponentName).get(name); const localStorageProp: Set = localStoragePropCollection.get(parentComponentName).get(name); + let localFuncName: string; + const localValue: ts.Expression[] = [ + ts.factory.createStringLiteral(localStorageLink && !localStorageProp ? + Array.from(localStorageLink)[0] : !localStorageLink && localStorageProp ? + Array.from(localStorageProp)[0] : COMPONENT_CONSTRUCTOR_UNDEFINED), + node.initializer ? node.initializer : ts.factory.createNumericLiteral(COMPONENT_CONSTRUCTOR_UNDEFINED), + ts.factory.createThis(), ts.factory.createStringLiteral(name || COMPONENT_CONSTRUCTOR_UNDEFINED) + ]; + if (!partialUpdateConfig.partialUpdateMode) { + localFuncName = localStorageLink && !localStorageProp ? COMPONENT_SET_AND_LINK : + COMPONENT_SET_AND_PROP; + } else { + localFuncName = localStorageLink && !localStorageProp ? CREATE_LOCAL_STORAGE_LINK : + CREATE_LOCAL_STORAGE_PROP; + localValue.splice(-2, 1); + } return ts.factory.createCallExpression( ts.factory.createPropertyAccessExpression( - ts.factory.createPropertyAccessExpression( - ts.factory.createThis(), - ts.factory.createIdentifier(`${COMPONENT_CONSTRUCTOR_LOCALSTORAGE}_`) - ), - ts.factory.createIdentifier(localStorageLink && !localStorageProp ? COMPONENT_SET_AND_LINK : - COMPONENT_SET_AND_PROP) + !partialUpdateConfig.partialUpdateMode ? + ts.factory.createPropertyAccessExpression( + ts.factory.createThis(), + ts.factory.createIdentifier(`${COMPONENT_CONSTRUCTOR_LOCALSTORAGE}_`) + ) : ts.factory.createThis(), + ts.factory.createIdentifier(localFuncName) ), [node.type], - [ - ts.factory.createStringLiteral(localStorageLink && !localStorageProp ? - Array.from(localStorageLink)[0] : !localStorageLink && localStorageProp ? - Array.from(localStorageProp)[0] : COMPONENT_CONSTRUCTOR_UNDEFINED), - node.initializer ? node.initializer : ts.factory.createNumericLiteral(COMPONENT_CONSTRUCTOR_UNDEFINED), - ts.factory.createThis(), ts.factory.createStringLiteral(name || COMPONENT_CONSTRUCTOR_UNDEFINED) - ] + localValue ); } @@ -348,7 +371,6 @@ function processComponentMethod(node: ts.MethodDeclaration, parentComponentName: } const buildNode: ts.MethodDeclaration = processComponentBuild(node, log); updateItem = processBuildMember(buildNode, context, log); - curPropMap.clear(); } else if (node.body && ts.isBlock(node.body)) { if (name === COMPONENT_TRANSITION_FUNCTION) { updateItem = ts.factory.updateMethodDeclaration(node, node.decorators, node.modifiers, @@ -364,10 +386,12 @@ function processComponentMethod(node: ts.MethodDeclaration, parentComponentName: updateItem = processBuildMember(builderNode, context, log); } else if (hasDecorator(node, COMPONENT_STYLES_DECORATOR)) { if (node.parameters && node.parameters.length === 0) { - INNER_STYLE_FUNCTION.set(name, node.body); - STYLES_ATTRIBUTE.add(name); - BUILDIN_STYLE_NAMES.add(name); - decoratorParamSet.add(STYLES); + if (ts.isBlock(node.body) && node.body.statements && node.body.statements.length) { + INNER_STYLE_FUNCTION.set(name, node.body); + STYLES_ATTRIBUTE.add(name); + BUILDIN_STYLE_NAMES.add(name); + decoratorParamSet.add(STYLES); + } } else { log.push({ type: LogType.ERROR, @@ -384,7 +408,7 @@ function processComponentMethod(node: ts.MethodDeclaration, parentComponentName: export function createParentParameter(): ts.ParameterDeclaration { return ts.factory.createParameterDeclaration(undefined, undefined, undefined, ts.factory.createIdentifier(COMPONENT_CONSTRUCTOR_PARENT), undefined, undefined, - ts.factory.createIdentifier(COMPONENT_IF_UNDEFINED)); + ts.factory.createIdentifier(NULL)); } function processBuildMember(node: ts.MethodDeclaration, context: ts.TransformationContext, @@ -512,6 +536,10 @@ export function createReference(node: ts.PropertyAssignment, log: LogInfo[]): ts if (ts.isIdentifier(initExpression) && initExpression.escapedText.toString().match(LINK_REG)) { initText = initExpression.escapedText.toString().replace(LINK_REG, ''); + } else if (ts.isPropertyAccessExpression(initExpression) && initExpression.expression && + initExpression.expression.kind === ts.SyntaxKind.ThisKeyword && + ts.isIdentifier(initExpression.name) && initExpression.name.escapedText.toString().match(LINK_REG)) { + initText = initExpression.name.escapedText.toString().replace(LINK_REG, ''); } else if (isMatchInitExpression(initExpression) && linkParentComponent.includes(propertyName.escapedText.toString())) { initText = initExpression.name.escapedText.toString().replace(LINK_REG, ''); @@ -522,9 +550,6 @@ export function createReference(node: ts.PropertyAssignment, log: LogInfo[]): ts pos: initExpression.getStart() }); } - } else if (partialUpdateConfig.partialUpdateMode && isMatchInitExpression(initExpression) && - propParentComponent.includes(propertyName.escapedText.toString())) { - initText = initExpression.name.escapedText.toString(); } if (initText) { node = addDoubleUnderline(node, propertyName, initText); @@ -576,6 +601,10 @@ function addInitialParamsFunc(statements: ts.Statement[], parentComponentName: t return createParamsInitBlock(COMPONENT_CONSTRUCTOR_INITIAL_PARAMS, statements, parentComponentName); } +function addUpdateStateVarsFunc(statements: ts.Statement[], parentComponentName: ts.Identifier): ts.MethodDeclaration { + return createParamsInitBlock(COMPONENT_UPDATE_STATE_VARS, statements, parentComponentName); +} + function addPurgeVariableDepFunc(statements: ts.Statement[]): ts.MethodDeclaration { return ts.factory.createMethodDeclaration( undefined, undefined, undefined, @@ -590,9 +619,7 @@ function addDeleteParamsFunc(statements: ts.PropertyDeclaration[]): ts.MethodDec statements.forEach((statement: ts.PropertyDeclaration) => { const name: ts.Identifier = statement.name as ts.Identifier; let paramsStatement: ts.ExpressionStatement; - if (partialUpdateConfig.partialUpdateMode && !statement.decorators) { - paramsStatement = createParamsStatement(name); - } else { + if (!partialUpdateConfig.partialUpdateMode || statement.decorators) { paramsStatement = createParamsWithUnderlineStatement(name); } deleteStatements.push(paramsStatement); @@ -619,17 +646,6 @@ function addDeleteParamsFunc(statements: ts.PropertyDeclaration[]): ts.MethodDec return deleteParamsMethod; } -function createParamsStatement(name: ts.Identifier): ts.ExpressionStatement { - return ts.factory.createExpressionStatement(ts.factory.createBinaryExpression( - ts.factory.createPropertyAccessExpression( - ts.factory.createThis(), - ts.factory.createIdentifier(`${name.escapedText.toString()}`) - ), - ts.factory.createToken(ts.SyntaxKind.EqualsToken), - ts.factory.createIdentifier(COMPONENT_CONSTRUCTOR_UNDEFINED) - )); -} - function createParamsWithUnderlineStatement(name: ts.Identifier): ts.ExpressionStatement { return ts.factory.createExpressionStatement( ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression( @@ -706,6 +722,7 @@ function createHeritageClause(): ts.HeritageClause { function createTypeReference(decoratorName: string, type: ts.TypeNode, log: LogInfo[], program: ts.Program): ts.TypeNode { let newType: ts.TypeNode; + let isCheckAny: boolean = true; switch (decoratorName) { case COMPONENT_STATE_DECORATOR: case COMPONENT_PROVIDE_DECORATOR: @@ -749,6 +766,12 @@ function createTypeReference(decoratorName: string, type: ts.TypeNode, log: LogI type || ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword), ]); break; + default: + isCheckAny = false; + break; + } + if (isCheckAny) { + checkAny(type, log); } return newType; } @@ -756,6 +779,7 @@ function createTypeReference(decoratorName: string, type: ts.TypeNode, log: LogI function createTypeReferencePU(decoratorName: string, type: ts.TypeNode, log: LogInfo[], program: ts.Program): ts.TypeNode { let newType: ts.TypeNode; + let isCheckAny: boolean = true; switch (decoratorName) { case COMPONENT_STATE_DECORATOR: case COMPONENT_PROVIDE_DECORATOR: @@ -799,6 +823,22 @@ function createTypeReferencePU(decoratorName: string, type: ts.TypeNode, log: Lo type || ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword), ]); break; + default: + isCheckAny = false; + break; + } + if (isCheckAny) { + checkAny(type, log); } return newType; } + +function checkAny(typeNode: ts.TypeNode, log: LogInfo[]): void { + if (typeNode.kind === ts.SyntaxKind.AnyKeyword && log) { + log.push({ + type: LogType.WARN, + message: `Please define an explicit type, not any.`, + pos: typeNode.getStart() + }); + } +} diff --git a/compiler/src/process_component_constructor.ts b/compiler/src/process_component_constructor.ts index 27bcb7801b8d2ceb471046f08bc3a0ef79e2f362..139b44c2736dab16e4bda48d4dcfef827572d1f9 100644 --- a/compiler/src/process_component_constructor.ts +++ b/compiler/src/process_component_constructor.ts @@ -27,14 +27,10 @@ import { COMPONENT_CONSTRUCTOR_LOCALSTORAGE, BASE_COMPONENT_NAME_PU, COMPONENT_CONSTRUCTOR_LOCALSTORAGE_PU, - COMPONENT_CONSTRUCTOR_LOCALSTORAGE_TYPE_PU + COMPONENT_CONSTRUCTOR_LOCALSTORAGE_TYPE_PU, + ELMTID } from './pre_define'; -import { - localStorageLinkCollection, - localStoragePropCollection -} from './validate_ui_syntax'; - import { partialUpdateConfig } from '../main'; export function getInitConstructor(members: ts.NodeArray, parentComponentName: ts.Identifier @@ -87,17 +83,16 @@ function initConstructorParams(node: ts.ConstructorDeclaration, parentComponentN if (!ts.isIdentifier(parentComponentName)) { return; } - const localStorageNum: number = localStorageLinkCollection.get(parentComponentName.getText()).size + - localStoragePropCollection.get(parentComponentName.getText()).size; const paramNames: Set = !partialUpdateConfig.partialUpdateMode ? new Set([ COMPONENT_CONSTRUCTOR_ID, COMPONENT_CONSTRUCTOR_PARENT, COMPONENT_CONSTRUCTOR_PARAMS, - localStorageNum ? COMPONENT_CONSTRUCTOR_LOCALSTORAGE : COMPONENT_CONSTRUCTOR_PARAMS + COMPONENT_CONSTRUCTOR_LOCALSTORAGE ]) : new Set([ COMPONENT_CONSTRUCTOR_PARENT, COMPONENT_CONSTRUCTOR_PARAMS, - COMPONENT_CONSTRUCTOR_LOCALSTORAGE_PU + COMPONENT_CONSTRUCTOR_LOCALSTORAGE_PU, + ELMTID ]); const newParameters: ts.ParameterDeclaration[] = Array.from(node.parameters); if (newParameters.length !== 0) { @@ -105,9 +100,10 @@ function initConstructorParams(node: ts.ConstructorDeclaration, parentComponentN newParameters.splice(0, newParameters.length); } paramNames.forEach((paramName: string) => { - // @ts-ignore newParameters.push(ts.factory.createParameterDeclaration(undefined, undefined, undefined, - ts.factory.createIdentifier(paramName), undefined, undefined, undefined)); + ts.factory.createIdentifier(paramName), undefined, undefined, + paramName === ELMTID ? ts.factory.createPrefixUnaryExpression( + ts.SyntaxKind.MinusToken, ts.factory.createNumericLiteral('1')) : undefined)); }); return ts.factory.updateConstructorDeclaration(node, undefined, node.modifiers, newParameters, @@ -154,8 +150,6 @@ function addParamsType(ctorNode: ts.ConstructorDeclaration, modifyPara: ts.Param export function addConstructor(ctorNode: any, watchMap: Map, parentComponentName: ts.Identifier): ts.ConstructorDeclaration { const watchStatements: ts.ExpressionStatement[] = []; - const localStorageNum: number = localStorageLinkCollection.get(parentComponentName.getText()).size + - localStoragePropCollection.get(parentComponentName.getText()).size; watchMap.forEach((value, key) => { const watchNode: ts.ExpressionStatement = ts.factory.createExpressionStatement( ts.factory.createCallExpression( @@ -173,26 +167,25 @@ export function addConstructor(ctorNode: any, watchMap: Map, )); watchStatements.push(watchNode); }); - const callSuperStatement: ts.Statement = createCallSuperStatement(localStorageNum); + const callSuperStatement: ts.Statement = createCallSuperStatement(); const updateWithValueParamsStatement: ts.Statement = createUPdWithValStatement(); return updateConstructor(updateConstructor(ctorNode, [], [callSuperStatement], true), [], - [...watchStatements, updateWithValueParamsStatement], false, true, parentComponentName); + [updateWithValueParamsStatement, ...watchStatements], false, true, parentComponentName); } -function createCallSuperStatement(localStorageNum: number): ts.Statement{ +function createCallSuperStatement(): ts.Statement { if (!partialUpdateConfig.partialUpdateMode) { return ts.factory.createExpressionStatement(ts.factory.createCallExpression( - ts.factory.createSuper(), undefined, - localStorageNum ? [ts.factory.createIdentifier(COMPONENT_CONSTRUCTOR_ID), - ts.factory.createIdentifier(COMPONENT_CONSTRUCTOR_PARENT), - ts.factory.createIdentifier(COMPONENT_CONSTRUCTOR_LOCALSTORAGE)] : - [ts.factory.createIdentifier(COMPONENT_CONSTRUCTOR_ID), - ts.factory.createIdentifier(COMPONENT_CONSTRUCTOR_PARENT)])); + ts.factory.createSuper(), undefined, + [ts.factory.createIdentifier(COMPONENT_CONSTRUCTOR_ID), + ts.factory.createIdentifier(COMPONENT_CONSTRUCTOR_PARENT), + ts.factory.createIdentifier(COMPONENT_CONSTRUCTOR_LOCALSTORAGE)])); } else { - return (ts.factory.createExpressionStatement( + return ts.factory.createExpressionStatement( ts.factory.createCallExpression(ts.factory.createSuper(), undefined, [ts.factory.createIdentifier(COMPONENT_CONSTRUCTOR_PARENT), - ts.factory.createIdentifier(COMPONENT_CONSTRUCTOR_LOCALSTORAGE_PU)]))); + ts.factory.createIdentifier(COMPONENT_CONSTRUCTOR_LOCALSTORAGE_PU), + ts.factory.createIdentifier(ELMTID)])); } } diff --git a/compiler/src/process_component_member.ts b/compiler/src/process_component_member.ts index 792336481b8def6c880fd1786ad5a80bcb77dd9c..07f984b88c3c41fad4c2b0aeab1f2ca2ff934417 100644 --- a/compiler/src/process_component_member.ts +++ b/compiler/src/process_component_member.ts @@ -56,10 +56,8 @@ import { COMPONENT_CONSTRUCTOR_PARENT, EXTNAME_ETS, _GENERATE_ID, - MARKDEPENDENTELEMENTSDIRTY, RMELMTID, PURGEDEPENDENCYONELMTID, - SETPROPERTYUNCHANGED, BASICDECORATORS, BASE_COMPONENT_NAME_PU, OBSERVED_PROPERTY_SIMPLE_PU, @@ -67,7 +65,15 @@ import { SYNCHED_PROPERTY_SIMPLE_TWO_WAY_PU, SYNCHED_PROPERTY_OBJECT_TWO_WAY_PU, SYNCHED_PROPERTY_SIMPLE_ONE_WAY_PU, - SYNCHED_PROPERTY_NESED_OBJECT_PU + SYNCHED_PROPERTY_OBJECT_ONE_WAY_PU, + SYNCHED_PROPERTY_NESED_OBJECT_PU, + COMPONENT_CUSTOM_DECORATOR, + THIS, + CREATE_STORAGE_LINK, + CREATE_STORAGE_PROP, + ELMTID, + COMPONENT_CONSTRUCTOR_PARAMS, + RESERT } from './pre_define'; import { forbiddenUseStateType, @@ -77,23 +83,29 @@ import { observedClassCollection, enumCollection, componentCollection, - classMethodCollection + classMethodCollection, + stateCollection } from './validate_ui_syntax'; import { updateConstructor } from './process_component_constructor'; import { LogType, LogInfo, - componentInfo, - createFunction + componentInfo } from './utils'; import { createReference, isProperty } from './process_component_class'; import { transformLog } from './process_ui_syntax'; -import { globalProgram, projectConfig } from '../main'; - -import { partialUpdateConfig } from '../main'; +import { + globalProgram, + projectConfig, + partialUpdateConfig +} from '../main'; +import { + parentConditionalExpression, + createFunction +} from './process_component_build' export type ControllerType = { hasController: boolean @@ -113,7 +125,7 @@ export const mandatorySpecifyDefaultValueDecorators: Set = new Set([...observedPropertyDecorators, ...appStorageDecorators]); export const forbiddenSpecifyDefaultValueDecorators: Set = - new Set([...propAndLinkDecorators, COMPONENT_CONSUME_DECORATOR, COMPONENT_OBJECT_LINK_DECORATOR]); + new Set([COMPONENT_LINK_DECORATOR, COMPONENT_CONSUME_DECORATOR, COMPONENT_OBJECT_LINK_DECORATOR]); export const mandatoryToInitViaParamDecorators: Set = new Set([...propAndLinkDecorators, COMPONENT_OBJECT_LINK_DECORATOR]); @@ -123,8 +135,10 @@ export const setUpdateParamsDecorators: Set = COMPONENT_BUILDERPARAM_DECORATOR ]); +export const setStateVarsDecorators: Set = new Set([COMPONENT_OBJECT_LINK_DECORATOR]); + export const immutableDecorators: Set = - new Set([COMPONENT_STORAGE_PROP_DECORATOR, COMPONENT_OBJECT_LINK_DECORATOR, COMPONENT_BUILDERPARAM_DECORATOR]); + new Set([COMPONENT_OBJECT_LINK_DECORATOR, COMPONENT_BUILDERPARAM_DECORATOR]); export const simpleTypes: Set = new Set([ts.SyntaxKind.StringKeyword, ts.SyntaxKind.NumberKeyword, ts.SyntaxKind.BooleanKeyword, ts.SyntaxKind.EnumDeclaration]); @@ -144,8 +158,8 @@ export class UpdateResult { private deleteParams: boolean = false; private controllerSet: ts.MethodDeclaration; private purgeVariableDepStatement: ts.Statement; - private rerenderStatement: ts.Statement; private decoratorName: string; + private stateVarsParams: ts.Statement; public setProperity(updateItem: ts.PropertyDeclaration) { this.itemUpdate = true; @@ -177,6 +191,10 @@ export class UpdateResult { this.updateParams = updateParams; } + public setStateVarsParams(stateVarsParams: ts.Statement) { + this.stateVarsParams = stateVarsParams; + } + public setDeleteParams(deleteParams: boolean) { this.deleteParams = deleteParams; } @@ -185,10 +203,6 @@ export class UpdateResult { this.purgeVariableDepStatement = purgeVariableDepStatement; } - public setRerenderStatement(rerenderStatement: ts.Statement) { - this.rerenderStatement = rerenderStatement; - } - public setDecoratorName(decoratorName: string) { this.decoratorName = decoratorName; } @@ -213,12 +227,12 @@ export class UpdateResult { return this.updateParams; } - public getPurgeVariableDepStatement(): ts.Statement { - return this.purgeVariableDepStatement; + public getStateVarsParams(): ts.Statement { + return this.stateVarsParams; } - public getRerenderStatement(): ts.Statement { - return this.rerenderStatement; + public getPurgeVariableDepStatement(): ts.Statement { + return this.purgeVariableDepStatement; } public getVariableGet(): ts.GetAccessorDeclaration { @@ -260,13 +274,35 @@ export function processMemberVariableDecorators(parentName: ts.Identifier, } else if (!item.type) { validatePropertyNonType(name, log); return updateResult; + } else if (validateCustomDecorator(item.decorators, log)) { + updateResult.setUpdateParams(createUpdateParams(name, COMPONENT_CUSTOM_DECORATOR)); } else { processPropertyNodeDecorator(parentName, item, updateResult, ctorNode, name, watchMap, log, program, context, hasPreview, interfaceNode); } + if (item.decorators && item.decorators.length && validatePropDecorator(item.decorators)) { + updateResult.setStateVarsParams(createStateVarsBody(name)); + } return updateResult; } +function createStateVarsBody(name: ts.Identifier): ts.ExpressionStatement { + return ts.factory.createExpressionStatement(ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression( + ts.factory.createPropertyAccessExpression( + ts.factory.createThis(), + ts.factory.createIdentifier("__"+name.escapedText.toString()) + ), + ts.factory.createIdentifier(RESERT) + ), + undefined, + [ts.factory.createPropertyAccessExpression( + ts.factory.createIdentifier(COMPONENT_CONSTRUCTOR_PARAMS), + name + )] + )) +} + function createControllerSet(node: ts.PropertyDeclaration, componentName: ts.Identifier, name: ts.Identifier, checkController: ControllerType): ts.MethodDeclaration { if (componentCollection.customDialogs.has(componentName.getText()) && node.type && @@ -359,13 +395,15 @@ function processStateDecorators(node: ts.PropertyDeclaration, decorator: string, updateResult.setVariableSet(createSetAccessor(name, CREATE_SET_METHOD, node.type)); } if (setUpdateParamsDecorators.has(decorator)) { - updateResult.setUpdateParams(createUpdateParams(name, decorator)); + updateResult.setUpdateParams(createUpdateParams(name, decorator, node)); + } + if (setStateVarsDecorators.has(decorator)) { + updateResult.setStateVarsParams(createStateVarsParams(name, decorator)); } if (partialUpdateConfig.partialUpdateMode && BASICDECORATORS.has(decorator)) { const variableWithUnderLink: string = '__' + name.escapedText.toString(); updateResult.setDecoratorName(decorator); updateResult.setPurgeVariableDepStatement(createPurgeVariableDepStatement(variableWithUnderLink)); - updateResult.setRerenderStatement(createRerenderStatement(variableWithUnderLink)); } } @@ -385,22 +423,6 @@ function createPurgeVariableDepStatement(variableWithUnderLink: string): ts.Stat ); } -function createRerenderStatement(variableWithUnderLink: string): ts.Statement { - return ts.factory.createExpressionStatement( - ts.factory.createCallExpression( - ts.factory.createPropertyAccessExpression( - ts.factory.createPropertyAccessExpression( - ts.factory.createThis(), - ts.factory.createIdentifier(variableWithUnderLink) - ), - ts.factory.createIdentifier(MARKDEPENDENTELEMENTSDIRTY) - ), - undefined, - [ts.factory.createThis()] - ) - ); -} - function processWatch(node: ts.PropertyDeclaration, decorator: ts.Decorator, watchMap: Map, log: LogInfo[]): void { if (node.name) { @@ -466,9 +488,7 @@ function createVariableInitStatement(node: ts.PropertyDeclaration, decorator: st break; case COMPONENT_STORAGE_PROP_DECORATOR: case COMPONENT_STORAGE_LINK_DECORATOR: - const setFuncName: string = decorator === COMPONENT_STORAGE_PROP_DECORATOR ? - APP_STORAGE_SET_AND_PROP : APP_STORAGE_SET_AND_LINK; - updateState = updateStoragePropAndLinkProperty(node, name, setFuncName, log); + updateState = updateStoragePropAndLinkProperty(node, name, decorator, log); break; case COMPONENT_OBJECT_LINK_DECORATOR: updateState = !partialUpdateConfig.partialUpdateMode @@ -501,17 +521,24 @@ function wrongDecoratorInPreview(node: ts.PropertyDeclaration, decorator: string } } -function createUpdateParams(name: ts.Identifier, decorator: string): ts.Statement { +function createUpdateParams(name: ts.Identifier, decorator: string, + localInitializationNode: ts.PropertyDeclaration = undefined): ts.Statement { let updateParamsNode: ts.Statement; switch (decorator) { case COMPONENT_NON_DECORATOR: case COMPONENT_STATE_DECORATOR: case COMPONENT_PROVIDE_DECORATOR: + case COMPONENT_CUSTOM_DECORATOR: updateParamsNode = createUpdateParamsWithIf(name); break; case COMPONENT_PROP_DECORATOR: if (!partialUpdateConfig.partialUpdateMode) { updateParamsNode = createUpdateParamsWithoutIf(name); + } else { + if (localInitializationNode && localInitializationNode.initializer) { + updateParamsNode = createUpdateParamsWithIf(name, true, + localInitializationNode.initializer); + } } break; case COMPONENT_BUILDERPARAM_DECORATOR: @@ -524,14 +551,26 @@ function createUpdateParams(name: ts.Identifier, decorator: string): ts.Statemen return updateParamsNode; } -function createUpdateParamsWithIf(name: ts.Identifier): ts.IfStatement { +function createStateVarsParams(name: ts.Identifier, decorator: string): ts.Statement { + let updateParamsNode: ts.Statement; + switch (decorator) { + case COMPONENT_OBJECT_LINK_DECORATOR: + updateParamsNode = createUpdateParamsWithSet(name); + break; + } + return updateParamsNode; +} + +function createUpdateParamsWithIf(name: ts.Identifier, isSet: boolean = false, + initializeNode: ts.Expression = undefined): ts.IfStatement { return ts.factory.createIfStatement(ts.factory.createBinaryExpression( ts.factory.createPropertyAccessExpression( ts.factory.createIdentifier(CREATE_CONSTRUCTOR_PARAMS), ts.factory.createIdentifier(name.escapedText.toString())), ts.factory.createToken(ts.SyntaxKind.ExclamationEqualsEqualsToken), ts.factory.createIdentifier(COMPONENT_CONSTRUCTOR_UNDEFINED)), ts.factory.createBlock([ - createUpdateParamsWithoutIf(name)], true), undefined); + isSet ? createUpdateParamsWithSet(name) : createUpdateParamsWithoutIf(name)], true), + isSet ? ts.factory.createBlock([createUpdateParamsWithSet(name, true, initializeNode)]) : undefined); } function createUpdateParamsWithoutIf(name: ts.Identifier): ts.ExpressionStatement { @@ -541,11 +580,12 @@ function createUpdateParamsWithoutIf(name: ts.Identifier): ts.ExpressionStatemen createPropertyAccessExpressionWithParams(name.getText()))); } -function createUpdateParamsWithSet(name: ts.Identifier): ts.ExpressionStatement { +function createUpdateParamsWithSet(name: ts.Identifier, hasElse: boolean = false, + initializeNode: ts.Expression = undefined): ts.ExpressionStatement { return ts.factory.createExpressionStatement(ts.factory.createCallExpression( ts.factory.createPropertyAccessExpression(createPropertyAccessExpressionWithThis(`__${name.getText()}`), ts.factory.createIdentifier(CREATE_SET_METHOD)), undefined, - [createPropertyAccessExpressionWithParams(name.getText())])); + [hasElse ? initializeNode : createPropertyAccessExpressionWithParams(name.getText())])); } function updateNormalProperty(node: ts.PropertyDeclaration, name: ts.Identifier, @@ -595,14 +635,31 @@ function updateSynchedPropertyOneWay(nameIdentifier: ts.Identifier, type: ts.Typ } function updateStoragePropAndLinkProperty(node: ts.PropertyDeclaration, name: ts.Identifier, - setFuncName: string, log: LogInfo[]): ts.ExpressionStatement { + decorator: string, log: LogInfo[]): ts.ExpressionStatement { if (isSingleKey(node)) { + let setFuncName: string; + let storageFuncName: string; + const storageValue: ts.Expression[] = [ + node.decorators[0].expression.arguments[0], + node.initializer, + ts.factory.createThis(), + ts.factory.createStringLiteral(name.getText()) + ]; + if (!partialUpdateConfig.partialUpdateMode) { + setFuncName = decorator === COMPONENT_STORAGE_PROP_DECORATOR ? + APP_STORAGE_SET_AND_PROP : APP_STORAGE_SET_AND_LINK; + storageFuncName = APP_STORAGE; + } else { + setFuncName = decorator === COMPONENT_STORAGE_PROP_DECORATOR ? + CREATE_STORAGE_PROP : CREATE_STORAGE_LINK; + storageFuncName = THIS; + storageValue.splice(2, 1); + } return ts.factory.createExpressionStatement(ts.factory.createBinaryExpression( createPropertyAccessExpressionWithThis(`__${name.getText()}`), ts.factory.createToken(ts.SyntaxKind.EqualsToken), ts.factory.createCallExpression( - ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier(APP_STORAGE), - ts.factory.createIdentifier(setFuncName)), undefined, [node.decorators[0].expression.arguments[0], - node.initializer, ts.factory.createThis(), ts.factory.createStringLiteral(name.getText())]))); + ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier(storageFuncName), + ts.factory.createIdentifier(setFuncName)), undefined, storageValue))); } else { validateAppStorageDecoractorsNonSingleKey(node, log); } @@ -671,14 +728,16 @@ export function createViewCreate(node: ts.NewExpression | ts.Identifier): ts.Cal } export function createCustomComponentNewExpression(node: ts.CallExpression, name: string, - isInnerBuilder: boolean = false): ts.NewExpression { + isBuilder: boolean = false, isGlobalBuilder: boolean = false, + isCutomDialog: boolean = false): ts.NewExpression { const newNode: ts.NewExpression = ts.factory.createNewExpression(node.expression, node.typeArguments, node.arguments.length ? node.arguments : []); - return addCustomComponentId(newNode, name, isInnerBuilder); + return addCustomComponentId(newNode, name, isBuilder, isGlobalBuilder, isCutomDialog); } function addCustomComponentId(node: ts.NewExpression, componentName: string, - isInnerBuilder: boolean = false): ts.NewExpression { + isBuilder: boolean = false, isGlobalBuilder: boolean = false, + isCutomDialog: boolean = false): ts.NewExpression { for (const item of componentCollection.customComponents) { componentInfo.componentNames.add(item); } @@ -693,18 +752,16 @@ function addCustomComponentId(node: ts.NewExpression, componentName: string, } if (!partialUpdateConfig.partialUpdateMode) { ++componentInfo.id; - argumentsArray.unshift(isInnerBuilder ? ts.factory.createBinaryExpression( + argumentsArray.unshift(isBuilder ? ts.factory.createBinaryExpression( ts.factory.createStringLiteral(path.basename(transformLog.sourceFile.fileName, EXTNAME_ETS) + '_'), ts.factory.createToken(ts.SyntaxKind.PlusToken), ts.factory.createIdentifier(_GENERATE_ID)) : ts.factory.createStringLiteral(componentInfo.id.toString()), - isInnerBuilder ? ts.factory.createConditionalExpression( - ts.factory.createIdentifier(COMPONENT_CONSTRUCTOR_PARENT), - ts.factory.createToken(ts.SyntaxKind.QuestionToken), - ts.factory.createIdentifier(COMPONENT_CONSTRUCTOR_PARENT), - ts.factory.createToken(ts.SyntaxKind.ColonToken), ts.factory.createThis() - ) : ts.factory.createThis()); + isBuilder ? parentConditionalExpression() : ts.factory.createThis()); } else { - argumentsArray.unshift(ts.factory.createThis()); + argumentsArray.unshift(isGlobalBuilder ? parentConditionalExpression() : ts.factory.createThis()); + if (!isCutomDialog) { + argumentsArray.push(ts.factory.createIdentifier('undefined'), ts.factory.createIdentifier(ELMTID)); + } } node = ts.factory.updateNewExpression(node, node.expression, node.typeArguments, argumentsArray); @@ -738,10 +795,14 @@ function createPropertyAccessExpressionWithThis(propertyName: string): ts.Proper function addAddProvidedVar(node: ts.PropertyDeclaration, name: ts.Identifier, decoratorName: string, updateState: ts.Statement[]): void { if (decoratorName === COMPONENT_PROVIDE_DECORATOR) { + let parameterName: string; if (isSingleKey(node)) { - updateState.push(createAddProvidedVar(getDecoratorKey(node), name)); + parameterName = getDecoratorKey(node); + updateState.push(createAddProvidedVar(parameterName, name)); + } + if (parameterName !== name.getText()) { + updateState.push(createAddProvidedVar(name.getText(), name)); } - updateState.push(createAddProvidedVar(name.getText(), name)); } } @@ -786,6 +847,7 @@ function isForbiddenUseStateType(typeNode: ts.TypeNode): boolean { } export function isSimpleType(typeNode: ts.TypeNode, program: ts.Program, log?: LogInfo[]): boolean { + typeNode = typeNode || ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword); let checker: ts.TypeChecker; if (globalProgram.program) { checker = globalProgram.program.getTypeChecker(); @@ -794,47 +856,51 @@ export function isSimpleType(typeNode: ts.TypeNode, program: ts.Program, log?: L } else if (program) { checker = program.getTypeChecker(); } - const enumType: ts.SyntaxKind = getEnumType(typeNode, checker); - if (simpleTypes.has(enumType || typeNode.kind) || isEnumtype(typeNode)) { + return getDeclarationType(typeNode, checker, log); +} + +function getDeclarationType(typeNode: ts.TypeNode, checker: ts.TypeChecker, log: LogInfo[]): boolean { + if (simpleTypes.has(typeNode.kind)) { return true; - } else if (ts.isUnionTypeNode(typeNode) && typeNode.types) { - const types: ts.NodeArray = typeNode.types; - let basicType: boolean = false; - let referenceType: boolean = false; - for (let i = 0; i < types.length; i++) { - const enumType: ts.SyntaxKind = getEnumType(types[i], checker); - if (simpleTypes.has(enumType || types[i].kind) || isEnumtype(typeNode)) { - basicType = true; - } else { - referenceType = true; + } + if (checker) { + const type: ts.Type = checker.getTypeFromTypeNode(typeNode); + /* Enum */ + if (type.flags & (32 | 1024)) { + return true; + } + // @ts-ignore + if (type.types && type.types.length) { + // @ts-ignore + const types = type.types; + let basicType: boolean = false; + let referenceType: boolean = false; + for (let i = 0; i < types.length; i++) { + if (isBasicType(types[i].flags)) { + basicType = true; + } else { + referenceType = true; + } } if (basicType && referenceType && log) { validateVariableType(typeNode, log); return false; } + if (!referenceType) { + return true; + } } - return true; } return false; } -function getEnumType(typeNode: ts.TypeNode, checker: ts.TypeChecker): ts.SyntaxKind { - if (!checker) { - return; - } - if (ts.isTypeReferenceNode(typeNode) && ts.isIdentifier(typeNode.typeName)) { - const type: ts.Type = - checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(typeNode.typeName)); - if (type.symbol && type.symbol.valueDeclaration) { - return type.symbol.valueDeclaration.kind; - } - } -} - -function isEnumtype(typeNode: ts.TypeNode): boolean { - if (ts.isTypeReferenceNode(typeNode) && ts.isIdentifier(typeNode.typeName)) { - return enumCollection.has(typeNode.typeName.getText()); +function isBasicType(flags: number): boolean { + if (flags & (4 | /* String */ 8 | /* Number */ 16 | /* Boolean */ 32 | /* Enum */ 64 | /* BigInt */ + 128 | /* StringLiteral */ 256 | /* NumberLiteral */ 512 /* BooleanLiteral */| 1024 /* EnumLiteral */| + 2048 /* BigIntLiteral */)) { + return true; } + return false; } function isObservedClassType(type: ts.TypeNode): boolean { @@ -995,7 +1061,9 @@ function validateWatchParam(type: LogType, pos: number, log: LogInfo[]): void { function validateVariableType(typeNode: ts.TypeNode, log: LogInfo[]): void { log.push({ type: LogType.ERROR, - message: 'The state variable type of a struct component cannot be declared by both a simple type and an object type.', + message: `The state variable type here is '${typeNode.getText()}', ` + + `it contains both a simple type and an object type,\n ` + + `which are not allowed to be defined for state variable of a struct.`, pos: typeNode.getStart() }); } @@ -1022,11 +1090,12 @@ function updateSynchedPropertyTwoWayPU(nameIdentifier: ts.Identifier, type: ts.T function updateSynchedPropertyOneWayPU(nameIdentifier: ts.Identifier, type: ts.TypeNode, decoractor: string, log: LogInfo[], program: ts.Program): ts.ExpressionStatement { const name: string = nameIdentifier.escapedText.toString(); - if (isSimpleType(type, program)) { + if (isSimpleType(type, program, log)) { return createInitExpressionStatementForDecorator(name, SYNCHED_PROPERTY_SIMPLE_ONE_WAY_PU, createPropertyAccessExpressionWithParams(name)); } else { - validateNonSimpleType(nameIdentifier, decoractor, log); + return createInitExpressionStatementForDecorator(name, SYNCHED_PROPERTY_OBJECT_ONE_WAY_PU, + createPropertyAccessExpressionWithParams(name)); } } @@ -1039,3 +1108,41 @@ function updateSynchedPropertyNesedObjectPU(nameIdentifier: ts.Identifier, validateNonObservedClassType(nameIdentifier, decoractor, log); } } + +function validateCustomDecorator(decorators: ts.NodeArray, log: LogInfo[]): boolean { + let hasInnerDecorator: boolean = false; + let hasCustomDecorator: boolean = false; + let innerDecorator: ts.Decorator; + for(let i = 0; i < decorators.length; i++) { + let decorator: ts.Decorator = decorators[i]; + const decoratorName: string = decorator.getText().replace(/\(.*\)$/, '').trim(); + if (INNER_COMPONENT_MEMBER_DECORATORS.has(decoratorName)) { + hasInnerDecorator = true; + innerDecorator = innerDecorator ? innerDecorator : decorator; + } else { + hasCustomDecorator = true; + } + } + if (hasCustomDecorator && hasInnerDecorator) { + log.push({ + type: LogType.ERROR, + message: `The inner decorator ${innerDecorator.getText()} cannot be used together with custom decorator.`, + pos: innerDecorator.getStart() + }); + } else if(!hasInnerDecorator) { + return true; + } + return false; +} + +function validatePropDecorator(decorators: ts.NodeArray): boolean { + for(let i = 0; i < decorators.length; i++) { + let decorator: ts.Decorator = decorators[i]; + const decoratorName: string = decorator.getText().replace(/\(.*\)$/, '').trim(); + if (COMPONENT_PROP_DECORATOR === decoratorName) { + return true; + } + } + return false; +} + diff --git a/compiler/src/process_custom_component.ts b/compiler/src/process_custom_component.ts index 7f6eeac022868ca9613c1e6efb5b2a90b05f61ac..5b1d2afac9aed882374d79453570ce8cd62683d9 100644 --- a/compiler/src/process_custom_component.ts +++ b/compiler/src/process_custom_component.ts @@ -41,7 +41,11 @@ import { STOPGETACCESSRECORDING, ALLOCATENEWELMETIDFORNEXTCOMPONENT, STATE_OBJECTLINK_DECORATORS, - BASE_COMPONENT_NAME_PU + BASE_COMPONENT_NAME_PU, + OBSERVECOMPONENTCREATION, + ISINITIALRENDER, + UPDATE_STATE_VARS_OF_CHIND_BY_ELMTID, + COMPONENT_CUSTOM_DECORATOR } from './pre_define'; import { propertyCollection, @@ -55,44 +59,48 @@ import { consumeCollection, objectLinkCollection, isStaticViewCollection, - builderParamObjectCollection + builderParamObjectCollection, + getLocalStorageCollection } from './validate_ui_syntax'; import { propAndLinkDecorators, curPropMap, - observedPropertyDecorators, createViewCreate, createCustomComponentNewExpression } from './process_component_member'; import { LogType, LogInfo, - componentInfo, - createFunction + componentInfo } from './utils'; -import { bindComponentAttr } from './process_component_build'; -import { partialUpdateConfig } from '../main'; - -const localArray: string[] = [...observedPropertyDecorators, COMPONENT_NON_DECORATOR, - COMPONENT_PROP_DECORATOR, COMPONENT_OBJECT_LINK_DECORATOR]; +import { + bindComponentAttr, + parentConditionalExpression, + createComponentCreationStatement, + createFunction +} from './process_component_build'; +import { + partialUpdateConfig +} from '../main'; -const decoractorMap: Map>> = new Map( - [[COMPONENT_STATE_DECORATOR, stateCollection], - [COMPONENT_LINK_DECORATOR, linkCollection], - [COMPONENT_PROP_DECORATOR, propCollection], - [COMPONENT_NON_DECORATOR, regularCollection], - [COMPONENT_PROVIDE_DECORATOR, provideCollection], - [COMPONENT_OBJECT_LINK_DECORATOR, objectLinkCollection]]); +let decoractorMap: Map>>; export function processCustomComponent(node: ts.ExpressionStatement, newStatements: ts.Statement[], - log: LogInfo[], name: string, isInnerBuilder: boolean = false): void { + log: LogInfo[], name: string, isBuilder: boolean = false, isGlobalBuilder: boolean = false): void { + decoractorMap = new Map( + [[COMPONENT_STATE_DECORATOR, stateCollection], + [COMPONENT_LINK_DECORATOR, linkCollection], + [COMPONENT_PROP_DECORATOR, propCollection], + [COMPONENT_NON_DECORATOR, regularCollection], + [COMPONENT_PROVIDE_DECORATOR, provideCollection], + [COMPONENT_OBJECT_LINK_DECORATOR, objectLinkCollection]]); const componentNode: ts.CallExpression = getCustomComponentNode(node); if (componentNode) { const hasChainCall: boolean = componentNode.parent && ts.isPropertyAccessExpression(componentNode.parent); let ischangeNode: boolean = false; let customComponentNewExpression: ts.NewExpression = createCustomComponentNewExpression( - componentNode, name, isInnerBuilder); + componentNode, name, isBuilder, isGlobalBuilder); let argumentsArray: ts.PropertyAssignment[]; if (isHasChild(componentNode)) { // @ts-ignore @@ -110,17 +118,25 @@ export function processCustomComponent(node: ts.ExpressionStatement, newStatemen ts.factory.createNewExpression(componentNode.expression, componentNode.typeArguments, [ts.factory.createObjectLiteralExpression(argumentsArray, true)])); customComponentNewExpression = createCustomComponentNewExpression( - newNode.expression as ts.CallExpression, name, isInnerBuilder); + newNode.expression as ts.CallExpression, name, isBuilder); } } if (hasChainCall) { - newStatements.push(ts.factory.createExpressionStatement( - createFunction(ts.factory.createIdentifier(COMPONENT_COMMON), - ts.factory.createIdentifier(COMPONENT_CREATE_FUNCTION), null))); - bindComponentAttr(node, ts.factory.createIdentifier(COMPONENT_COMMON), newStatements, log); + if (partialUpdateConfig.partialUpdateMode) { + const commomComponentNode: ts.Statement[] = [ts.factory.createExpressionStatement( + createFunction(ts.factory.createIdentifier(COMPONENT_COMMON), + ts.factory.createIdentifier(COMPONENT_CREATE_FUNCTION), null))]; + bindComponentAttr(node, ts.factory.createIdentifier(COMPONENT_COMMON), commomComponentNode, log); + newStatements.push(createComponentCreationStatement(componentAttributes(), commomComponentNode, isGlobalBuilder)); + } else { + newStatements.push(ts.factory.createExpressionStatement( + createFunction(ts.factory.createIdentifier(COMPONENT_COMMON), + ts.factory.createIdentifier(COMPONENT_CREATE_FUNCTION), null))); + bindComponentAttr(node, ts.factory.createIdentifier(COMPONENT_COMMON), newStatements, log); + } } addCustomComponent(node, newStatements, customComponentNewExpression, log, name, componentNode, - isInnerBuilder); + isBuilder, isGlobalBuilder); if (hasChainCall) { newStatements.push(ts.factory.createExpressionStatement( createFunction(ts.factory.createIdentifier(COMPONENT_COMMON), @@ -129,6 +145,16 @@ export function processCustomComponent(node: ts.ExpressionStatement, newStatemen } } +function componentAttributes(): ts.Statement { + return ts.factory.createExpressionStatement( + ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression( + ts.factory.createIdentifier(COMPONENT_COMMON), + ts.factory.createIdentifier(COMPONENT_POP_FUNCTION) + ), undefined, [] + )); +} + function isHasChild(node: ts.CallExpression): boolean { return node.arguments && node.arguments[0] && ts.isObjectLiteralExpression(node.arguments[0]) && node.arguments[0].properties && node.arguments[0].properties.length > 0; @@ -152,70 +178,114 @@ function changeNodeFromCallToArrow(node: ts.CallExpression): ts.ArrowFunction { function addCustomComponent(node: ts.ExpressionStatement, newStatements: ts.Statement[], newNode: ts.NewExpression, log: LogInfo[], name: string, componentNode: ts.CallExpression, - isInnerBuilder: boolean = false): void { + isBuilder: boolean = false, isGlobalBuilder: boolean = false): void { if (ts.isNewExpression(newNode)) { const propertyArray: ts.ObjectLiteralElementLike[] = []; validateCustomComponentPrams(componentNode, name, propertyArray, log); - addCustomComponentStatements(node, newStatements, newNode, name, propertyArray, isInnerBuilder); + addCustomComponentStatements(node, newStatements, newNode, name, propertyArray, componentNode, isBuilder, isGlobalBuilder); } } function addCustomComponentStatements(node: ts.ExpressionStatement, newStatements: ts.Statement[], newNode: ts.NewExpression, name: string, props: ts.ObjectLiteralElementLike[], - isInnerBuilder: boolean = false): void { + componentNode: ts.CallExpression, isBuilder: boolean = false, isGlobalBuilder: boolean = false): void { if (!partialUpdateConfig.partialUpdateMode) { const id: string = componentInfo.id.toString(); - newStatements.push(createFindChildById(id, name, isInnerBuilder), createCustomComponentIfStatement(id, + newStatements.push(createFindChildById(id, name, isBuilder), createCustomComponentIfStatement(id, ts.factory.updateExpressionStatement(node, createViewCreate(newNode)), ts.factory.createObjectLiteralExpression(props, true), name)); } else { - newStatements.push(createCustomComponent(newNode)); + newStatements.push(createCustomComponent(node, newNode, name, componentNode, isGlobalBuilder)); + } +} + +function createChildElmtId(node: ts.CallExpression, name: string): ts.PropertyAssignment[] { + const propsAndObjectLinks: string[] = []; + const childParam: ts.PropertyAssignment[] = []; + if (propCollection.get(name)) { + propsAndObjectLinks.push(...propCollection.get(name)); + } + if (objectLinkCollection.get(name)) { + propsAndObjectLinks.push(...objectLinkCollection.get(name)); } + if (node.arguments[0].properties) { + node.arguments[0].properties.forEach(item => { + if (ts.isIdentifier(item.name) && propsAndObjectLinks.includes(item.name.escapedText.toString())) { + childParam.push(item); + } + }) + } + return childParam; } -function createCustomComponent(newNode: ts.NewExpression): ts.Block { +function createCustomComponent(node: ts.ExpressionStatement, newNode: ts.NewExpression, name: string, + componentNode: ts.CallExpression, isGlobalBuilder: boolean = false): ts.Block { + let componentParameter: ts.ObjectLiteralExpression; + if (componentNode.arguments && componentNode.arguments.length) { + componentParameter = ts.factory.createObjectLiteralExpression(createChildElmtId(componentNode, name), true); + } else { + componentParameter = ts.factory.createObjectLiteralExpression([], false); + } return ts.factory.createBlock( [ - ts.factory.createVariableStatement(undefined, - ts.factory.createVariableDeclarationList( - [ts.factory.createVariableDeclaration( - ts.factory.createIdentifier(ELMTID), undefined, undefined, - ts.factory.createCallExpression( - ts.factory.createPropertyAccessExpression( - ts.factory.createIdentifier(VIEWSTACKPROCESSOR), - ts.factory.createIdentifier(ALLOCATENEWELMETIDFORNEXTCOMPONENT) - ), undefined, []))], - ts.NodeFlags.Const - ) - ), - ts.factory.createExpressionStatement( - ts.factory.createCallExpression( - ts.factory.createPropertyAccessExpression( - ts.factory.createIdentifier(VIEWSTACKPROCESSOR), - ts.factory.createIdentifier(STARTGETACCESSRECORDINGFOR) - ), undefined, - [ts.factory.createIdentifier(ELMTID)] - ) - ), - ts.factory.createExpressionStatement( - ts.factory.createCallExpression( - ts.factory.createPropertyAccessExpression( - ts.factory.createIdentifier(BASE_COMPONENT_NAME_PU), - ts.factory.createIdentifier(COMPONENT_CREATE_FUNCTION) - ), undefined, - [newNode] - ) - ), - ts.factory.createExpressionStatement( - ts.factory.createCallExpression( - ts.factory.createPropertyAccessExpression( - ts.factory.createIdentifier(VIEWSTACKPROCESSOR), - ts.factory.createIdentifier(STOPGETACCESSRECORDING) - ), undefined, [] - ) - ) - ], - true + ts.factory.createExpressionStatement(ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression(isGlobalBuilder ? + ts.factory.createParenthesizedExpression(parentConditionalExpression()) : ts.factory.createThis(), + ts.factory.createIdentifier(OBSERVECOMPONENTCREATION) + ), undefined, + [ts.factory.createArrowFunction(undefined, undefined, + [ + ts.factory.createParameterDeclaration(undefined, undefined, undefined, + ts.factory.createIdentifier(ELMTID) + ), + ts.factory.createParameterDeclaration(undefined, undefined, undefined, + ts.factory.createIdentifier(ISINITIALRENDER) + ) + ], undefined, + ts.factory.createToken(ts.SyntaxKind.EqualsGreaterThanToken), + ts.factory.createBlock( + [ + ts.factory.createExpressionStatement( + ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression( + ts.factory.createIdentifier(VIEWSTACKPROCESSOR), + ts.factory.createIdentifier(STARTGETACCESSRECORDINGFOR) + ), undefined, + [ts.factory.createIdentifier(ELMTID)] + )), + createIfCustomComponent(newNode, componentParameter, isGlobalBuilder), + ts.factory.createExpressionStatement(ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression( + ts.factory.createIdentifier(VIEWSTACKPROCESSOR), + ts.factory.createIdentifier(STOPGETACCESSRECORDING) + ), + undefined, + [] + )) + ], true))])) + ], true); +} + +function createIfCustomComponent(newNode: ts.NewExpression, componentParameter: ts.ObjectLiteralExpression, + isGlobalBuilder: boolean = false): ts.IfStatement { + return ts.factory.createIfStatement( + ts.factory.createIdentifier(ISINITIALRENDER), + ts.factory.createBlock( + [ + ts.factory.createExpressionStatement( + ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression( + ts.factory.createIdentifier(BASE_COMPONENT_NAME_PU), + ts.factory.createIdentifier(COMPONENT_CREATE_FUNCTION) + ), undefined, [newNode])) + ], true), + ts.factory.createBlock( + [ts.factory.createExpressionStatement(ts.factory.createCallExpression( + ts.factory.createPropertyAccessExpression(isGlobalBuilder ? + ts.factory.createParenthesizedExpression(parentConditionalExpression()) : ts.factory.createThis(), + ts.factory.createIdentifier(UPDATE_STATE_VARS_OF_CHIND_BY_ELMTID) + ), undefined, + [ts.factory.createIdentifier(ELMTID), componentParameter]))], true) ); } @@ -289,7 +359,10 @@ function isThisProperty(node: ts.ObjectLiteralElementLike, propertySet: Set): boolean { if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && - node.initializer.escapedText && node.initializer.escapedText.includes('$')) { + (node.initializer.escapedText && node.initializer.escapedText.includes('$') || + ts.isPropertyAccessExpression(node.initializer) && node.initializer.expression && + node.initializer.expression.kind === ts.SyntaxKind.ThisKeyword && + ts.isIdentifier(node.initializer.name) && node.initializer.name.escapedText.toString().includes('$'))) { return false; } if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && @@ -308,28 +381,41 @@ function validateStateManagement(node: ts.ObjectLiteralElementLike, customCompon function checkFromParentToChild(node: ts.ObjectLiteralElementLike, customComponentName: string, log: LogInfo[]): void { let propertyName: string; - if (node.name && node.name.escapedText) { - // @ts-ignore + if (ts.isIdentifier(node.name)) { propertyName = node.name.escapedText.toString(); } const curPropertyKind: string = getPropertyDecoratorKind(propertyName, customComponentName); + let parentPropertyName: string; if (curPropertyKind) { if (isInitFromParent(node)) { - const parentPropertyName: string = + parentPropertyName = getParentPropertyName(node as ts.PropertyAssignment, curPropertyKind, log); - if (!parentPropertyName) { - return; + let parentPropertyKind: string = curPropMap.get(parentPropertyName); + if (!parentPropertyKind) { + parentPropertyKind = COMPONENT_NON_DECORATOR; } - const parentPropertyKind: string = curPropMap.get(parentPropertyName); if (parentPropertyKind && !isCorrectInitFormParent(parentPropertyKind, curPropertyKind)) { validateIllegalInitFromParent( node, propertyName, curPropertyKind, parentPropertyName, parentPropertyKind, log); } - } else if (isInitFromLocal(node) && ts.isPropertyAssignment(node)) { - if (!localArray.includes(curPropertyKind)) { + } else if (isInitFromLocal(node) && ts.isPropertyAssignment(node) && + curPropertyKind !== COMPONENT_OBJECT_LINK_DECORATOR) { + if (!isCorrectInitFormParent(COMPONENT_NON_DECORATOR, curPropertyKind)) { validateIllegalInitFromParent(node, propertyName, curPropertyKind, node.initializer.getText(), COMPONENT_NON_DECORATOR, log); } + } else if (curPropertyKind === COMPONENT_OBJECT_LINK_DECORATOR && node.initializer && + (ts.isPropertyAccessExpression(node.initializer) || + ts.isElementAccessExpression(node.initializer))) { + return; + } else { + parentPropertyName = + getParentPropertyName(node as ts.PropertyAssignment, curPropertyKind, log) || propertyName; + const parentPropertyKind = COMPONENT_NON_DECORATOR; + if (!isCorrectInitFormParent(parentPropertyKind, curPropertyKind)) { + validateIllegalInitFromParent( + node, propertyName, curPropertyKind, parentPropertyName, parentPropertyKind, log, LogType.WARN); + } } } } @@ -356,8 +442,11 @@ function isInitFromLocal(node: ts.ObjectLiteralElementLike): boolean { function getParentPropertyName(node: ts.PropertyAssignment, curPropertyKind: string, log: LogInfo[]): string { - let parentPropertyName: string; const initExpression: ts.Expression = node.initializer; + if (!initExpression) { + return undefined; + } + let parentPropertyName: string = initExpression.getText(); if (curPropertyKind === COMPONENT_LINK_DECORATOR) { if (hasDollar(initExpression)) { // @ts-ignore @@ -370,45 +459,30 @@ function getParentPropertyName(node: ts.PropertyAssignment, curPropertyKind: str if (hasDollar(initExpression)) { validateNonLinkWithDollar(node, log); } else { - // @ts-ignore - parentPropertyName = node.initializer.name.getText(); + // @ts-ignore + if (node.initializer && node.initializer.name) { + parentPropertyName = node.initializer.name.getText(); + } } } + return parentPropertyName; } function isCorrectInitFormParent(parent: string, child: string): boolean { switch (child) { case COMPONENT_STATE_DECORATOR: - case COMPONENT_PROVIDE_DECORATOR: - if (parent === COMPONENT_NON_DECORATOR) { - return true; - } - break; - case COMPONENT_LINK_DECORATOR: - if ([COMPONENT_STATE_DECORATOR, COMPONENT_LINK_DECORATOR, - COMPONENT_STORAGE_LINK_DECORATOR].includes(parent)) { - return true; - } - break; case COMPONENT_PROP_DECORATOR: - if ([COMPONENT_STATE_DECORATOR, ...propAndLinkDecorators].includes(parent)) { - return true; - } - break; + case COMPONENT_PROVIDE_DECORATOR: + return true; case COMPONENT_NON_DECORATOR: - if ([COMPONENT_STATE_DECORATOR, ...propAndLinkDecorators, COMPONENT_NON_DECORATOR, + if ([COMPONENT_NON_DECORATOR, COMPONENT_STATE_DECORATOR, COMPONENT_LINK_DECORATOR, COMPONENT_PROP_DECORATOR, COMPONENT_OBJECT_LINK_DECORATOR, COMPONENT_STORAGE_LINK_DECORATOR].includes(parent)) { return true; } break; - case COMPONENT_OBJECT_LINK_DECORATOR: - if (!partialUpdateConfig.partialUpdateMode && parent === COMPONENT_STATE_DECORATOR) { - return true; - } else if (partialUpdateConfig.partialUpdateMode && STATE_OBJECTLINK_DECORATORS.includes(parent)) { - return true; - } - break; + case COMPONENT_LINK_DECORATOR: + return ![COMPONENT_NON_DECORATOR].includes(parent); } return false; } @@ -421,7 +495,7 @@ function getPropertyDecoratorKind(propertyName: string, customComponentName: str } } -function createFindChildById(id: string, name: string, isInnerBuilder: boolean = false): ts.VariableStatement { +function createFindChildById(id: string, name: string, isBuilder: boolean = false): ts.VariableStatement { return ts.factory.createVariableStatement(undefined, ts.factory.createVariableDeclarationList( [ts.factory.createVariableDeclaration(ts.factory.createIdentifier( `${CUSTOM_COMPONENT_EARLIER_CREATE_CHILD}${id}`), undefined, ts.factory.createTypeReferenceNode( @@ -429,27 +503,24 @@ function createFindChildById(id: string, name: string, isInnerBuilder: boolean = ts.factory.createConditionalExpression( ts.factory.createParenthesizedExpression( ts.factory.createBinaryExpression( - createConditionParent(isInnerBuilder), + createConditionParent(isBuilder), ts.factory.createToken(ts.SyntaxKind.AmpersandAmpersandToken), ts.factory.createPropertyAccessExpression( - createConditionParent(isInnerBuilder), + createConditionParent(isBuilder), ts.factory.createIdentifier(CUSTOM_COMPONENT_FUNCTION_FIND_CHILD_BY_ID) ))), ts.factory.createToken(ts.SyntaxKind.QuestionToken), ts.factory.createAsExpression(ts.factory.createCallExpression( - ts.factory.createPropertyAccessExpression(createConditionParent(isInnerBuilder), + ts.factory.createPropertyAccessExpression(createConditionParent(isBuilder), ts.factory.createIdentifier(`${CUSTOM_COMPONENT_FUNCTION_FIND_CHILD_BY_ID}`)), undefined, - [isInnerBuilder ? ts.factory.createCallExpression(ts.factory.createIdentifier(GENERATE_ID), + [isBuilder ? ts.factory.createCallExpression(ts.factory.createIdentifier(GENERATE_ID), undefined, []) : ts.factory.createStringLiteral(id)]), ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(name))), ts.factory.createToken(ts.SyntaxKind.ColonToken), ts.factory.createIdentifier('undefined')))], ts.NodeFlags.Let)); } -function createConditionParent(isInnerBuilder: boolean): ts.ParenthesizedExpression | ts.ThisExpression { - return isInnerBuilder ? ts.factory.createParenthesizedExpression(ts.factory.createConditionalExpression( - ts.factory.createIdentifier(COMPONENT_CONSTRUCTOR_PARENT), ts.factory.createToken(ts.SyntaxKind.QuestionToken), - ts.factory.createIdentifier(COMPONENT_CONSTRUCTOR_PARENT), ts.factory.createToken(ts.SyntaxKind.ColonToken), - ts.factory.createThis())) : ts.factory.createThis(); +export function createConditionParent(isBuilder: boolean): ts.ParenthesizedExpression | ts.ThisExpression { + return isBuilder ? ts.factory.createParenthesizedExpression(parentConditionalExpression()) : ts.factory.createThis(); } function createCustomComponentIfStatement(id: string, node: ts.ExpressionStatement, @@ -502,10 +573,13 @@ function validateForbiddenToInitViaParam(node: ts.ObjectLiteralElementLike, const forbiddenToInitViaParamSet: Set = new Set([ ...getCollectionSet(customComponentName, storageLinkCollection), ...getCollectionSet(customComponentName, storagePropCollection), - ...getCollectionSet(customComponentName, consumeCollection)]); - if (isThisProperty(node, forbiddenToInitViaParamSet)) { + ...getCollectionSet(customComponentName, consumeCollection) + ]); + const localStorageSet: Set = new Set(); + getLocalStorageCollection(customComponentName, localStorageSet); + if (isThisProperty(node, forbiddenToInitViaParamSet) || isThisProperty(node, localStorageSet)) { log.push({ - type: LogType.ERROR, + type: localStorageSet.has(node.name.getText()) ? LogType.WARN : LogType.ERROR, message: `Property '${node.name.getText()}' in the custom component '${customComponentName}'` + ` cannot initialize here (forbidden to specify).`, pos: node.name.getStart() @@ -558,13 +632,20 @@ function validateMandatoryToInitViaParam(node: ts.ExpressionStatement, customCom function validateIllegalInitFromParent(node: ts.ObjectLiteralElementLike, propertyName: string, curPropertyKind: string, parentPropertyName: string, parentPropertyKind: string, - log: LogInfo[]): void { + log: LogInfo[], inputType: LogType = undefined): void { + let type: LogType = LogType.ERROR; + if (inputType) { + type = inputType; + } else if ([COMPONENT_STATE_DECORATOR, COMPONENT_OBJECT_LINK_DECORATOR].includes( + parentPropertyKind) && curPropertyKind === COMPONENT_OBJECT_LINK_DECORATOR) { + type = LogType.WARN; + } log.push({ - type: LogType.ERROR, + type: type, message: `The ${parentPropertyKind} property '${parentPropertyName}' cannot be assigned to ` + `the ${curPropertyKind} property '${propertyName}'.`, // @ts-ignore - pos: node.initializer.getStart() + pos: node.initializer ? node.initializer.getStart() : node.getStart() }); } diff --git a/compiler/src/process_har_writejs.ts b/compiler/src/process_har_writejs.ts new file mode 100644 index 0000000000000000000000000000000000000000..7863e46977d22e334a36bed3cebca7940ed559e2 --- /dev/null +++ b/compiler/src/process_har_writejs.ts @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2023 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 { generateSourceFilesInHar } from './utils'; +import { projectConfig } from '../main.js'; + +module.exports = function writejsfile(source: string): string { + generateSourceFilesInHar(this.resourcePath, source, '.js', projectConfig); + return source; +}; diff --git a/compiler/src/process_import.ts b/compiler/src/process_import.ts index b00fd699c2869d0c472e6a1823cd53cbe846485f..ac9b026892fa9c732b0e308622d64e2a7e674cbd 100644 --- a/compiler/src/process_import.ts +++ b/compiler/src/process_import.ts @@ -19,15 +19,14 @@ import path from 'path'; import { EXTNAME_ETS, - NODE_MODULES, + EXTNAME_TS, INDEX_ETS, - PACKAGE_JSON, - STRUCT, - CLASS, + INDEX_TS, CUSTOM_COMPONENT_DEFAULT, CUSTOM_DECORATOR_NAME, COMPONENT_DECORATOR_ENTRY, - COMPONENT_BUILDER_DECORATOR + COMPONENT_BUILDER_DECORATOR, + CARD_LOG_TYPE_IMPORT } from './pre_define'; import { propertyCollection, @@ -43,14 +42,29 @@ import { enumCollection, getComponentSet, IComponentSet, - builderParamObjectCollection + builderParamObjectCollection, + stateCollection, + regularCollection, + storagePropCollection, + storageLinkCollection, + provideCollection, + consumeCollection, + objectLinkCollection, + localStorageLinkCollection, + localStoragePropCollection } from './validate_ui_syntax'; -import { hasDecorator, LogInfo, LogType, repeatLog } from './utils'; +import { + getExtensionIfUnfullySpecifiedFilepath, + hasDecorator, + LogInfo, + LogType, + repeatLog +} from './utils'; import { projectConfig } from '../main'; -import { isOhmUrl, resolveSourceFile } from './resolve_ohm_url'; -import { CUSTOM_BUILDER_METHOD } from './component_map'; +import { CUSTOM_BUILDER_METHOD, INNER_COMPONENT_NAMES } from './component_map'; +import { validatorCard } from './process_ui_syntax'; -const IMPORT_FILE_ASTCACHE: Map = new Map(); +export const IMPORT_FILE_ASTCACHE: Map = new Map(); export default function processImport(node: ts.ImportDeclaration | ts.ImportEqualsDeclaration | ts.ExportDeclaration, pagesDir: string, log: LogInfo[], asName: Map = new Map(), @@ -71,6 +85,7 @@ isEntryPage: boolean = true, pathCollection: Set = new Set()): void { node.importClause.namedBindings.elements && isEntryPage) { node.importClause.namedBindings.elements.forEach(item => { if (item.name && ts.isIdentifier(item.name)) { + validateModuleName(item.name, log); if (item.propertyName && ts.isIdentifier(item.propertyName) && asName) { asName.set(item.propertyName.escapedText.toString(), item.name.escapedText.toString()); } else { @@ -89,28 +104,13 @@ isEntryPage: boolean = true, pathCollection: Set = new Set()): void { } } } - if (filePath && path.extname(filePath) !== EXTNAME_ETS && !isModule(filePath) && !isOhmUrl(filePath)) { - const dirIndexPath: string = path.resolve(path.resolve(pagesDir, filePath), INDEX_ETS); - if (/^(\.|\.\.)\//.test(filePath) && !fs.existsSync(path.resolve(pagesDir, filePath + EXTNAME_ETS)) && - fs.existsSync(dirIndexPath)) { - filePath = dirIndexPath; - } else { - filePath += EXTNAME_ETS; - } + + if (filePath) { + validatorCard(log, CARD_LOG_TYPE_IMPORT, node.getStart()); } try { - let fileResolvePath: string; - if (isOhmUrl(filePath) && filePath.indexOf(NODE_MODULES) < 0) { - fileResolvePath = resolveSourceFile(filePath); - } else if (/^(\.|\.\.)\//.test(filePath) && filePath.indexOf(NODE_MODULES) < 0) { - fileResolvePath = path.resolve(pagesDir, filePath); - } else if (/^\//.test(filePath) && filePath.indexOf(NODE_MODULES) < 0 || - fs.existsSync(filePath) && fs.statSync(filePath).isFile()) { - fileResolvePath = filePath; - } else { - fileResolvePath = getFileResolvePath(fileResolvePath, pagesDir, filePath, projectConfig.projectPath); - } + let fileResolvePath: string = getFileFullPath(filePath, pagesDir); if (fs.existsSync(fileResolvePath) && fs.statSync(fileResolvePath).isFile() && !pathCollection.has(fileResolvePath)) { let sourceFile: ts.SourceFile; @@ -118,12 +118,7 @@ isEntryPage: boolean = true, pathCollection: Set = new Set()): void { if (IMPORT_FILE_ASTCACHE.has(fileResolvePath)) { sourceFile = IMPORT_FILE_ASTCACHE.get(fileResolvePath); } else { - const content: string = preprocessNewExtend(preprocessExtend(processSystemApi( - fs.readFileSync(fileResolvePath, { encoding: 'utf-8' }).replace( - new RegExp('\\b' + STRUCT + '\\b.+\\{', 'g'), item => { - return item.replace(new RegExp('\\b' + STRUCT + '\\b', 'g'), `${CLASS} `); - })))); - sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS); + sourceFile = generateSourceFileAST(fileResolvePath, filePath); IMPORT_FILE_ASTCACHE[fileResolvePath] = sourceFile; } visitAllNode(sourceFile, sourceFile, defaultName, asName, path.dirname(fileResolvePath), log, @@ -134,6 +129,13 @@ isEntryPage: boolean = true, pathCollection: Set = new Set()): void { } } +export function generateSourceFileAST(fileResolvePath: string, filePath: string): ts.SourceFile { + const originContent: string = fs.readFileSync(fileResolvePath, { encoding: 'utf-8' }); + const content: string = path.extname(fileResolvePath) === EXTNAME_ETS ? + preprocessNewExtend(preprocessExtend(processSystemApi(originContent))) : originContent; + return ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true, ts.ScriptKind.ETS); +} + function visitAllNode(node: ts.Node, sourceFile: ts.SourceFile, defaultNameFromParent: string, asNameFromParent: Map, pagesDir: string, log: LogInfo[], entryCollection: Set, exportCollection: Set, defaultCollection: Set, asExportCollection: Map, @@ -149,7 +151,7 @@ function visitAllNode(node: ts.Node, sourceFile: ts.SourceFile, defaultNameFromP if (ts.isEnumDeclaration(node) && node.name) { enumCollection.add(node.name.getText()); } - if (ts.isClassDeclaration(node) && ts.isIdentifier(node.name) && isCustomComponent(node)) { + if (ts.isStructDeclaration(node) && ts.isIdentifier(node.name) && isCustomComponent(node)) { addDependencies(node, defaultNameFromParent, asNameFromParent); isExportEntry(node, log, entryCollection, exportCollection, defaultCollection, fileResolvePath, sourceFile); if (asExportCollection.has(node.name.getText())) { @@ -175,11 +177,14 @@ function visitAllNode(node: ts.Node, sourceFile: ts.SourceFile, defaultNameFromP if (ts.isExportAssignment(node) && node.expression && ts.isIdentifier(node.expression) && hasCollection(node.expression)) { if (defaultNameFromParent) { - setDependencies(defaultNameFromParent, - linkCollection.get(node.expression.escapedText.toString()), - propertyCollection.get(node.expression.escapedText.toString()), - propCollection.get(node.expression.escapedText.toString()), - builderParamObjectCollection.get(node.expression.escapedText.toString())); + const propertiesName: string = node.expression.escapedText.toString(); + setDependencies(defaultNameFromParent, linkCollection.get(propertiesName), + propertyCollection.get(propertiesName), propCollection.get(propertiesName), + builderParamObjectCollection.get(propertiesName), stateCollection.get(propertiesName), + regularCollection.get(propertiesName), storagePropCollection.get(propertiesName), + storageLinkCollection.get(propertiesName), provideCollection.get(propertiesName), + consumeCollection.get(propertiesName), objectLinkCollection.get(propertiesName), + localStorageLinkCollection.get(propertiesName), localStoragePropCollection.get(propertiesName)); } addDefaultExport(node); } @@ -199,6 +204,7 @@ function visitAllNode(node: ts.Node, sourceFile: ts.SourceFile, defaultNameFromP if (!item.propertyName) { asExportCollection.set(item.name.escapedText.toString(), item.name.escapedText.toString()); } else if (item.propertyName && ts.isIdentifier(item.propertyName)) { + validateModuleName(item.name, log, sourceFile, fileResolvePath); if (hasCollection(item.propertyName)) { let asExportName: string = item.name.escapedText.toString(); const asExportPropertyName: string = item.propertyName.escapedText.toString(); @@ -208,7 +214,12 @@ function visitAllNode(node: ts.Node, sourceFile: ts.SourceFile, defaultNameFromP setDependencies(asExportName, linkCollection.get(asExportPropertyName), propertyCollection.get(asExportPropertyName), propCollection.get(asExportPropertyName), - builderParamObjectCollection.get(asExportPropertyName)); + builderParamObjectCollection.get(asExportPropertyName), + stateCollection.get(asExportPropertyName), regularCollection.get(asExportPropertyName), + storagePropCollection.get(asExportPropertyName), storageLinkCollection.get(asExportPropertyName), + provideCollection.get(asExportPropertyName), consumeCollection.get(asExportPropertyName), + objectLinkCollection.get(asExportPropertyName), localStorageLinkCollection.get(asExportPropertyName), + localStoragePropCollection.get(asExportPropertyName)); } asExportCollection.set(item.propertyName.escapedText.toString(), item.name.escapedText.toString()); } @@ -287,7 +298,7 @@ function collectSpecialFunctionNode(node: ts.FunctionDeclaration, asNameFromPare } } -function isExportEntry(node: ts.ClassDeclaration, log: LogInfo[], entryCollection: Set, +function isExportEntry(node: ts.StructDeclaration, log: LogInfo[], entryCollection: Set, exportCollection: Set, defaultCollection: Set, fileResolvePath: string, sourceFile: ts.SourceFile): void { if (process.env.watchMode === 'true' && node && node.decorators) { @@ -331,7 +342,7 @@ function remindExportEntryComponent(node: ts.Node, log: LogInfo[], fileResolvePa } } -function addDependencies(node: ts.ClassDeclaration, defaultNameFromParent: string, +function addDependencies(node: ts.StructDeclaration, defaultNameFromParent: string, asNameFromParent: Map): void { const componentName: string = node.name.getText(); const ComponentSet: IComponentSet = getComponentSet(node); @@ -339,19 +350,28 @@ function addDependencies(node: ts.ClassDeclaration, defaultNameFromParent: strin node.modifiers[1] && node.modifiers[0].kind === ts.SyntaxKind.ExportKeyword && node.modifiers[1].kind === ts.SyntaxKind.DefaultKeyword) { setDependencies(defaultNameFromParent, ComponentSet.links, ComponentSet.properties, - ComponentSet.props, ComponentSet.builderParams); + ComponentSet.props, ComponentSet.builderParams, ComponentSet.states, ComponentSet.regulars, + ComponentSet.storageProps, ComponentSet.storageLinks, ComponentSet.provides, + ComponentSet.consumes, ComponentSet.objectLinks, ComponentSet.localStorageLink, + ComponentSet.localStorageProp); } else if (asNameFromParent.has(componentName)) { setDependencies(asNameFromParent.get(componentName), ComponentSet.links, ComponentSet.properties, - ComponentSet.props, ComponentSet.builderParams); + ComponentSet.props, ComponentSet.builderParams, ComponentSet.states, ComponentSet.regulars, + ComponentSet.storageProps, ComponentSet.storageLinks, ComponentSet.provides, + ComponentSet.consumes, ComponentSet.objectLinks, ComponentSet.localStorageLink, + ComponentSet.localStorageProp); } else { setDependencies(componentName, ComponentSet.links, ComponentSet.properties, ComponentSet.props, - ComponentSet.builderParams); + ComponentSet.builderParams, ComponentSet.states, ComponentSet.regulars, + ComponentSet.storageProps, ComponentSet.storageLinks, ComponentSet.provides, + ComponentSet.consumes, ComponentSet.objectLinks, ComponentSet.localStorageLink, + ComponentSet.localStorageProp); } } -function addDefaultExport(node: ts.ClassDeclaration | ts.ExportAssignment): void { +function addDefaultExport(node: ts.StructDeclaration | ts.ExportAssignment): void { let name: string; - if (ts.isClassDeclaration(node) && node.name && ts.isIdentifier(node.name)) { + if (ts.isStructDeclaration(node) && node.name && ts.isIdentifier(node.name)) { name = node.name.escapedText.toString(); } else if (ts.isExportAssignment(node) && node.expression && ts.isIdentifier(node.expression)) { name = node.expression.escapedText.toString(); @@ -370,29 +390,98 @@ function addDefaultExport(node: ts.ClassDeclaration | ts.ExportAssignment): void propCollection.get(name), builderParamObjectCollection.has(CUSTOM_COMPONENT_DEFAULT) ? new Set([...builderParamObjectCollection.get(CUSTOM_COMPONENT_DEFAULT), - ...builderParamObjectCollection.get(name)]) : builderParamObjectCollection.get(name)); + ...builderParamObjectCollection.get(name)]) : builderParamObjectCollection.get(name), + stateCollection.has(CUSTOM_COMPONENT_DEFAULT) ? + new Set([...stateCollection.get(CUSTOM_COMPONENT_DEFAULT), + ...stateCollection.get(name)]) : stateCollection.get(name), + regularCollection.has(CUSTOM_COMPONENT_DEFAULT) ? + new Set([...regularCollection.get(CUSTOM_COMPONENT_DEFAULT), + ...regularCollection.get(name)]) : regularCollection.get(name), + storagePropCollection.has(CUSTOM_COMPONENT_DEFAULT) ? + new Set([...storagePropCollection.get(CUSTOM_COMPONENT_DEFAULT), + ...storagePropCollection.get(name)]) : storagePropCollection.get(name), + storageLinkCollection.has(CUSTOM_COMPONENT_DEFAULT) ? + new Set([...storageLinkCollection.get(CUSTOM_COMPONENT_DEFAULT), + ...storageLinkCollection.get(name)]) : storageLinkCollection.get(name), + provideCollection.has(CUSTOM_COMPONENT_DEFAULT) ? + new Set([...provideCollection.get(CUSTOM_COMPONENT_DEFAULT), + ...provideCollection.get(name)]) : provideCollection.get(name), + consumeCollection.has(CUSTOM_COMPONENT_DEFAULT) ? + new Set([...consumeCollection.get(CUSTOM_COMPONENT_DEFAULT), + ...consumeCollection.get(name)]) : consumeCollection.get(name), + objectLinkCollection.has(CUSTOM_COMPONENT_DEFAULT) ? + new Set([...objectLinkCollection.get(CUSTOM_COMPONENT_DEFAULT), + ...objectLinkCollection.get(name)]) : objectLinkCollection.get(name), + getNewLocalStorageMap(localStorageLinkCollection, name), + getNewLocalStorageMap(localStoragePropCollection, name) + ); +} + +function getNewLocalStorageMap(collection: Map>>, name: string) + : Map> { + let localStorageLinkMap: Map> = new Map(); + if (collection.has(CUSTOM_COMPONENT_DEFAULT)) { + const tempSet: Set = new Set(); + if (collection.get(CUSTOM_COMPONENT_DEFAULT)) { + for (const key of collection.get(CUSTOM_COMPONENT_DEFAULT).keys()) { + tempSet.add(key); + } + } + if (collection.get(name)) { + for (const key of collection.get(name).keys()) { + tempSet.add(key); + } + } + localStorageLinkMap.set(name, tempSet); + } else { + localStorageLinkMap = collection.get(name); + } + return localStorageLinkMap; } function setDependencies(component: string, linkArray: Set, propertyArray: Set, - propArray: Set, builderParamArray: Set): void { + propArray: Set, builderParamArray: Set, stateArray: Set, + regularArray: Set, storagePropsArray: Set, storageLinksArray: Set, + providesArray: Set, consumesArray: Set, objectLinksArray: Set, + localStorageLinkMap: Map>, localStoragePropMap: Map>): void { linkCollection.set(component, linkArray); propertyCollection.set(component, propertyArray); propCollection.set(component, propArray); builderParamObjectCollection.set(component, builderParamArray); componentCollection.customComponents.add(component); + stateCollection.set(component, stateArray); + regularCollection.set(component, regularArray); + storagePropCollection.set(component, storagePropsArray); + storageLinkCollection.set(component, storageLinksArray); + provideCollection.set(component, providesArray); + consumeCollection.set(component, consumesArray); + objectLinkCollection.set(component, objectLinksArray); + localStorageLinkCollection.set(component, localStorageLinkMap); + localStoragePropCollection.set(component, localStoragePropMap); } function hasCollection(node: ts.Identifier): boolean { - return linkCollection.has(node.escapedText.toString()) || - propCollection.has(node.escapedText.toString()) || - propertyCollection.has(node.escapedText.toString()); + const name: string = node.escapedText.toString(); + return linkCollection.has(name) || + propCollection.has(name) || + propertyCollection.has(name) || + builderParamObjectCollection.has(name) || + stateCollection.has(name) || + regularCollection.has(name) || + storagePropCollection.has(name) || + storageLinkCollection.has(name) || + provideCollection.has(name) || + consumeCollection.has(name) || + objectLinkCollection.has(name) || + localStorageLinkCollection.has(name) || + localStoragePropCollection.has(name) } function isModule(filePath: string): boolean { - return !/^(\.|\.\.)?\//.test(filePath) || filePath.indexOf(NODE_MODULES) > -1; + return !/^(\.|\.\.)?\//.test(filePath) || filePath.indexOf(projectConfig.packageDir) > -1; } -function isCustomComponent(node: ts.ClassDeclaration): boolean { +function isCustomComponent(node: ts.StructDeclaration): boolean { if (node.decorators && node.decorators.length) { for (let i = 0; i < node.decorators.length; ++i) { const decoratorName: ts.Identifier = node.decorators[i].expression as ts.Identifier; @@ -405,23 +494,33 @@ function isCustomComponent(node: ts.ClassDeclaration): boolean { return false; } +let packageJsonEntry: string = ''; + function isPackageJsonEntry(filePath: string): boolean { - const packageJsonPath: string = path.join(filePath, PACKAGE_JSON); + const packageJsonPath: string = path.join(filePath, projectConfig.packageJson); if (fs.existsSync(packageJsonPath)) { - let entry: string; + let entryTypes: string; + let entryMain: string; try { - entry = JSON.parse(fs.readFileSync(packageJsonPath).toString()).main; + const packageJson: Object = JSON.parse(fs.readFileSync(packageJsonPath).toString()); + entryTypes = packageJson.types; + entryMain = packageJson.main; } catch (e) { return false; } - if (typeof entry === 'string' && fs.existsSync(path.join(filePath, entry))) { + if (entryExist(filePath, entryTypes)) { + packageJsonEntry = path.resolve(filePath, entryTypes); + return true; + } else if (entryExist(filePath, entryMain)) { + packageJsonEntry = path.resolve(filePath, entryMain); return true; } } } -function getPackageJsonEntry(filePath: string): string { - return path.join(filePath, JSON.parse(fs.readFileSync(path.join(filePath, PACKAGE_JSON)).toString()).main); +function entryExist(filePath: string, entry: string): boolean { + return typeof entry === 'string' && fs.existsSync(path.resolve(filePath, entry)) && + fs.statSync(path.resolve(filePath, entry)).isFile(); } function getModuleFilePath(filePath: string): string { @@ -455,15 +554,18 @@ function getFileResolvePath(fileResolvePath: string, pagesDir: string, filePath: } let curPageDir: string = pagesDir; while (!fs.existsSync(fileResolvePath)) { - if (filePath.indexOf(NODE_MODULES) > -1) { + if (filePath.indexOf(projectConfig.packageDir) > -1) { fileResolvePath = path.join(curPageDir, filePath); } else { - fileResolvePath = path.join(curPageDir, NODE_MODULES, filePath); + fileResolvePath = path.join(curPageDir, projectConfig.packageDir, filePath); } if (fs.existsSync(fileResolvePath + EXTNAME_ETS)) { fileResolvePath = fileResolvePath + EXTNAME_ETS; } else if (isPackageJsonEntry(fileResolvePath)) { - fileResolvePath = getPackageJsonEntry(fileResolvePath); + fileResolvePath = packageJsonEntry; + if (fs.statSync(fileResolvePath).isDirectory() && fs.existsSync(path.join(fileResolvePath, INDEX_ETS))) { + fileResolvePath = path.join(fileResolvePath, INDEX_ETS); + } } else if (fs.existsSync(path.join(fileResolvePath, INDEX_ETS))) { fileResolvePath = path.join(fileResolvePath, INDEX_ETS); } @@ -474,3 +576,55 @@ function getFileResolvePath(fileResolvePath: string, pagesDir: string, filePath: } return fileResolvePath; } + +export function getFileFullPath(filePath: string, pagesDir: string): string { + if (filePath && path.extname(filePath) !== EXTNAME_ETS && path.extname(filePath) !== EXTNAME_TS && + !isModule(filePath)) { + const dirIndexEtsPath: string = path.resolve(path.resolve(pagesDir, filePath), INDEX_ETS); + const dirIndexTsPath: string = path.resolve(path.resolve(pagesDir, filePath), INDEX_TS); + if (/^(\.|\.\.)\//.test(filePath) && !fs.existsSync(path.resolve(pagesDir, filePath + EXTNAME_ETS)) && + fs.existsSync(dirIndexEtsPath)) { + filePath = dirIndexEtsPath; + } else if (/^(\.|\.\.)\//.test(filePath) && !fs.existsSync(path.resolve(pagesDir, filePath + EXTNAME_TS)) && + fs.existsSync(dirIndexTsPath)) { + filePath = dirIndexTsPath; + } else { + filePath += getExtensionIfUnfullySpecifiedFilepath(path.resolve(pagesDir, filePath)); + } + } + + let fileResolvePath: string; + if (/^(\.|\.\.)\//.test(filePath) && filePath.indexOf(projectConfig.packageDir) < 0) { + fileResolvePath = path.resolve(pagesDir, filePath); + } else if (/^\//.test(filePath) && filePath.indexOf(projectConfig.packageDir) < 0 || + fs.existsSync(filePath) && fs.statSync(filePath).isFile()) { + fileResolvePath = filePath; + } else { + fileResolvePath = getFileResolvePath(fileResolvePath, pagesDir, filePath, projectConfig.projectPath); + } + + return fileResolvePath; +} + +function validateModuleName(moduleNode: ts.Identifier, log: LogInfo[], sourceFile?: ts.SourceFile, + fileResolvePath?: string): void { + const moduleName: string = moduleNode.escapedText.toString(); + if (INNER_COMPONENT_NAMES.has(moduleName)) { + const error: LogInfo = { + type: LogType.ERROR, + message: `The module name '${moduleName}' can not be the same as the inner component name.`, + pos: moduleNode.getStart() + }; + if (sourceFile && fileResolvePath) { + const posOfNode: ts.LineAndCharacter = sourceFile.getLineAndCharacterOfPosition(moduleNode.getStart()); + const line: number = posOfNode.line + 1; + const column: number = posOfNode.character + 1; + Object.assign(error, { + fileName: fileResolvePath, + line: line, + column: column + }); + } + log.push(error); + } +} diff --git a/compiler/src/process_js_file.ts b/compiler/src/process_js_file.ts deleted file mode 100644 index 982bfd2bdc5ecb8fe09e72d5bb59bbf68067de0c..0000000000000000000000000000000000000000 --- a/compiler/src/process_js_file.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { writeFileSyncByString } from './utils'; -import { projectConfig } from '../main'; -import { - ESMODULE, - ARK -} from './pre_define'; - -module.exports = function processjs2file(source: string): string { - if (projectConfig.compileMode === ESMODULE && projectConfig.processTs === false - && process.env.compilerType && process.env.compilerType === ARK) { - writeFileSyncByString(this.resourcePath, source); - } - return source; -}; diff --git a/compiler/src/process_module_files.ts b/compiler/src/process_module_files.ts new file mode 100644 index 0000000000000000000000000000000000000000..a5a41fabfa2df3bfd64b33249b8a04b03566b394 --- /dev/null +++ b/compiler/src/process_module_files.ts @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2023 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 path from 'path'; +import ts from 'typescript'; +import fs from 'fs'; + +import { newSourceMaps as rollupNewSourceMaps } from './fast_build/ark_compiler/transform'; +import { + EXTNAME_JS, + EXTNAME_TS, + EXTNAME_ETS, + TS_NOCHECK +} from './pre_define'; +import { + genTemporaryPath, + mkdirsSync, + toUnixPath, +} from './utils'; +import { + genSourceMapFileName, + newSourceMaps as webpackNewSourceMaps, + transformModuleSpecifier, + getBuildModeInLowerCase +} from './ark_utils'; +import { processSystemApi } from './validate_ui_syntax'; +import { DEBUG } from './fast_build/ark_compiler/common/ark_define'; + +export const SRC_MAIN: string = 'src/main'; + +export function writeFileSyncByNode(node: ts.SourceFile, toTsFile: boolean, projectConfig: any): void { + if (toTsFile) { + const newStatements: ts.Node[] = []; + const tsIgnoreNode: ts.Node = ts.factory.createExpressionStatement(ts.factory.createIdentifier(TS_NOCHECK)); + newStatements.push(tsIgnoreNode); + if (node.statements && node.statements.length) { + newStatements.push(...node.statements); + } + + node = ts.factory.updateSourceFile(node, newStatements); + } + const mixedInfo: {content: string, sourceMapJson: any} = genContentAndSourceMapInfo(node, toTsFile, projectConfig); + let temporaryFile: string = genTemporaryPath(node.fileName, projectConfig.projectPath, process.env.cachePath, + projectConfig); + if (temporaryFile.length === 0) { + return; + } + let temporarySourceMapFile: string = ''; + if (temporaryFile.endsWith(EXTNAME_ETS)) { + if (toTsFile) { + temporaryFile = temporaryFile.replace(/\.ets$/, EXTNAME_TS); + } else { + temporaryFile = temporaryFile.replace(/\.ets$/, EXTNAME_JS); + } + temporarySourceMapFile = genSourceMapFileName(temporaryFile); + } else { + if (!toTsFile) { + temporaryFile = temporaryFile.replace(/\.ts$/, EXTNAME_JS); + temporarySourceMapFile = genSourceMapFileName(temporaryFile); + } + } + mkdirsSync(path.dirname(temporaryFile)); + if (temporarySourceMapFile.length > 0 && getBuildModeInLowerCase(projectConfig) === DEBUG) { + let source = toUnixPath(node.fileName).replace(toUnixPath(projectConfig.projectRootPath) + '/', ''); + process.env.compileTool === 'rollup' ? rollupNewSourceMaps[source] = mixedInfo.sourceMapJson : + webpackNewSourceMaps[source] = mixedInfo.sourceMapJson; + } + fs.writeFileSync(temporaryFile, mixedInfo.content); +} + +function genContentAndSourceMapInfo(node: ts.SourceFile, toTsFile: boolean, projectConfig: any): any { + const printer: ts.Printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed }); + const options: ts.CompilerOptions = { + sourceMap: true + }; + const mapOpions: any = { + sourceMap: true, + inlineSourceMap: false, + inlineSources: false, + sourceRoot: '', + mapRoot: '', + extendedDiagnostics: false + }; + const host: ts.CompilerHost = ts.createCompilerHost(options); + const fileName: string = node.fileName; + // @ts-ignore + const sourceMapGenerator: any = ts.createSourceMapGenerator( + host, + // @ts-ignore + ts.getBaseFileName(fileName), + '', + '', + mapOpions + ); + // @ts-ignore + const writer: any = ts.createTextWriter( + // @ts-ignore + ts.getNewLineCharacter({newLine: ts.NewLineKind.LineFeed, removeComments: false})); + printer['writeFile'](node, writer, sourceMapGenerator); + const sourceMapJson: any = sourceMapGenerator.toJSON(); + sourceMapJson['sources'] = [fileName.replace(toUnixPath(projectConfig.projectRootPath) + '/', '')]; + let content: string = writer.getText(); + if (toTsFile) { + content = content.replace(`${TS_NOCHECK};`, TS_NOCHECK); + } + if (process.env.compileTool !== 'rollup') { + content = transformModuleSpecifier(fileName, processSystemApi(content, true), projectConfig); + } + + return { + content: content, + sourceMapJson: sourceMapJson + }; +} diff --git a/compiler/src/process_source_file.ts b/compiler/src/process_source_file.ts new file mode 100644 index 0000000000000000000000000000000000000000..22fe2bc4ee091a2a02ee54b8329a6d9c68206c4f --- /dev/null +++ b/compiler/src/process_source_file.ts @@ -0,0 +1,15 @@ +import { writeFileSyncByString } from './ark_utils'; +import { projectConfig } from '../main'; +import { + ESMODULE, + ARK +} from './pre_define'; +import { logger } from './compile_info'; + +module.exports = function processSourcefile(source: string): string { + if (projectConfig.compileMode === ESMODULE && process.env.compilerType + && process.env.compilerType === ARK) { + writeFileSyncByString(this.resourcePath, source, projectConfig, logger); + } + return source; +}; diff --git a/compiler/src/process_ui_syntax.ts b/compiler/src/process_ui_syntax.ts index 7c170d3a179d29d1d1d75766cd211a500c58cd53..b0cfb34194a150dd0d1b380882e80d0fadd18d73 100644 --- a/compiler/src/process_ui_syntax.ts +++ b/compiler/src/process_ui_syntax.ts @@ -16,12 +16,7 @@ import ts from 'typescript'; import path from 'path'; -import { componentCollection } from './validate_ui_syntax'; -import { - processComponentClass, - createParentParameter -} from './process_component_class'; -import processImport from './process_import'; +import validateReExportType from './validate_module_syntax'; import { PAGE_ENTRY_FUNCTION_NAME, PREVIEW_COMPONENT_FUNCTION_NAME, @@ -30,6 +25,7 @@ import { COMPONENT_CONSTRUCTOR_UNDEFINED, BUILD_ON, COMPONENT_BUILDER_DECORATOR, + COMPONENT_CONCURRENT_DECORATOR, COMPONENT_EXTEND_DECORATOR, COMPONENT_STYLES_DECORATOR, RESOURCE, @@ -51,23 +47,36 @@ import { CUSTOM_DIALOG_CONTROLLER_BUILDER, ESMODULE, ARK, - COMPONENT_COMMON, EXTNAME_ETS, GENERATE_ID, _GENERATE_ID, VIEWSTACKPROCESSOR, STARTGETACCESSRECORDINGFOR, ALLOCATENEWELMETIDFORNEXTCOMPONENT, - STOPGETACCESSRECORDING + STOPGETACCESSRECORDING, + CARD_ENTRY_FUNCTION_NAME, + CARD_LOG_TYPE_COMPONENTS, + CARD_LOG_TYPE_DECORATORS, + CARD_LOG_TYPE_IMPORT } from './pre_define'; import { componentInfo, LogInfo, LogType, hasDecorator, - FileLog, - writeFileSyncByNode + FileLog } from './utils'; +import { writeFileSyncByNode } from './process_module_files'; +import { + componentCollection, + localStorageLinkCollection, + localStoragePropCollection, +} from './validate_ui_syntax'; +import { + processComponentClass, + createParentParameter +} from './process_component_class'; +import processImport from './process_import'; import { processComponentBlock, bindComponentAttr, @@ -82,39 +91,49 @@ import { INTERFACE_NODE_SET, ID_ATTRS } from './component_map'; -import { - localStorageLinkCollection, - localStoragePropCollection -} from './validate_ui_syntax'; import { resources, projectConfig, partialUpdateConfig } from '../main'; import { createCustomComponentNewExpression, createViewCreate } from './process_component_member'; +import { ModuleSourceFile } from "./fast_build/ark_compiler/module/module_source_file"; export const transformLog: FileLog = new FileLog(); export let contextGlobal: ts.TransformationContext; +export let resourceFileName: string = ''; export function processUISyntax(program: ts.Program, ut = false): Function { + let entryNodeKey: ts.Expression; return (context: ts.TransformationContext) => { contextGlobal = context; let pagesDir: string; return (node: ts.SourceFile) => { pagesDir = path.resolve(path.dirname(node.fileName)); - if (process.env.compiler === BUILD_ON) { + resourceFileName = path.resolve(node.fileName); + if (process.env.compiler === BUILD_ON || process.env.compileTool === 'rollup') { transformLog.sourceFile = node; preprocessIdAttrs(node.fileName); - if (!ut && (path.basename(node.fileName) === 'app.ets' || /\.ts$/.test(node.fileName))) { + if (!ut && (process.env.compileMode !== 'moduleJson' && + path.resolve(node.fileName) === path.resolve(projectConfig.projectPath, 'app.ets') || + /\.ts$/.test(node.fileName))) { node = ts.visitEachChild(node, processResourceNode, context); - if (projectConfig.compileMode === ESMODULE && projectConfig.processTs === true - && process.env.compilerType && process.env.compilerType === ARK) { - writeFileSyncByNode(node, true); + if (projectConfig.compileMode === ESMODULE) { + validateReExportType(node, pagesDir, transformLog.errors); + if (projectConfig.processTs === true) { + process.env.compileTool === 'rollup' ? + ModuleSourceFile.newSourceFile(path.normalize(node.fileName), node) : + writeFileSyncByNode(node, true, projectConfig); + } } return node; } - node = createEntryNode(node, context); + const id: number = ++componentInfo.id; node = ts.visitEachChild(node, processAllNodes, context); + node = createEntryNode(node, context, entryNodeKey, id); + if (projectConfig.compileMode === ESMODULE) { + validateReExportType(node, pagesDir, transformLog.errors); + } GLOBAL_STYLE_FUNCTION.forEach((block, styleName) => { BUILDIN_STYLE_NAMES.delete(styleName); }); @@ -128,21 +147,36 @@ export function processUISyntax(program: ts.Program, ut = false): Function { }); node = ts.factory.updateSourceFile(node, statements); INTERFACE_NODE_SET.clear(); - if (projectConfig.compileMode === ESMODULE && projectConfig.processTs === true - && process.env.compilerType && process.env.compilerType === ARK) { - writeFileSyncByNode(node, true); + if (projectConfig.compileMode === ESMODULE && projectConfig.processTs === true) { + process.env.compileTool === 'rollup' ? ModuleSourceFile.newSourceFile(path.normalize(node.fileName), node) : + writeFileSyncByNode(node, true, projectConfig); } return node; } else { return node; } }; + + function entryKeyNode(node: ts.Node): ts.Expression { + if (node && node.decorators && node.decorators.length) { + node.decorators.forEach(item => { + if (item.expression && ts.isCallExpression(item.expression) && ts.isIdentifier(item.expression.expression) && + item.expression.expression.escapedText.toString() === 'Entry' && item.expression.arguments && + item.expression.arguments.length && ts.isIdentifier(item.expression.arguments[0])) { + entryNodeKey = item.expression.arguments[0]; + } + }); + } + return entryNodeKey; + } + function processAllNodes(node: ts.Node): ts.Node { if (ts.isImportDeclaration(node) || ts.isImportEqualsDeclaration(node) || ts.isExportDeclaration(node) && node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) { processImport(node, pagesDir, transformLog.errors); } else if (ts.isStructDeclaration(node)) { componentCollection.currentClassName = node.name.getText(); + componentCollection.entryComponent === componentCollection.currentClassName && entryKeyNode(node); node = processComponentClass(node, context, transformLog.errors, program); componentCollection.currentClassName = null; INNER_STYLE_FUNCTION.forEach((block, styleName) => { @@ -158,7 +192,8 @@ export function processUISyntax(program: ts.Program, ut = false): Function { node.parameters.push(createParentParameter()); node = ts.factory.updateFunctionDeclaration(node, undefined, node.modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, - processComponentBlock(node.body, false, transformLog.errors, false, true, node.name.getText())); + processComponentBlock(node.body, false, transformLog.errors, false, true, + node.name.getText(), undefined, true)); } else if (hasDecorator(node, COMPONENT_STYLES_DECORATOR)) { if (node.parameters.length === 0) { node = undefined; @@ -169,6 +204,9 @@ export function processUISyntax(program: ts.Program, ut = false): Function { pos: node.getStart() }); } + } else if (hasDecorator(node, COMPONENT_CONCURRENT_DECORATOR)) { + // ark compiler's feature + node = processConcurrent(node); } } else if (isResource(node)) { node = processResourceData(node as ts.CallExpression); @@ -302,7 +340,7 @@ function processCustomDialogControllerPropertyAssignment(parent: ts.Expression, function processCustomDialogControllerBuilder(parent: ts.Expression, node: ts.CallExpression, componentName: string): ts.ArrowFunction { - const newExp: ts.Expression = createCustomComponentNewExpression(node, componentName); + const newExp: ts.Expression = createCustomComponentNewExpression(node, componentName, false, false, true); const jsDialog: ts.Identifier = ts.factory.createIdentifier(JS_DIALOG); return createCustomComponentBuilderArrowFunction(parent, jsDialog, newExp); } @@ -348,7 +386,7 @@ function createCustomComponentBuilderArrowFunction(parent: ts.Expression, ); } -function isResource(node: ts.Node): boolean { +export function isResource(node: ts.Node): boolean { return ts.isCallExpression(node) && ts.isIdentifier(node.expression) && (node.expression.escapedText.toString() === RESOURCE || node.expression.escapedText.toString() === RESOURCE_RAWFILE) && node.arguments.length > 0; @@ -359,20 +397,22 @@ function isAnimateTo(node: ts.Node): boolean { node.expression.escapedText.toString() === ATTRIBUTE_ANIMATETO; } -function processResourceData(node: ts.CallExpression): ts.Node { +export function processResourceData(node: ts.CallExpression, + previewLog: {isAcceleratePreview: boolean, log: LogInfo[]} = {isAcceleratePreview: false, log: []}): ts.Node { if (ts.isStringLiteral(node.arguments[0])) { if (node.expression.getText() === RESOURCE_RAWFILE) { return createResourceParam(0, RESOURCE_TYPE.rawfile, [node.arguments[0]]); } else { - return getResourceDataNode(node); + return getResourceDataNode(node, previewLog); } } return node; } -function getResourceDataNode(node: ts.CallExpression): ts.Node { +function getResourceDataNode(node: ts.CallExpression, + previewLog: {isAcceleratePreview: boolean, log: LogInfo[]}): ts.Node { const resourceData: string[] = (node.arguments[0] as ts.StringLiteral).text.trim().split('.'); - if (validateResourceData(resourceData, resources, node.arguments[0].getStart())) { + if (preCheckResourceData(resourceData, resources, node.arguments[0].getStart(), previewLog)) { const resourceType: number = RESOURCE_TYPE[resourceData[1]]; if (resourceType === undefined) { transformLog.errors.push({ @@ -384,13 +424,19 @@ function getResourceDataNode(node: ts.CallExpression): ts.Node { } const resourceValue: number = resources[resourceData[0]][resourceData[1]][resourceData[2]]; return createResourceParam(resourceValue, resourceType, - Array.from(node.arguments).slice(1)); + projectConfig.compileHar ? Array.from(node.arguments) : Array.from(node.arguments).slice(1)); } return node; } function createResourceParam(resourceValue: number, resourceType: number, argsArr: ts.Expression[]): ts.ObjectLiteralExpression { + if (projectConfig.compileHar) { + projectConfig.bundleName = ''; + projectConfig.moduleName = ''; + resourceValue = -1; + } + const propertyArray: Array = [ ts.factory.createPropertyAssignment( ts.factory.createStringLiteral(RESOURCE_NAME_ID), @@ -406,14 +452,14 @@ function createResourceParam(resourceValue: number, resourceType: number, argsAr ) ]; - if (projectConfig.bundleName) { + if (projectConfig.bundleName || projectConfig.bundleName === '') { propertyArray.push(ts.factory.createPropertyAssignment( ts.factory.createStringLiteral(RESOURCE_NAME_BUNDLE), ts.factory.createStringLiteral(projectConfig.bundleName) )); } - if (projectConfig.moduleName) { + if (projectConfig.moduleName || projectConfig.moduleName === '') { propertyArray.push(ts.factory.createPropertyAssignment( ts.factory.createStringLiteral(RESOURCE_NAME_MODULE), ts.factory.createStringLiteral(projectConfig.moduleName) @@ -425,29 +471,38 @@ function createResourceParam(resourceValue: number, resourceType: number, argsAr return resourceParams; } -function validateResourceData(resourceData: string[], resources: object, pos: number): boolean { +function preCheckResourceData(resourceData: string[], resources: object, pos: number, + previewLog: {isAcceleratePreview: boolean, log: LogInfo[]}): boolean { + if (previewLog.isAcceleratePreview) { + return validateResourceData(resourceData, resources, pos, previewLog.log); + } else { + return validateResourceData(resourceData, resources, pos, transformLog.errors); + } +} + +function validateResourceData(resourceData: string[], resources: object, pos: number, log: LogInfo[]): boolean { if (resourceData.length !== 3) { - transformLog.errors.push({ + log.push({ type: LogType.ERROR, message: 'The input parameter is not supported.', pos: pos }); } else if (!resources[resourceData[0]]) { - transformLog.errors.push({ + log.push({ type: LogType.ERROR, - message: `The value of '${resourceData[0]}' is invalid.`, + message: `Unknown resource source '${resourceData[0]}'.`, pos: pos }); } else if (!resources[resourceData[0]][resourceData[1]]) { - transformLog.errors.push({ + log.push({ type: LogType.ERROR, - message: `Value '${resourceData[1]}' does not exist on type 'typeof ${resourceData[0]}'.`, + message: `Unknown resource type '${resourceData[1]}'.`, pos: pos }); } else if (!resources[resourceData[0]][resourceData[1]][resourceData[2]]) { - transformLog.errors.push({ + log.push({ type: LogType.ERROR, - message: `Value '${resourceData[2]}' does not exist on type 'typeof ${resourceData[1]}'.`, + message: `Unknown resource name '${resourceData[2]}'.`, pos: pos }); } else { @@ -503,7 +558,7 @@ function processExtend(node: ts.FunctionDeclaration, log: LogInfo[]): ts.Functio } return ts.factory.updateFunctionDeclaration(node, undefined, node.modifiers, node.asteriskToken, ts.factory.createIdentifier(extendFunctionName), node.typeParameters, - node.parameters, node.type, isOriginalExtend(node.body) ? + node.parameters, ts.factory.createToken(ts.SyntaxKind.VoidKeyword), isOriginalExtend(node.body) ? ts.factory.updateBlock(node.body, statementArray) : bodynode); } function traverseExtendExpression(node: ts.Node): ts.Node { @@ -512,15 +567,23 @@ function processExtend(node: ts.FunctionDeclaration, log: LogInfo[]): ts.Functio ts.factory.createExpressionStatement(processExtendBody(node.expression, componentName)); const statementArray: ts.Statement[] = []; bindComponentAttr(changeCompName, ts.factory.createIdentifier(componentName), statementArray, []); - return ts.factory.createCallExpression( - ts.factory.createParenthesizedExpression(ts.factory.createFunctionExpression( - undefined, undefined, undefined, undefined, [], undefined, - ts.factory.createBlock(statementArray, true))), undefined, []); + return ts.factory.createBlock(statementArray, true); } return ts.visitEachChild(node, traverseExtendExpression, contextGlobal); } } +function processConcurrent(node: ts.FunctionDeclaration): ts.FunctionDeclaration { + if (node.body) { + const statementArray: ts.Statement[] + = [ts.factory.createExpressionStatement(ts.factory.createStringLiteral('use concurrent')), + ...node.body.statements]; + return ts.factory.updateFunctionDeclaration(node, undefined, node.modifiers, node.asteriskToken, node.name, + node.typeParameters, node.parameters, node.type, ts.factory.updateBlock(node.body, statementArray)); + } + return node; +} + export function isOriginalExtend(node: ts.Block): boolean { let innerNode: ts.Node = node.statements[0]; if (node.statements.length === 1 && ts.isExpressionStatement(innerNode)) { @@ -585,64 +648,75 @@ export function isExtendFunction(node: ts.FunctionDeclaration): string { return null; } -function createEntryNode(node: ts.SourceFile, context: ts.TransformationContext): ts.SourceFile { +function createEntryNode(node: ts.SourceFile, context: ts.TransformationContext, + entryNodeKey: ts.Expression, id: number): ts.SourceFile { + let cardRelativePath: string = undefined; + if (projectConfig && projectConfig.cardObj) { + cardRelativePath = projectConfig.cardObj[resourceFileName]; + } if (componentCollection.previewComponent.size === 0 || !projectConfig.isPreview) { if (componentCollection.entryComponent) { if (!partialUpdateConfig.partialUpdateMode) { const entryNode: ts.ExpressionStatement = - createEntryFunction(componentCollection.entryComponent, context) as ts.ExpressionStatement; + createEntryFunction(componentCollection.entryComponent, context, + cardRelativePath, entryNodeKey, id) as ts.ExpressionStatement; return context.factory.updateSourceFile(node, [...node.statements, entryNode]); } else { const entryNodes: ts.ExpressionStatement[] = - createEntryFunction(componentCollection.entryComponent, context) as ts.ExpressionStatement[]; - return context.factory.updateSourceFile(node, [...node.statements, ...entryNodes]); + createEntryFunction(componentCollection.entryComponent, context, + cardRelativePath, entryNodeKey, id) as ts.ExpressionStatement[]; + return entryNodes ? + context.factory.updateSourceFile(node, [...node.statements, ...entryNodes]) : + context.factory.updateSourceFile(node, [...node.statements]); } } else { return node; } } else { const statementsArray: ts.Statement = - createPreviewComponentFunction(componentCollection.entryComponent, context); + createPreviewComponentFunction(componentCollection.entryComponent, context, cardRelativePath, id); return context.factory.updateSourceFile(node, [...node.statements, statementsArray]); } } -function createEntryFunction(name: string, context: ts.TransformationContext) - : ts.ExpressionStatement | ts.ExpressionStatement[] { +function createEntryFunction(name: string, context: ts.TransformationContext, cardRelativePath: string, + entryNodeKey: ts.Expression, id: number): ts.ExpressionStatement | ts.ExpressionStatement[] { let localStorageName: string; const localStorageNum: number = localStorageLinkCollection.get(name).size + localStoragePropCollection.get(name).size; - if (componentCollection.entryComponent === name && componentCollection.localStorageName && - localStorageNum) { + if (componentCollection.entryComponent === name && componentCollection.localStorageName) { localStorageName = componentCollection.localStorageName; } else if (componentCollection.entryComponent === name && !componentCollection.localStorageName && localStorageNum) { transformLog.errors.push({ - type: LogType.ERROR, + type: LogType.WARN, message: `@Entry should have a parameter, like '@Entry (storage)'.`, pos: componentCollection.entryComponentPos }); return; } const newArray: ts.Expression[] = [ - context.factory.createStringLiteral((++componentInfo.id).toString()), + context.factory.createStringLiteral(id.toString()), context.factory.createIdentifier(COMPONENT_CONSTRUCTOR_UNDEFINED), context.factory.createObjectLiteralExpression([], false) ]; if (localStorageName) { - newArray.push(context.factory.createIdentifier(localStorageName)); + newArray.push(entryNodeKey); } + const newExpressionParams: any[] = [ + context.factory.createNewExpression( + context.factory.createIdentifier(name),undefined, newArray)]; + addCardStringliteral(newExpressionParams, context, cardRelativePath); if (!partialUpdateConfig.partialUpdateMode) { const newExpressionStatement: ts.ExpressionStatement = context.factory.createExpressionStatement(context.factory.createCallExpression( - context.factory.createIdentifier(PAGE_ENTRY_FUNCTION_NAME), undefined, - [context.factory.createNewExpression(context.factory.createIdentifier(name), - undefined, newArray)])); + context.factory.createIdentifier(cardRelativePath ? CARD_ENTRY_FUNCTION_NAME : + PAGE_ENTRY_FUNCTION_NAME), undefined, newExpressionParams)); return newExpressionStatement; } else { return [ createStartGetAccessRecording(context), - createLoadDocument(context, name), + createLoadDocument(context, name, cardRelativePath, localStorageName), createStopGetAccessRecording(context) ]; } @@ -668,21 +742,24 @@ function createStartGetAccessRecording(context: ts.TransformationContext): ts.Ex ); } -function createLoadDocument(context: ts.TransformationContext, name: string): ts.ExpressionStatement { +function createLoadDocument(context: ts.TransformationContext, name: string, + cardRelativePath: string, localStorageName: string): ts.ExpressionStatement { + const newArray: ts.Expression[] = [ + context.factory.createIdentifier('undefined'), + context.factory.createObjectLiteralExpression([], false) + ]; + if (localStorageName) { + newArray.push(context.factory.createIdentifier(localStorageName)); + } + const newExpressionParams: any[] = [ + context.factory.createNewExpression( + context.factory.createIdentifier(name), + undefined, newArray)]; + addCardStringliteral(newExpressionParams, context, cardRelativePath); return context.factory.createExpressionStatement( context.factory.createCallExpression( - context.factory.createIdentifier(PAGE_ENTRY_FUNCTION_NAME), - undefined, - [context.factory.createNewExpression( - context.factory.createIdentifier(name), - undefined, - [context.factory.createIdentifier('undefined'), - context.factory.createObjectLiteralExpression( - [], - false - )] - )] - ) + context.factory.createIdentifier(cardRelativePath ? CARD_ENTRY_FUNCTION_NAME : + PAGE_ENTRY_FUNCTION_NAME), undefined, newExpressionParams) ); } @@ -699,13 +776,18 @@ function createStopGetAccessRecording(context: ts.TransformationContext): ts.Exp ); } -function createPreviewComponentFunction(name: string, context: ts.TransformationContext) - : ts.Statement { - const newArray: ts.Expression[] = [ - context.factory.createStringLiteral((++componentInfo.id).toString()), - context.factory.createIdentifier(COMPONENT_CONSTRUCTOR_UNDEFINED), - context.factory.createObjectLiteralExpression([], false) - ]; +function createPreviewComponentFunction(name: string, context: ts.TransformationContext, + cardRelativePath: string, id: number): ts.Statement { + const newArray: ts.Expression[] = partialUpdateConfig.partialUpdateMode ? + [ + context.factory.createIdentifier(COMPONENT_CONSTRUCTOR_UNDEFINED), + context.factory.createObjectLiteralExpression([], false) + ] : + [ + context.factory.createStringLiteral(id.toString()), + context.factory.createIdentifier(COMPONENT_CONSTRUCTOR_UNDEFINED), + context.factory.createObjectLiteralExpression([], false) + ]; const argsArr: ts.Expression[] = []; componentCollection.previewComponent.forEach(componentName => { const newExpression: ts.Expression = context.factory.createNewExpression( @@ -716,6 +798,9 @@ function createPreviewComponentFunction(name: string, context: ts.Transformation argsArr.push(context.factory.createStringLiteral(componentName)); argsArr.push(newExpression); }); + const newExpressionParams: any[] = name ? [context.factory.createNewExpression( + context.factory.createIdentifier(name), undefined, newArray)] : []; + addCardStringliteral(newExpressionParams, context, cardRelativePath); const ifStatement: ts.Statement = context.factory.createIfStatement( context.factory.createCallExpression( context.factory.createIdentifier(GET_PREVIEW_FLAG_FUNCTION_NAME), @@ -740,15 +825,12 @@ function createPreviewComponentFunction(name: string, context: ts.Transformation ...argsArr ] )), + name && partialUpdateConfig.partialUpdateMode ? createStartGetAccessRecording(context) : undefined, name ? context.factory.createExpressionStatement(context.factory.createCallExpression( - context.factory.createIdentifier(PAGE_ENTRY_FUNCTION_NAME), - undefined, - [context.factory.createNewExpression( - context.factory.createIdentifier(name), - undefined, - newArray - )] - )) : undefined + context.factory.createIdentifier(cardRelativePath ? CARD_ENTRY_FUNCTION_NAME : + PAGE_ENTRY_FUNCTION_NAME), undefined, newExpressionParams + )) : undefined, + name && partialUpdateConfig.partialUpdateMode ? createStopGetAccessRecording(context) : undefined ], true ) @@ -759,3 +841,36 @@ function createPreviewComponentFunction(name: string, context: ts.Transformation export function resetLog(): void { transformLog.errors = []; } + +function addCardStringliteral(newExpressionParams: any[], context: ts.TransformationContext, + cardRelativePath: string): void { + if (cardRelativePath) { + newExpressionParams.push(context.factory.createStringLiteral( + projectConfig.bundleName + '/' + projectConfig.moduleName + '/' + + cardRelativePath)); + } +} + +export function validatorCard(log: any[], type: number, pos: number, + name: string = ''): void { + if (projectConfig && projectConfig.cardObj && resourceFileName + && projectConfig.cardObj[resourceFileName]) { + const logInfo: object = { + type: LogType.ERROR, + message: '', + pos: pos + }; + switch (type) { + case CARD_LOG_TYPE_COMPONENTS: + logInfo.message = `Card page cannot use the component ${name}.`; + break; + case CARD_LOG_TYPE_DECORATORS: + logInfo.message = `Card page cannot use ${name}`; + break; + case CARD_LOG_TYPE_IMPORT: + logInfo.message = `Card page cannot use import.`; + break; + } + log.push(logInfo); + } +} diff --git a/compiler/src/process_visual.ts b/compiler/src/process_visual.ts new file mode 100644 index 0000000000000000000000000000000000000000..935825b7a81763d594062e1ca6187107a04eec09 --- /dev/null +++ b/compiler/src/process_visual.ts @@ -0,0 +1,327 @@ +/* + * Copyright (c) 2023 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 ts from 'typescript'; +import fs from 'fs'; +import path from 'path'; +import { SourceMapGenerator } from 'source-map'; + +import { + validateUISyntax, + componentCollection, + preprocessExtend, + preprocessNewExtend, + ReplaceResult, + sourceReplace +} from './validate_ui_syntax'; +import { + LogType, + LogInfo, + mkDir +} from './utils'; +import { + MODULE_ETS_PATH, + MODULE_VISUAL_PATH, + SUPERVISUAL, + SUPERVISUAL_SOURCEMAP_EXT +} from './pre_define'; + +import { projectConfig } from '../main.js'; +import { genETS } from '../codegen/codegen_ets.js'; + +const visualMap: Map = new Map(); +const slotMap: Map = new Map(); + +const red: string = '\u001b[31m'; +const reset: string = '\u001b[39m'; + +export function parseVisual(resourcePath: string, resourceQuery: string, content: string, + log: LogInfo[], source: string, isFastBuild: boolean = false): string { + if (!(componentCollection.entryComponent || componentCollection.customComponents) || !projectConfig.aceSuperVisualPath) { + return content; + } + const visualPath: string = findVisualFile(resourcePath); + if (!visualPath || !fs.existsSync(visualPath)) { + return content; + } + const visualContent: any = getVisualContent(visualPath, log); + if (!visualContent) { + return content; + } + visualMap.clear(); + slotMap.clear(); + const compilerOptions = ts.readConfigFile( + path.resolve(__dirname, '../tsconfig.json'), ts.sys.readFile).config.compilerOptions; + Object.assign(compilerOptions, { + 'sourceMap': false + }); + const sourceFile: ts.SourceFile = ts.createSourceFile(resourcePath, content, + ts.ScriptTarget.Latest, true, ts.ScriptKind.ETS, compilerOptions); + let newContent: string = content; + if (sourceFile.statements) { + sourceFile.statements.forEach(statement => { + newContent = parseStatement(statement, newContent, log, visualContent); + }); + } + if (isFastBuild) { + newContent = preprocessExtend(newContent); + newContent = preprocessNewExtend(newContent); + } else { + const result: ReplaceResult = sourceReplace(newContent, resourcePath); + newContent = result.content; + log.concat(result.log); + } + let resultLog: LogInfo[] = validateUISyntax(source, newContent, resourcePath, resourceQuery); + log.concat(resultLog); + if (!log.length) { + generateSourceMapForNewAndOriEtsFile(resourcePath, source); + } + return newContent; +} + +function parseStatement(statement: ts.Statement, content: string, log: LogInfo[], + visualContent: any): string { + if (statement.kind === ts.SyntaxKind.StructDeclaration && statement.name) { + if (statement.members) { + statement.members.forEach(member => { + if (member.kind && member.kind === ts.SyntaxKind.MethodDeclaration) { + content = parseMember(statement, member, content, log, visualContent); + } + }); + } + } + return content; +} + +function parseMember(statement: ts.Statement, member: ts.MethodDeclaration, content: string, + log: LogInfo[], visualContent: any): string { + let newContent: string = content; + if (member.name && member.name.getText() === 'build') { + const buildBody: string = member.getText(); + if (buildBody.replace(/\ +/g, '').replace(/[\r\n]/g, '') === 'build(){}') { + newContent = insertVisualCode(statement, member, visualContent, newContent); + } else { + log.push({ + type: LogType.ERROR, + message: `when the corresponding visual file exists,` + + ` the build function of the entry component must be empty.`, + pos: member.pos + }); + } + } + return newContent; +} + +function insertVisualCode(statement: ts.Statement, member: ts.MethodDeclaration, + visualContent: any, content: string): string { + let newContent: string = content; + newContent = insertImport(visualContent, newContent); + newContent = insertVarAndFunc(member, visualContent, newContent, content); + newContent = insertBuild(member, visualContent, newContent, content); + newContent = insertAboutToAppear(statement, member, visualContent, newContent, content); + return newContent; +} + +function insertImport(visualContent: any, content: string): string { + if (!visualContent.etsImport) { + return content; + } + const mediaQueryImport: string = visualContent.etsImport + '\n'; + const newContent: string = mediaQueryImport + content; + slotMap.set(0, mediaQueryImport.length); + visualMap.set(0, mediaQueryImport.split('\n').length - 1); + return newContent; +} + +function insertVarAndFunc(build: ts.MethodDeclaration, visualContent: any, + content: string, oriContent: string): string { + const visualVarAndFunc: string = (visualContent.etsVariable ? visualContent.etsVariable : '') + + (visualContent.etsFunction ? visualContent.etsFunction : ''); + return visualVarAndFunc ? insertVisualCodeBeforePos(build, '\n' + visualVarAndFunc, content, + oriContent) : content; +} + +function insertBuild(build: ts.MethodDeclaration, visualContent: any, content: string, + oriContent: string): string { + return visualContent.build ? insertVisualCodeAfterPos(build.body, + '\n' + visualContent.build + '\n', content, oriContent) : content; +} + +function insertAboutToAppear(statement: ts.Statement, build: ts.MethodDeclaration, + visualContent: any, content: string, oriContent: string): string { + if (!visualContent.aboutToAppear) { + return content; + } + for (const member of statement.members) { + const hasAboutToAppear: boolean = member.kind && member.kind === ts.SyntaxKind.MethodDeclaration + && member.name && member.name.getText() === 'aboutToAppear'; + if (hasAboutToAppear) { + return insertVisualCodeAfterPos(member.body, '\n' + visualContent.aboutToAppear, content, + oriContent); + } + } + + const aboutToAppearFunc: string = '\n aboutToAppear() {\n' + visualContent.aboutToAppear + + ' }\n'; + return insertVisualCodeBeforePos(build, aboutToAppearFunc, content, oriContent); +} + +function insertVisualCodeAfterPos(member: ts.Block, visualContent: string, content: string, + oriContent: string): string { + const contentBeforePos: string = oriContent.substring(0, member.getStart() + 1); + const originEtsFileLineNumber: number = contentBeforePos.split('\n').length; + const visualLines: number = visualContent.split('\n').length - 1; + const insertedLineNumbers: number = visualMap.get(originEtsFileLineNumber); + visualMap.set(originEtsFileLineNumber, insertedLineNumbers ? insertedLineNumbers + visualLines : + visualLines); + + let newPos: number = member.getStart() + 1; + for (const [key, value] of slotMap) { + if (member.getStart() >= key) { + newPos += value; + } + } + + const newContent: string = content.substring(0, newPos) + visualContent + + content.substring(newPos); + slotMap.set(member.getStart(), visualContent.length); + return newContent; +} + +function insertVisualCodeBeforePos(member: ts.MethodDeclaration, visualContent: string, + content: string, oriContent: string): string { + const contentBeforePos: string = oriContent.substring(0, member.pos); + const originEtsFileLineNumber: number = contentBeforePos.split('\n').length; + const visualLines: number = visualContent.split('\n').length - 1; + const insertedLineNumbers: number = visualMap.get(originEtsFileLineNumber); + visualMap.set(originEtsFileLineNumber, insertedLineNumbers ? insertedLineNumbers + visualLines : + visualLines); + let newPos: number = member.pos; + for (const [key, value] of slotMap) { + if (member.pos >= key) { + newPos += value; + } + } + const newContent: string = content.substring(0, newPos) + visualContent + + content.substring(newPos); + slotMap.set(member.pos, visualContent.length); + return newContent; +} + +function generateSourceMapForNewAndOriEtsFile(resourcePath: string, content: string) { + if (!process.env.cachePath) { + return; + } + const sourcemap: SourceMapGenerator = new SourceMapGenerator({ + file: resourcePath + }); + const lines: Array = content.split('\n'); + const originEtsFileLines: number = lines.length; + for (let l: number = 1; l <= originEtsFileLines; l++) { + let newEtsFileLineNumber: number = l; + for (const [originEtsFileLineNumber, visualLines] of visualMap) { + if (l > originEtsFileLineNumber) { + newEtsFileLineNumber += visualLines; + } + } + sourcemap.addMapping({ + generated: { + line: newEtsFileLineNumber, + column: 0 + }, + source: resourcePath, + original: { + line: l, + column: 0 + } + }); + } + const visualMapName: string = path.parse(resourcePath).name + SUPERVISUAL_SOURCEMAP_EXT; + const visualDirPath: string = path.parse(resourcePath).dir; + const etsDirPath: string = path.parse(projectConfig.projectPath).dir; + let visualMapDirPath: string = path.resolve(process.env.cachePath, SUPERVISUAL + + visualDirPath.replace(etsDirPath, '')); + if (!visualDirPath.includes(etsDirPath)) { + const projectRootPath = getProjectRootPath(); + visualMapDirPath = path.resolve(process.env.cachePath, SUPERVISUAL + + visualDirPath.replace(projectRootPath, '')); + } + if (!(fs.existsSync(visualMapDirPath) && fs.statSync(visualMapDirPath).isDirectory())) { + mkDir(visualMapDirPath); + } + fs.writeFile(path.resolve(visualMapDirPath, visualMapName), sourcemap.toString(), (err) => { + if (err) { + return console.error(red, 'ERROR: Failed to write visual.js.map', reset); + } + }); +} + +function getProjectRootPath(): string { + let projectRootPath = projectConfig.projectRootPath; + if (!projectRootPath) { + if (!projectConfig.aceModuleJsonPath) { + projectRootPath = path.resolve(projectConfig.projectPath, '../../../../../'); + } else { + projectRootPath = path.resolve(projectConfig.projectPath, '../../../../'); + } + } + return projectRootPath; +} + +function findVisualFile(filePath: string): string { + let etsDirPath: string = path.parse(projectConfig.projectPath).dir; + let visualDirPath: string = path.parse(projectConfig.aceSuperVisualPath).dir; + let resolvePath = filePath.replace(projectConfig.projectPath, projectConfig.aceSuperVisualPath) + .replace(etsDirPath, visualDirPath).replace(/\.ets$/, '.visual'); + if (fs.existsSync(resolvePath)) { + return resolvePath; + } + try { + const projectRootPath = getProjectRootPath(); + let moduleName = ''; + const relativePath = filePath.replace(projectRootPath, ''); + const moduleNames = relativePath.split(path.sep); + for (let i = 0; i < moduleNames.length; ++i) { + if (moduleNames[i] === 'src') { + if (i >= moduleNames.length - 2) { + break; + } + const modulePath = path.join(moduleNames[i], moduleNames[i + 1], moduleNames[i + 2]); + if (modulePath === MODULE_ETS_PATH) { + break; + } + } + moduleName = path.join(moduleName, moduleNames[i]); + } + etsDirPath = path.join(projectRootPath, moduleName, MODULE_ETS_PATH); + visualDirPath = path.join(projectRootPath, moduleName, MODULE_VISUAL_PATH); + resolvePath = filePath.replace(etsDirPath, visualDirPath).replace(/\.ets$/, '.visual'); + return resolvePath; + } catch (e) { + // avoid projectConfig attributes has undefined value + return ''; + } +} + +function getVisualContent(visualPath: string, log: LogInfo[]): any { + const parseContent: any = genETS(fs.readFileSync(visualPath, 'utf-8')); + if (parseContent && parseContent.errorType && parseContent.errorType !== '') { + log.push({ + type: LogType.ERROR, + message: parseContent.message + }); + } + return parseContent ? parseContent.ets : null; +} \ No newline at end of file diff --git a/compiler/src/resolve_ohm_url.ts b/compiler/src/resolve_ohm_url.ts index 79516029711b121bfabf0d3cba1491cc9af01909..6987b21fb6b19364aa3c470aa04302ac723a12af 100644 --- a/compiler/src/resolve_ohm_url.ts +++ b/compiler/src/resolve_ohm_url.ts @@ -1,8 +1,6 @@ import * as fs from 'fs'; import * as path from 'path'; import { logger } from './compile_info'; -import { NODE_MODULES, ONE, ZERO } from './pre_define'; -import { toUnixPath, getPackageInfo } from './utils'; const { projectConfig } = require('../main'); const red: string = '\u001b[31m'; @@ -45,13 +43,13 @@ function addExtension(file: string, srcPath: string): string { } if (fs.existsSync(file + '.ts') && fs.statSync(file + '.ts').isFile()) { if (extension !== '.d.ts') { - logger.error(red, `ETS:ERROR Failed to compile with files with same name ${srcPath} in the same directory`, reset); + logger.error(red, `ArkTS:ERROR Failed to compile with files with same name ${srcPath} in the same directory`, reset); } extension = '.ts'; } if (fs.existsSync(file + '.js') && fs.statSync(file + '.js').isFile()) { if (extension !== '.d.ts') { - logger.error(red, `ETS:ERROR Failed to compile with files with same name ${srcPath} in the same directory`, reset); + logger.error(red, `ArkTS:ERROR Failed to compile with files with same name ${srcPath} in the same directory`, reset); } extension = '.js'; } @@ -60,7 +58,7 @@ function addExtension(file: string, srcPath: string): string { export function resolveSourceFile(ohmUrl: string): string { if (!projectConfig.aceBuildJson) { - logger.error(red, `ETS:ERROR Failed to resolve OhmUrl because of aceBuildJson not existing `, reset); + logger.error(red, `ArkTS:ERROR Failed to resolve OhmUrl because of aceBuildJson not existing `, reset); return ohmUrl; } @@ -83,44 +81,8 @@ export function resolveSourceFile(ohmUrl: string): string { } } - logger.error(red, `ETS:ERROR Failed to resolve existed file by this ohm url ${ohmUrl} `, reset); + logger.error(red, `ArkTS:ERROR Failed to resolve existed file by this ohm url ${ohmUrl} `, reset); } return file; } - -export function getOhmUrlByFilepath(filePath: string): string { - let unixFilePath: string = toUnixPath(filePath); - unixFilePath = unixFilePath.substring(0, filePath.lastIndexOf('.')); // remove extension - const REG_PROJECT_SRC: RegExp = /(\S+)\/src\/(?:main|ohosTest)\/(ets|js)\/(\S+)/; - - const packageInfo: string[] = getPackageInfo(projectConfig.aceModuleJsonPath); - const moduleName: string = packageInfo[1]; - const moduleRootPath: string = toUnixPath(projectConfig.modulePathMap[moduleName]); - const projectRootPath: string = toUnixPath(projectConfig.projectRootPath); - // case1: /entry/src/main/ets/xxx/yyy - // case2: /node_modules/xxx/yyy - // case3: /entry/node_modules/xxx/yyy - const projectFilePath: string = unixFilePath.replace(projectRootPath, ''); - - const result: RegExpMatchArray | null = projectFilePath.match(REG_PROJECT_SRC); - if (result && result[1].indexOf(NODE_MODULES) === -1) { - return `${result[2]}/${result[3]}`; - } - - if (projectFilePath.indexOf(NODE_MODULES) !== -1) { - - const tryProjectNPM: string = toUnixPath(path.join(projectRootPath, NODE_MODULES)); - if (unixFilePath.indexOf(tryProjectNPM) !== -1) { - return unixFilePath.replace(tryProjectNPM, `${NODE_MODULES}/${ONE}`); - } - - const tryModuleNPM: string = toUnixPath(path.join(moduleRootPath, NODE_MODULES)); - if (unixFilePath.indexOf(tryModuleNPM) !== -1) { - return unixFilePath.replace(tryModuleNPM, `${NODE_MODULES}/${ZERO}`); - } - } - - logger.error(red, `ETS:ERROR Failed to get an resolved OhmUrl by filepath "${filePath}"`, reset); - return filePath; -} \ No newline at end of file diff --git a/compiler/src/result_process.ts b/compiler/src/result_process.ts index c3914e906f01d4ff28df135282cb9d944935ef0e..9097b2759bb1f11397adfdf919cc6c1eb4f19928 100644 --- a/compiler/src/result_process.ts +++ b/compiler/src/result_process.ts @@ -13,9 +13,7 @@ * limitations under the License. */ -import ts from 'typescript'; - -import { BUILD_OFF } from './pre_define'; +import { BUILD_OFF, ESMODULE, JSBUNDLE } from './pre_define'; import { resetLog, transformLog @@ -26,12 +24,15 @@ import { processSystemApi } from './validate_ui_syntax'; import { - LogInfo, emitLogInfo, - componentInfo + componentInfo, + generateSourceFilesInHar, + getTransformLog } from './utils'; +import { generateSourceFilesToTemporary } from './ark_utils'; import { resetComponentCollection } from './validate_ui_syntax'; -import { abilityConfig } from '../main'; +import { abilityConfig, projectConfig } from '../main'; +import { logger } from './compile_info'; module.exports = function resultProcess(source: string, map: any): void { process.env.compiler = BUILD_OFF; @@ -42,30 +43,23 @@ module.exports = function resultProcess(source: string, map: any): void { linkCollection.clear(); resetComponentCollection(); if (transformLog && transformLog.errors.length) { - const sourceFile: ts.SourceFile = transformLog.sourceFile; - const logInfos: LogInfo[] = transformLog.errors.map((item) => { - if (item.pos) { - if (!item.column || !item.line) { - const posOfNode: ts.LineAndCharacter = sourceFile.getLineAndCharacterOfPosition(item.pos); - item.line = posOfNode.line + 1; - item.column = posOfNode.character + 1; - } - } else { - item.line = item.line || undefined; - item.column = item.column || undefined; - } - if (!item.fileName) { - item.fileName = sourceFile.fileName; - } - return item; - }); - emitLogInfo(this, logInfos); + emitLogInfo(this, getTransformLog(transformLog)); resetLog(); } } - if ([abilityConfig.abilityEntryFile].concat(abilityConfig.projectAbilityPath).concat(abilityConfig.testRunnerFile).includes(this.resourcePath)) { + if (projectConfig.compileMode == JSBUNDLE && + [abilityConfig.abilityEntryFile].concat(abilityConfig.projectAbilityPath).concat(abilityConfig.testRunnerFile).includes(this.resourcePath)) { source = source.replace(/exports\.default/, 'globalThis.exports.default'); } + if (projectConfig.compileMode == ESMODULE && projectConfig.processTs === false + && process.env.compilerType && process.env.compilerType === 'ark' && !projectConfig.compileHar) { + generateSourceFilesToTemporary(this.resourcePath, source, map, projectConfig, logger); + } + + if (projectConfig.compileHar) { + generateSourceFilesInHar(this.resourcePath, source, '.js', projectConfig); + } + this.callback(null, source, map); }; diff --git a/compiler/src/utils.ts b/compiler/src/utils.ts index 271ef177f76e5d65f2914507abde759e74ce1ffb..1b2be90053ba2a83393f2b82abdc621e42cf46fc 100644 --- a/compiler/src/utils.ts +++ b/compiler/src/utils.ts @@ -16,24 +16,20 @@ import path from 'path'; import ts from 'typescript'; import fs from 'fs'; +import os from 'os'; +import uglifyJS from 'uglify-js'; + import { projectConfig } from '../main'; import { createHash } from 'crypto'; -import { processSystemApi } from './validate_ui_syntax'; import { - NODE_MODULES, - TEMPORARY, - MAIN, AUXILIARY, - ZERO, - ONE, - EXTNAME_JS, - EXTNAME_TS, - EXTNAME_MJS, - EXTNAME_CJS, - EXTNAME_ABC, EXTNAME_ETS, - EXTNAME_TS_MAP, - EXTNAME_JS_MAP, + EXTNAME_CJS, + EXTNAME_MJS, + EXTNAME_JS, + MAIN, + FAIL, + TEMPORARY, ESMODULE } from './pre_define'; @@ -45,7 +41,13 @@ export enum LogType { export const TEMPORARYS: string = 'temporarys'; export const BUILD: string = 'build'; export const SRC_MAIN: string = 'src/main'; -const TS_NOCHECK: string = '// @ts-nocheck'; + +const red: string = '\u001b[31m'; +const reset: string = '\u001b[39m'; + +const WINDOWS: string = 'Windows_NT'; +const LINUX: string = 'Linux'; +const MAC: string = 'Darwin'; export interface LogInfo { type: LogType, @@ -79,18 +81,22 @@ export class FileLog { } } -export function emitLogInfo(loader: any, infos: LogInfo[]) { +export function emitLogInfo(loader: any, infos: LogInfo[], fastBuild: boolean = false, + resourcePath: string = null): void { if (infos && infos.length) { infos.forEach((item) => { switch (item.type) { case LogType.ERROR: - loader.emitError(getMessage(loader.resourcePath, item)); + fastBuild ? loader.error('\u001b[31m' + getMessage(item.fileName || resourcePath, item, true)) : + loader.emitError(getMessage(item.fileName || loader.resourcePath, item)); break; case LogType.WARN: - loader.emitWarning(getMessage(item.fileName || loader.resourcePath, item)); + fastBuild ? loader.warn('\u001b[33m' + getMessage(item.fileName || resourcePath, item, true)) : + loader.emitWarning(getMessage(item.fileName || loader.resourcePath, item)); break; case LogType.NOTE: - loader.emitWarning(getMessage(loader.resourcePath, item)); + fastBuild ? loader.info('\u001b[34m' + getMessage(item.fileName || resourcePath, item, true)) : + loader.emitWarning(getMessage(loader.resourcePath, item)); break; } }); @@ -109,16 +115,40 @@ export function addLog(type: LogType, message: string, pos: number, log: LogInfo }); } -export function getMessage(fileName: string, info: LogInfo): string { +export function getMessage(fileName: string, info: LogInfo, fastBuild: boolean = false): string { let message: string; if (info.line && info.column) { message = `BUILD${info.type} File: ${fileName}:${info.line}:${info.column}\n ${info.message}`; } else { message = `BUILD${info.type} File: ${fileName}\n ${info.message}`; } + if (fastBuild) { + message = message.replace(/^BUILD/, 'ArkTS:'); + } return message; } +export function getTransformLog(transformLog: FileLog): LogInfo[] { + const sourceFile: ts.SourceFile = transformLog.sourceFile; + const logInfos: LogInfo[] = transformLog.errors.map((item) => { + if (item.pos) { + if (!item.column || !item.line) { + const posOfNode: ts.LineAndCharacter = sourceFile.getLineAndCharacterOfPosition(item.pos); + item.line = posOfNode.line + 1; + item.column = posOfNode.character + 1; + } + } else { + item.line = item.line || undefined; + item.column = item.column || undefined; + } + if (!item.fileName) { + item.fileName = sourceFile.fileName; + } + return item; + }); + return logInfos; +} + class ComponentInfo { private _id: number = 0; private _componentNames: Set = new Set(['ForEach']); @@ -171,22 +201,10 @@ export function readFile(dir: string, utFiles: string[]) { } }); } catch (e) { - console.error('ETS ERROR: ' + e); + console.error(red, 'ArkTS ERROR: ' + e, reset); } } -export function createFunction(node: ts.Identifier, attrNode: ts.Identifier, - argumentsArr: ts.NodeArray): ts.CallExpression { - return ts.factory.createCallExpression( - ts.factory.createPropertyAccessExpression( - node, - attrNode - ), - undefined, - argumentsArr && argumentsArr.length ? argumentsArr : [] - ); -} - export function circularFile(inputPath: string, outputPath: string): void { if (!inputPath || !outputPath) { return; @@ -262,7 +280,8 @@ export function writeFileSync(filePath: string, content: string): void { fs.writeFileSync(filePath, content); } -export function genTemporaryPath(filePath: string, projectPath: string, buildPath: string): string { +export function genTemporaryPath(filePath: string, projectPath: string, buildPath: string, + projectConfig: any, buildInHar: boolean = false): string { filePath = toUnixPath(filePath); if (filePath.endsWith(EXTNAME_MJS)) { filePath = filePath.replace(/\.mjs$/, EXTNAME_JS); @@ -272,78 +291,46 @@ export function genTemporaryPath(filePath: string, projectPath: string, buildPat } projectPath = toUnixPath(projectPath); - if (checkNodeModulesFile(filePath, projectPath)) { - const fakeNodeModulesPath: string = toUnixPath(path.join(projectConfig.projectRootPath, NODE_MODULES)); + if (isPackageModulesFile(filePath, projectConfig)) { + const packageDir: string = projectConfig.packageDir; + const fakePkgModulesPath: string = toUnixPath(path.join(projectConfig.projectRootPath, packageDir)); let output: string = ''; - if (filePath.indexOf(fakeNodeModulesPath) === -1) { + if (filePath.indexOf(fakePkgModulesPath) === -1) { const hapPath: string = toUnixPath(projectConfig.projectRootPath); const tempFilePath: string = filePath.replace(hapPath, ''); - const sufStr: string = tempFilePath.substring(tempFilePath.indexOf(NODE_MODULES) + NODE_MODULES.length + 1); - output = path.join(buildPath, TEMPORARY, NODE_MODULES, MAIN, sufStr); + const sufStr: string = tempFilePath.substring(tempFilePath.indexOf(packageDir) + packageDir.length + 1); + output = path.join(buildPath, buildInHar ? '' : TEMPORARY, packageDir, MAIN, sufStr); } else { - output = filePath.replace(fakeNodeModulesPath, path.join(buildPath, TEMPORARY, NODE_MODULES, AUXILIARY)); + output = filePath.replace(fakePkgModulesPath, + path.join(buildPath, buildInHar ? '' : TEMPORARY, packageDir, AUXILIARY)); } return output; } if (filePath.indexOf(projectPath) !== -1) { const sufStr: string = filePath.replace(projectPath, ''); - const output: string = path.join(buildPath, TEMPORARY, sufStr); + const output: string = path.join(buildPath, buildInHar ? '' : TEMPORARY, sufStr); return output; } return ''; } -export function genBuildPath(filePath: string, projectPath: string, buildPath: string): string { +export function isPackageModulesFile(filePath: string, projectConfig: any): boolean { filePath = toUnixPath(filePath); - if (filePath.endsWith(EXTNAME_MJS)) { - filePath = filePath.replace(/\.mjs$/, EXTNAME_JS); - } - if (filePath.endsWith(EXTNAME_CJS)) { - filePath = filePath.replace(/\.cjs$/, EXTNAME_JS); - } - projectPath = toUnixPath(projectPath); - - if (checkNodeModulesFile(filePath, projectPath)) { - filePath = toUnixPath(filePath); - const fakeNodeModulesPath: string = toUnixPath(path.join(projectConfig.projectRootPath, NODE_MODULES)); - let output: string = ''; - if (filePath.indexOf(fakeNodeModulesPath) === -1) { - const hapPath: string = toUnixPath(projectConfig.projectRootPath); - const tempFilePath: string = filePath.replace(hapPath, ''); - const sufStr: string = tempFilePath.substring(tempFilePath.indexOf(NODE_MODULES) + NODE_MODULES.length + 1); - output = path.join(projectConfig.nodeModulesPath, ZERO, sufStr); - } else { - output = filePath.replace(fakeNodeModulesPath, path.join(projectConfig.nodeModulesPath, ONE)); - } - return output; - } - - if (filePath.indexOf(projectPath) !== -1) { - const sufStr: string = filePath.replace(projectPath, ''); - const output: string = path.join(buildPath, sufStr); - return output; - } - - return ''; -} - -export function checkNodeModulesFile(filePath: string, projectPath: string): boolean { - filePath = toUnixPath(filePath); - projectPath = toUnixPath(projectPath); const hapPath: string = toUnixPath(projectConfig.projectRootPath); const tempFilePath: string = filePath.replace(hapPath, ''); - if (tempFilePath.indexOf(NODE_MODULES) !== -1) { - const fakeNodeModulesPath: string = toUnixPath(path.resolve(projectConfig.projectRootPath, NODE_MODULES)); - if (filePath.indexOf(fakeNodeModulesPath) !== -1) { + const packageDir: string = projectConfig.packageDir; + if (tempFilePath.indexOf(packageDir) !== -1) { + const fakePkgModulesPath: string = toUnixPath(path.resolve(projectConfig.projectRootPath, packageDir)); + if (filePath.indexOf(fakePkgModulesPath) !== -1) { return true; } if (projectConfig.modulePathMap) { for (const key in projectConfig.modulePathMap) { const value: string = projectConfig.modulePathMap[key]; - const fakeModuleNodeModulesPath: string = toUnixPath(path.resolve(value, NODE_MODULES)); - if (filePath.indexOf(fakeModuleNodeModulesPath) !== -1) { + const fakeModulePkgModulesPath: string = toUnixPath(path.resolve(value, packageDir)); + if (filePath.indexOf(fakeModulePkgModulesPath) !== -1) { return true; } } @@ -353,6 +340,22 @@ export function checkNodeModulesFile(filePath: string, projectPath: string): boo return false; } +export function generateSourceFilesInHar(sourcePath: string, sourceContent: string, suffix: string, projectConfig: any) { + // compileShared: compile shared har of project + let jsFilePath: string = genTemporaryPath(sourcePath, + projectConfig.compileShared ? projectConfig.projectRootPath : projectConfig.moduleRootPath, + projectConfig.compileShared ? path.resolve(projectConfig.aceModuleBuild, '../etsFortgz') : projectConfig.cachePath, + projectConfig, projectConfig.compileShared); + if (!jsFilePath.match(new RegExp(projectConfig.packageDir))) { + jsFilePath = jsFilePath.replace(/\.ets$/, suffix).replace(/\.ts$/, suffix); + mkdirsSync(path.dirname(jsFilePath)); + if (projectConfig.obfuscateHarType === 'uglify' && suffix === '.js') { + sourceContent = uglifyJS.minify(sourceContent).code; + } + fs.writeFileSync(jsFilePath, sourceContent); + } +} + export function mkdirsSync(dirname: string): boolean { if (fs.existsSync(dirname)) { return true; @@ -364,207 +367,190 @@ export function mkdirsSync(dirname: string): boolean { return false; } -export function writeFileSyncByString(sourcePath: string, sourceCode: string): void { - const jsFilePath: string = genTemporaryPath(sourcePath, projectConfig.projectPath, process.env.cachePath); - if (jsFilePath.length === 0) { - return; +export function nodeLargeOrEqualTargetVersion(targetVersion: number): boolean { + const currentNodeVersion: number = parseInt(process.versions.node.split('.')[0]); + if (currentNodeVersion >= targetVersion) { + return true; } - mkdirsSync(path.dirname(jsFilePath)); - fs.writeFileSync(jsFilePath, sourceCode); - return; -} - -export const packageCollection: Map> = new Map(); - -export function getPackageInfo(configFile: string): Array { - if (packageCollection.has(configFile)) { - return packageCollection.get(configFile); - } - const data: any = JSON.parse(fs.readFileSync(configFile).toString()); - const bundleName: string = data.app.bundleName; - const moduleName: string = data.module.name; - packageCollection.set(configFile, [bundleName, moduleName]); - return [bundleName, moduleName]; -} - -function replaceRelativeDependency(item:string, moduleRequest: string, sourcePath: string): string { - if (sourcePath && projectConfig.compileMode === ESMODULE) { - const filePath: string = path.resolve(path.dirname(sourcePath), moduleRequest); - const result: RegExpMatchArray | null = filePath.match(/(\S+)(\/|\\)src(\/|\\)(?:main|ohosTest)(\/|\\)(ets|js)(\/|\\)(\S+)/); - if (result && projectConfig.aceModuleJsonPath) { - const npmModuleIdx: number = result[1].search(/(\/|\\)node_modules(\/|\\)/); - const projectRootPath: string = projectConfig.projectRootPath; - if (npmModuleIdx === -1 || npmModuleIdx === projectRootPath.search(/(\/|\\)node_modules(\/|\\)/)) { - const packageInfo: string[] = getPackageInfo(projectConfig.aceModuleJsonPath); - const bundleName: string = packageInfo[0]; - const moduleName: string = packageInfo[1]; - moduleRequest = `@bundle:${bundleName}/${moduleName}/${result[5]}/${toUnixPath(result[7])}`; - item = item.replace(/['"](\S+)['"]/, '\"' + moduleRequest + '\"'); - } + + return false; +} + +export function removeDir(dirName: string): void { + if (fs.existsSync(dirName)) { + if (nodeLargeOrEqualTargetVersion(16)) { + fs.rmSync(dirName, { recursive: true}); + } else { + fs.rmdirSync(dirName, { recursive: true}); } } - return item; } -function generateSourceMap(jsFilePath: string, sourceMapContent: string): void { - let buildFilePath: string = genBuildPath(jsFilePath, projectConfig.projectPath, projectConfig.buildPath); - if (buildFilePath.length === 0) { - return; - } - if (buildFilePath.endsWith(EXTNAME_ETS)) { - buildFilePath = buildFilePath.replace(/\.ets$/, EXTNAME_JS); +export function parseErrorMessage(message: string): string { + const messageArrary: string[] = message.split('\n'); + let logContent: string = ''; + messageArrary.forEach(element => { + if (!(/^at/.test(element.trim()))) { + logContent = logContent + element + '\n'; + } + }); + return logContent; +} + +export function isWindows(): boolean { + return os.type() === WINDOWS; +} + +export function isLinux(): boolean { + return os.type() === LINUX; +} + +export function isMac(): boolean { + return os.type() === MAC; +} + +export function maxFilePathLength(): number { + if (isWindows()) { + return 259; + } else if (isLinux()) { + return 4095; + } else if (isMac()) { + return 1016; } else { - buildFilePath = buildFilePath.replace(/\.ts$/, EXTNAME_JS); + return -1; } - let buildSourceMapFile: string = genSourceMapFileName(buildFilePath); - mkdirsSync(path.dirname(buildSourceMapFile)); - fs.writeFileSync(buildSourceMapFile, sourceMapContent); } -export function generateSourceFilesToTemporary(node: ts.SourceFile): void { - const mixedInfo: {content: string, sourceMapContent: string} = genContentAndSourceMapInfo(node, false); - let jsFilePath: string = genTemporaryPath(node.fileName, projectConfig.projectPath, process.env.cachePath); - if (jsFilePath.length === 0) { - return; - } - if (jsFilePath.endsWith(EXTNAME_ETS)) { - jsFilePath = jsFilePath.replace(/\.ets$/, EXTNAME_JS); +export function validateFilePathLength(filePath: string, logger: any): boolean { + if (maxFilePathLength() < 0) { + logger.error(red, "Unknown OS platform", reset); + process.exitCode = FAIL; + return false; + } else if (filePath.length > 0 && filePath.length <= maxFilePathLength()) { + return true; + } else if (filePath.length > maxFilePathLength()) { + logger.error(red, "The length of path exceeds the maximum length: " + maxFilePathLength(), reset); + process.exitCode = FAIL; + return false; } else { - jsFilePath = jsFilePath.replace(/\.ts$/, EXTNAME_JS); - } - let sourceMapFile: string = genSourceMapFileName(jsFilePath); - mkdirsSync(path.dirname(jsFilePath)); - if (sourceMapFile.length > 0 && projectConfig.buildArkMode === 'debug') { - mixedInfo.content += '\n' + "//# sourceMappingURL=" + path.basename(sourceMapFile); - generateSourceMap(node.fileName, mixedInfo.sourceMapContent); - } - // replace relative moduleSpecifier with ohmURl - const REG_RELATIVE_DEPENDENCY: RegExp = /(?:import|from)(?:\s*)['"]((?:\.\/|\.\.\/).*)['"]/g; - mixedInfo.content = mixedInfo.content.replace(REG_RELATIVE_DEPENDENCY, (item, moduleRequest)=>{ - return replaceRelativeDependency(item, moduleRequest, node.fileName); - }); - - fs.writeFileSync(jsFilePath, mixedInfo.content); + logger.error(red, "Validate file path failed", reset); + process.exitCode = FAIL; + return false; + } } -export function writeFileSyncByNode(node: ts.SourceFile, toTsFile: boolean): void { - if (toTsFile) { - const newStatements: ts.Node[] = []; - const tsIgnoreNode: ts.Node = ts.factory.createExpressionStatement(ts.factory.createIdentifier(TS_NOCHECK)); - newStatements.push(tsIgnoreNode); - if (node.statements && node.statements.length) { - newStatements.push(...node.statements); +export function validateFilePathLengths(filePaths: Array, logger: any): boolean { + filePaths.forEach((filePath) => { + if (!validateFilePathLength(filePath, logger)) { + return false; } + }) + return true; +} - node = ts.factory.updateSourceFile(node, newStatements); +export function unlinkSync(filePath: string): void { + if (fs.existsSync(filePath)) { + fs.unlinkSync(filePath); } - const mixedInfo: {content: string, sourceMapContent: string} = genContentAndSourceMapInfo(node, toTsFile); - let temporaryFile: string = genTemporaryPath(node.fileName, projectConfig.projectPath, process.env.cachePath, toTsFile); - if (temporaryFile.length === 0) { - return; +} + +export function getExtensionIfUnfullySpecifiedFilepath(filePath: string): string { + if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) { + return ""; } - let temporarySourceMapFile: string = ''; - if (temporaryFile.endsWith(EXTNAME_ETS)) { - if (toTsFile) { - temporaryFile = temporaryFile.replace(/\.ets$/, EXTNAME_TS); - } else { - temporaryFile = temporaryFile.replace(/\.ets$/, EXTNAME_JS); - } - temporarySourceMapFile = genSourceMapFileName(temporaryFile); - } else { - if (!toTsFile) { - temporaryFile = temporaryFile.replace(/\.ts$/, EXTNAME_JS); - temporarySourceMapFile = genSourceMapFileName(temporaryFile); - } + + let extension: string = EXTNAME_ETS; + if (fs.existsSync(filePath + '.ts') && fs.statSync(filePath + '.ts').isFile()) { + extension = '.ts'; + } else if (fs.existsSync(filePath + '.d.ts') && fs.statSync(filePath + '.d.ts').isFile()) { + extension = '.d.ts'; + } else if (fs.existsSync(filePath + '.d.ets') && fs.statSync(filePath + '.d.ets').isFile()) { + extension = '.d.ets'; + } else if (fs.existsSync(filePath + '.js') && fs.statSync(filePath + '.js').isFile()) { + extension = '.js'; + } else if (fs.existsSync(filePath + '.json') && fs.statSync(filePath + '.json').isFile()) { + extension = '.json'; } - mkdirsSync(path.dirname(temporaryFile)); - if (temporarySourceMapFile.length > 0 && projectConfig.buildArkMode === 'debug') { - mixedInfo.content += '\n' + "//# sourceMappingURL=" + path.basename(temporarySourceMapFile); - fs.writeFileSync(temporarySourceMapFile, mixedInfo.sourceMapContent); + + return extension; +} + +export function shouldWriteChangedList(watchModifiedFiles: string[], + watchRemovedFiles: string[]): boolean { + if (projectConfig.compileMode === ESMODULE && process.env.watchMode === 'true' && !projectConfig.isPreview && + projectConfig.changedFileList && (watchRemovedFiles.length + watchModifiedFiles.length)) { + if (process.env.compileTool !== 'rollup') { + if (!(watchModifiedFiles.length === 1 && + watchModifiedFiles[0] === projectConfig.projectPath && !watchRemovedFiles.length)) { + return true; + } else { + return false; + } + } + return true; } - fs.writeFileSync(temporaryFile, mixedInfo.content); + return false; } -function genContentAndSourceMapInfo(node: ts.SourceFile, toTsFile: boolean): any { - const printer: ts.Printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed }); - const options: ts.CompilerOptions = { - sourceMap: true - }; - const mapOpions: any = { - sourceMap: true, - inlineSourceMap: false, - inlineSources: false, - sourceRoot: '', - mapRoot: '', - extendedDiagnostics: false - }; - const host: ts.CompilerHost = ts.createCompilerHost(options); - const fileName: string = node.fileName; - // @ts-ignore - const sourceMapGenerator: any = ts.createSourceMapGenerator( - host, - // @ts-ignore - ts.getBaseFileName(fileName), - '', - '', - mapOpions - ); - // @ts-ignore - const writer: any = ts.createTextWriter( - // @ts-ignore - ts.getNewLineCharacter({newLine: ts.NewLineKind.LineFeed, removeComments: false})); - printer['writeFile'](node, writer, sourceMapGenerator); - const sourceMapJson: any = sourceMapGenerator.toJSON(); - sourceMapJson['sources'] = [fileName]; - const result: string = writer.getText(); - let content: string = result; - content = processSystemApi(content, true); - if (toTsFile) { - content = result.replace(`${TS_NOCHECK};`, TS_NOCHECK); - } - const sourceMapContent: string = JSON.stringify(sourceMapJson); +interface HotReloadIncrementalTime { + hotReloadIncrementalStartTime: string; + hotReloadIncrementalEndTime: string; +} + +export const hotReloadIncrementalTime: HotReloadIncrementalTime = { + hotReloadIncrementalStartTime: '', + hotReloadIncrementalEndTime: '' +}; + +interface FilesObj { + modifiedFiles: string[], + removedFiles: string[] +} +let allModifiedFiles: Set = new Set(); + +export function getHotReloadFiles(watchModifiedFiles: string[], + watchRemovedFiles: string[], hotReloadSupportFiles: Set): FilesObj { + hotReloadIncrementalTime.hotReloadIncrementalStartTime = new Date().getTime().toString(); + watchRemovedFiles = watchRemovedFiles.map(file => path.relative(projectConfig.projectPath, file)); + allModifiedFiles = new Set([...allModifiedFiles, ...watchModifiedFiles + .filter(file => fs.statSync(file).isFile() && + (hotReloadSupportFiles.has(file) || !['.ets', '.ts', '.js'].includes(path.extname(file)))) + .map(file => path.relative(projectConfig.projectPath, file))] + .filter(file => !watchRemovedFiles.includes(file))); return { - content: content, - sourceMapContent: sourceMapContent + modifiedFiles: [...allModifiedFiles], + removedFiles: [...watchRemovedFiles] }; } -export function genAbcFileName(temporaryFile: string): string { - let abcFile: string = temporaryFile; - if (temporaryFile.endsWith(EXTNAME_TS)) { - abcFile = temporaryFile.replace(/\.ts$/, EXTNAME_ABC); +export function getResolveModules(projectPath: string, faMode: boolean): string[] { + if (faMode) { + return [ + path.resolve(projectPath, '../../../../../'), + path.resolve(projectPath, '../../../../' + projectConfig.packageDir), + path.resolve(projectPath, '../../../../../' + projectConfig.packageDir), + path.resolve(projectPath, '../../') + ]; } else { - abcFile = temporaryFile.replace(/\.js$/, EXTNAME_ABC); + return [ + path.resolve(projectPath, '../../../../'), + path.resolve(projectPath, '../../../' + projectConfig.packageDir), + path.resolve(projectPath, '../../../../' + projectConfig.packageDir), + path.resolve(projectPath, '../') + ]; } - return abcFile; } -export function genSourceMapFileName(temporaryFile: string): string { - let abcFile: string = temporaryFile; - if (temporaryFile.endsWith(EXTNAME_TS)) { - abcFile = temporaryFile.replace(/\.ts$/, EXTNAME_TS_MAP); +export function writeUseOSFiles(useOSFiles: Set): void { + let info: string = ''; + if (!fs.existsSync(projectConfig.aceSoPath)) { + const parent: string = path.resolve(projectConfig.aceSoPath, '..'); + if (!(fs.existsSync(parent) && !fs.statSync(parent).isFile())) { + mkDir(parent); + } } else { - abcFile = temporaryFile.replace(/\.js$/, EXTNAME_JS_MAP); + info = fs.readFileSync(projectConfig.aceSoPath, 'utf-8') + '\n'; } - return abcFile; + fs.writeFileSync(projectConfig.aceSoPath, info + Array.from(useOSFiles).join('\n')); } - -export function compareNodeVersion(nodeVersion: number = 16): boolean { - const currentNodeVersion: number = parseInt(process.versions.node.split('.')[0]); - if (currentNodeVersion >= nodeVersion) { - return true; - } - - return false; -} - -export function removeDir(dirName: string): void { - if (fs.existsSync(dirName)) { - if (compareNodeVersion()) { - fs.rmSync(dirName, { recursive: true}); - } else { - fs.rmdirSync(dirName, { recursive: true}); - } - } -} \ No newline at end of file diff --git a/compiler/src/validate_module_syntax.ts b/compiler/src/validate_module_syntax.ts new file mode 100644 index 0000000000000000000000000000000000000000..001eb490032f8de7f2a7e043f919fb56d031e812 --- /dev/null +++ b/compiler/src/validate_module_syntax.ts @@ -0,0 +1,347 @@ +/* + * Copyright (c) 2022 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 ts from 'typescript'; + +import { LogInfo, LogType } from './utils'; +import { IMPORT_FILE_ASTCACHE, generateSourceFileAST, getFileFullPath } from './process_import' + +const FILE_TYPE_EXPORT_NAMES: Map> = new Map(); + +interface ImportName { + name: string, + node: ts.Node, + source: string +} + +function collectNonTypeMarkedReExportName(node: ts.SourceFile, pagesDir: string): Map> { + /* those cases need be validated + * case 1: re-export + * export { externalName as localName } from './xxx' + * + * case 2: indirect re-export nameBindings + * import { externalName as localName } from './xxx' + * export [type] { localName as re-exportName } + * + * case 3: indirect re-export default + * import defaultLocalName from './xxx' + * export [type] { defaultLocalName as re-exportName } + */ + const RE_EXPORT_NAME: Map> = new Map(); + const IMPORT_AS: Map = new Map(); + const EXPORT_LOCAL: Set = new Set(); + + node.statements.forEach(stmt => { + if (ts.isImportDeclaration(stmt) && stmt.importClause && !stmt.importClause.isTypeOnly) { + let fileFullPath: string = getFileFullPath(stmt.moduleSpecifier.getText().replace(/'|"/g, ''), pagesDir); + if (fileFullPath.endsWith('.ets') || fileFullPath.endsWith('.ts')) { + const importClause: ts.ImportClause = stmt.importClause; + if (importClause.name) { + let localName: string = importClause.name.escapedText.toString(); + let importName: ImportName = {name: 'default', node: stmt, source: fileFullPath}; + IMPORT_AS.set(localName, importName); + } + if (importClause.namedBindings && ts.isNamedImports(importClause.namedBindings)) { + importClause.namedBindings.elements.forEach(elem => { + let localName: string = elem.name.escapedText.toString(); + let importName: string = elem.propertyName ? elem.propertyName.escapedText.toString() : localName; + IMPORT_AS.set(localName, {name: importName, node: stmt, source: fileFullPath}) + }); + } + } + } + + if (ts.isExportDeclaration(stmt)) { + // TD: Check `export * from ...` when tsc supports `export type * from ...`. + if (stmt.moduleSpecifier && !stmt.isTypeOnly && stmt.exportClause && ts.isNamedExports(stmt.exportClause)) { + let fileFullPath: string = getFileFullPath(stmt.moduleSpecifier.getText().replace(/'|"/g, ''), pagesDir); + if (fileFullPath.endsWith('.ets') || fileFullPath.endsWith('.ts')) { + stmt.exportClause.elements.forEach(elem => { + let importName: string = elem.propertyName ? elem.propertyName.escapedText.toString() : + elem.name.escapedText.toString(); + if (RE_EXPORT_NAME.has(fileFullPath)) { + RE_EXPORT_NAME.get(fileFullPath).set(importName, stmt); + } else { + RE_EXPORT_NAME.set(fileFullPath, (new Map()).set(importName, stmt)); + } + }); + } + } + if (!stmt.moduleSpecifier && stmt.exportClause && ts.isNamedExports(stmt.exportClause)) { + stmt.exportClause.elements.forEach(elem => { + let localName: string = elem.propertyName ? elem.propertyName.escapedText.toString() : + elem.name.escapedText.toString(); + EXPORT_LOCAL.add(localName); + }); + } + } + }); + + EXPORT_LOCAL.forEach(local => { + if (IMPORT_AS.has(local)) { + let importName: ImportName = IMPORT_AS.get(local); + if (RE_EXPORT_NAME.has(importName.source)) { + RE_EXPORT_NAME.get(importName.source).set(importName.name, importName.node); + } else { + RE_EXPORT_NAME.set(importName.source, (new Map()).set(importName.name, importName.node)); + } + } + }); + + return RE_EXPORT_NAME; +} + +function processTypeImportDecl(node: ts.ImportDeclaration, localTypeNames: Set): void { + if (node.importClause && node.importClause.isTypeOnly) { + // import type T from ... + if (node.importClause.name) { + localTypeNames.add(node.importClause.name.escapedText.toString()); + } + // import type * as T from ... + if (node.importClause.namedBindings && ts.isNamespaceImport(node.importClause.namedBindings)) { + localTypeNames.add(node.importClause.namedBindings.name.escapedText.toString()); + } + // import type { e_T as T } from ... + if (node.importClause.namedBindings && ts.isNamedImports(node.importClause.namedBindings)) { + node.importClause.namedBindings.elements.forEach((elem: any) => { + localTypeNames.add(elem.name.escapedText.toString()); + }); + } + } +} + +function processExportDecl(node: ts.ExportDeclaration, typeExportNames: Set, + exportAs: Map): void { + if (node.isTypeOnly) { + if (node.moduleSpecifier && node.exportClause) { + // export type * as T from ... + if (ts.isNamespaceExport(node.exportClause)) { + typeExportNames.add(node.exportClause.name.escapedText.toString()); + } + // export type { e_T as T } from ... + if (ts.isNamedExports(node.exportClause)) { + node.exportClause.elements.forEach((elem: any) => { + typeExportNames.add(elem.name.escapedText.toString()); + }) + } + } + // export type { e_T as T } + if (!node.moduleSpecifier && node.exportClause && ts.isNamedExports(node.exportClause)) { + node.exportClause.elements.forEach((elem: any) => { + typeExportNames.add(elem.name.escapedText.toString()); + }); + } + } else { + // export { e_T as T } + if (!node.moduleSpecifier && node.exportClause && ts.isNamedExports(node.exportClause)) { + node.exportClause.elements.forEach((elem: any) => { + let exportName: string = elem.name.escapedText.toString(); + let localName: string = elem.propertyName ? elem.propertyName.escapedText.toString() : exportName; + exportAs.set(localName, exportName); + }); + } + } +} + +function processInterfaceAndTypeAlias(node: ts.InterfaceDeclaration | ts.TypeAliasDeclaration, + localTypeNames: Set, typeExportNames: Set): void { + let hasDefault: boolean = false, hasExport: boolean = false; + node.modifiers && node.modifiers.forEach(m => { + if (m.kind == ts.SyntaxKind.DefaultKeyword) { + hasDefault = true; + } + if (m.kind == ts.SyntaxKind.ExportKeyword) { + hasExport = true; + } + }); + localTypeNames.add(node.name.escapedText.toString()); + + if (hasExport) { + let exportName = hasDefault ? 'default' : node.name.escapedText.toString(); + typeExportNames.add(exportName); + } +} + +function checkTypeModuleDeclIsType(node: ts.ModuleDeclaration): boolean { + if (ts.isIdentifier(node.name) && node.body && ts.isModuleBlock(node.body)) { + for (let idx = 0; idx < node.body.statements.length; idx++) { + let stmt: ts.Statement = node.body.statements[idx]; + if (ts.isModuleDeclaration(stmt) && !checkTypeModuleDeclIsType(stmt)) { + return false; + } else if (ts.isImportEqualsDeclaration(stmt)) { + let hasExport: boolean = false; + stmt.modifiers && stmt.modifiers.forEach(m => { + if (m.kind == ts.SyntaxKind.ExportKeyword) { + hasExport = true; + } + }); + if (hasExport) { + return false; + } + } else if (!ts.isInterfaceDeclaration(stmt) && !ts.isTypeAliasDeclaration(stmt)) { + return false; + } + } + } + return true; +} + +function processNamespace(node: ts.ModuleDeclaration, localTypeNames: Set, typeExportNames: Set): void { + if (ts.isIdentifier(node.name) && node.body && ts.isModuleBlock(node.body)) { + if (!checkTypeModuleDeclIsType(node)) { + return; + } + + let hasExport: boolean = false; + node.modifiers && node.modifiers.forEach(m => { + if (m.kind == ts.SyntaxKind.ExportKeyword) { + hasExport = true; + } + }); + if (hasExport) { + typeExportNames.add(node.name.escapedText.toString()); + } + localTypeNames.add(node.name.escapedText.toString()); + } +} + +function addErrorLogIfReExportType(sourceFile: ts.SourceFile, log: LogInfo[], typeExportNames: Set, + exportNames: Map): void { + let reExportNamesArray: Array = Array.from(exportNames.keys()); + let typeExportNamesArray: Array = Array.from(typeExportNames); + const needWarningNames: Array = reExportNamesArray.filter(name => typeExportNamesArray.includes(name)); + needWarningNames.forEach(name => { + const moduleNode: ts.Node = exportNames.get(name)!; + let typeIdentifier: string = name; + if (name === 'default' && ts.isImportDeclaration(moduleNode) && moduleNode.importClause) { + typeIdentifier = moduleNode.importClause.name!.escapedText.toString(); + } + const posOfNode: ts.LineAndCharacter = sourceFile.getLineAndCharacterOfPosition(moduleNode.getStart()); + let warningMessage: string = `The re-export name '${typeIdentifier}' need to be marked as type, `; + warningMessage += ts.isImportDeclaration(moduleNode) ? "please use 'import type'." : "please use 'export type'."; + const warning: LogInfo = { + type: LogType.WARN, + message: warningMessage, + pos: moduleNode.getStart(), + fileName: sourceFile.fileName, + line: posOfNode.line + 1, + column: posOfNode.character + 1 + } + log.push(warning); + }); +} + +function collectTypeExportNames(source: string): Set { + let importFileAst: ts.SourceFile; + if (IMPORT_FILE_ASTCACHE.has(source)) { + importFileAst = IMPORT_FILE_ASTCACHE.get(source); + } else { + importFileAst = generateSourceFileAST(source, source); + IMPORT_FILE_ASTCACHE[source] = importFileAst; + } + const EXPORT_AS: Map = new Map(); + const LOCAL_TYPE_NAMES: Set = new Set(); + const TYPE_EXPORT_NAMES: Set = new Set(); + importFileAst.statements.forEach(stmt => { + switch(stmt.kind) { + case ts.SyntaxKind.ImportDeclaration: { + processTypeImportDecl(stmt, LOCAL_TYPE_NAMES); + break; + } + case ts.SyntaxKind.ExportDeclaration: { + processExportDecl(stmt, TYPE_EXPORT_NAMES, EXPORT_AS); + break; + } + case ts.SyntaxKind.ExportAssignment: { + if (ts.isIdentifier((stmt).expression)) { + EXPORT_AS.set(((stmt).expression).escapedText.toString(), "default"); + } + break; + } + case ts.SyntaxKind.ModuleDeclaration: { + processNamespace(stmt, LOCAL_TYPE_NAMES, TYPE_EXPORT_NAMES); + break; + } + case ts.SyntaxKind.InterfaceDeclaration: + case ts.SyntaxKind.TypeAliasDeclaration: { + processInterfaceAndTypeAlias(stmt, + LOCAL_TYPE_NAMES, TYPE_EXPORT_NAMES); + break; + } + default: + break; + } + }); + LOCAL_TYPE_NAMES.forEach(localName => { + if (EXPORT_AS.has(localName)) { + TYPE_EXPORT_NAMES.add(EXPORT_AS.get(localName)); + } + }); + FILE_TYPE_EXPORT_NAMES.set(source, TYPE_EXPORT_NAMES); + return TYPE_EXPORT_NAMES; +} + +/* + * Validate re-export names from ets/ts file whether is a type by compiling with [TranspileOnly]. + * Currently, there are three scenarios as following can not be validated correctly: + * case 1 export some specify type Identifier from one module's export * from ...: + * // A + * export { xx } from 'B' + * // B + * export * from 'C' + * // C + * export interface xx{} + * case 2 export some type Identifier from indirect .d.ts module: + * // A(ts) + * export { xx } from 'B' + * // B(.d.ts) + * export { xx } from 'C' + * // C(.d.ts) + * export interface xx {} + * case 3 export some type Identifier from '/// .d.ts' + * // A(ts) + * export { xx } from 'B' + * // B(.d.ts) + * ///C // extend B with C by using '///' + * // C(.d.ts) + * export interface xx {} + */ +export default function validateReExportType(node: ts.SourceFile, pagesDir: string, log: LogInfo[]): void { + /* + * those cases' name should be treat as Type + * case1: + * import type {T} from ... + * import type T from ... + * import type * as T from ... + * case2: + * export type {T} from ... + * export type * as T from ... + * case3: + * export interface T {} + * export type T = {} + * case4: + * export default interface {} + * case5: + * interface T {} + * export {T} + */ + const RE_EXPORT_NAME: Map> = collectNonTypeMarkedReExportName(node, pagesDir); + RE_EXPORT_NAME.forEach((exportNames: Map, source: string) => { + let typeExportNames: Set = FILE_TYPE_EXPORT_NAMES.has(source) ? + FILE_TYPE_EXPORT_NAMES.get(source) : collectTypeExportNames(source); + addErrorLogIfReExportType(node, log, typeExportNames, exportNames); + }); +} + \ No newline at end of file diff --git a/compiler/src/validate_ui_syntax.ts b/compiler/src/validate_ui_syntax.ts index be89ff108e9b0dd104a971ba27aa646fe1063f17..83633e685b64c54b9aef5c23bca46f1e3ee8f3fc 100644 --- a/compiler/src/validate_ui_syntax.ts +++ b/compiler/src/validate_ui_syntax.ts @@ -43,6 +43,7 @@ import { STYLES, VALIDATE_MODULE, COMPONENT_BUILDER_DECORATOR, + COMPONENT_CONCURRENT_DECORATOR, COMPONENT_EXTEND_DECORATOR, COMPONENT_STYLES_DECORATOR, RESOURCE_NAME_TYPE, @@ -51,7 +52,10 @@ import { COMPONENT_BUTTON, COMPONENT_TOGGLE, COMPONENT_BUILDERPARAM_DECORATOR, - ESMODULE + ESMODULE, + CARD_ENABLE_DECORATORS, + CARD_LOG_TYPE_DECORATORS, + JSBUNDLE } from './pre_define'; import { INNER_COMPONENT_NAMES, @@ -70,12 +74,15 @@ import { componentInfo, addLog, hasDecorator, - getPackageInfo } from './utils'; +import { getPackageInfo } from './ark_utils' import { projectConfig, abilityPagesFullPath } from '../main'; -import { collectExtend } from './process_ui_syntax'; -import { isExtendFunction } from './process_ui_syntax'; -import { isOhmUrl } from './resolve_ohm_url'; +import { + collectExtend, + isExtendFunction, + transformLog, + validatorCard +} from './process_ui_syntax'; import { logger } from './compile_info'; export interface ComponentCollection { @@ -142,7 +149,8 @@ export const originalImportNamesMap: Map = new Map(); export function validateUISyntax(source: string, content: string, filePath: string, fileQuery: string): LogInfo[] { let log: LogInfo[] = []; - if (path.basename(filePath) !== 'app.ets') { + if (process.env.compileMode === 'moduleJson' || + path.resolve(filePath) !== path.resolve(projectConfig.projectPath || '', 'app.ets')) { const res: LogInfo[] = checkComponentDecorator(source, filePath, fileQuery); if (res) { log = log.concat(res); @@ -248,7 +256,7 @@ export function isObservedClass(node: ts.Node): boolean { } export function isCustomDialogClass(node: ts.Node): boolean { - if (ts.isClassDeclaration(node) && hasDecorator(node, COMPONENT_DECORATOR_CUSTOM_DIALOG)) { + if (ts.isStructDeclaration(node) && hasDecorator(node, COMPONENT_DECORATOR_CUSTOM_DIALOG)) { return true; } return false; @@ -269,9 +277,10 @@ function checkDecorators(decorators: ts.NodeArray, result: Decorat componentCollection.customComponents.add(componentName); switch (name) { case COMPONENT_DECORATOR_ENTRY: - checkEntryComponent(node, log); + checkEntryComponent(node, log, sourceFile); result.entryCount++; componentCollection.entryComponent = componentName; + componentCollection.entryComponentPos = node.getStart(); collectLocalStorageName(element); break; case COMPONENT_DECORATOR_PREVIEW: @@ -308,9 +317,28 @@ function checkDecorators(decorators: ts.NodeArray, result: Decorat } } +function checkConcurrentDecorator(node: ts.FunctionDeclaration | ts.MethodDeclaration, log: LogInfo[], + sourceFile: ts.SourceFile): void { + if (projectConfig.compileMode === JSBUNDLE) { + const message: string = `@Concurrent can only be used in ESMODULE compile mode.`; + addLog(LogType.ERROR, message, node.decorators!.pos, log, sourceFile); + } + if (ts.isMethodDeclaration(node)) { + const message: string = `@Concurrent can not be used on method. please use it on function declaration.`; + addLog(LogType.ERROR, message, node.decorators!.pos, log, sourceFile); + } + if (node.asteriskToken) { + let hasAsync: boolean = false; + const checkAsyncModifier = (modifier: ts.Modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword; + node.modifiers && (hasAsync = node.modifiers.some(checkAsyncModifier)); + const funcKind: string = hasAsync ? 'Async generator' : 'Generator'; + const message: string = `@Concurrent can not be used on ${funcKind} function declaration.`; + addLog(LogType.ERROR, message, node.decorators!.pos, log, sourceFile); + } +} + function collectLocalStorageName(node: ts.Decorator): void { if (node && node.expression && ts.isCallExpression(node.expression)) { - componentCollection.entryComponentPos = node.expression.pos; if (node.expression.arguments && node.expression.arguments.length) { node.expression.arguments.forEach((item: ts.Node, index: number) => { if (ts.isIdentifier(item) && index === 0) { @@ -335,17 +363,24 @@ function visitAllNode(node: ts.Node, sourceFileNode: ts.SourceFile, allComponent if (ts.isStructDeclaration(node) && node.name && ts.isIdentifier(node.name)) { collectComponentProps(node); } - if ((ts.isMethodDeclaration(node) || ts.isFunctionDeclaration(node)) && - hasDecorator(node, COMPONENT_BUILDER_DECORATOR)) { + if (ts.isMethodDeclaration(node) || ts.isFunctionDeclaration(node)) { + if (hasDecorator(node, COMPONENT_BUILDER_DECORATOR)) { CUSTOM_BUILDER_METHOD.add(node.name.getText()); + } + if (hasDecorator(node, COMPONENT_CONCURRENT_DECORATOR)) { + // ark compiler's feature + checkConcurrentDecorator(node, log, sourceFileNode); + } } if (ts.isFunctionDeclaration(node) && isExtendFunction(node)) { const componentName: string = isExtendFunction(node); collectExtend(EXTEND_ATTRIBUTE, componentName, node.name.getText()); } else if (ts.isFunctionDeclaration(node) && hasDecorator(node, COMPONENT_STYLES_DECORATOR)) { - GLOBAL_STYLE_FUNCTION.set(node.name.getText(), node.body); - STYLES_ATTRIBUTE.add(node.name.getText()); - BUILDIN_STYLE_NAMES.add(node.name.getText()); + if (ts.isBlock(node.body) && node.body.statements && node.body.statements.length) { + GLOBAL_STYLE_FUNCTION.set(node.name.getText(), node.body); + STYLES_ATTRIBUTE.add(node.name.getText()); + BUILDIN_STYLE_NAMES.add(node.name.getText()); + } } node.getChildren().forEach((item: ts.Node) => visitAllNode(item, sourceFileNode, allComponentNames, log)); } @@ -439,7 +474,7 @@ function hasNonSingleChild(node: ts.EtsComponentExpression, allComponentNames: S isCheckType: ParamType): boolean { const nodeName: ts.Identifier = node.expression as ts.Identifier; const BlockNode: ts.Block = getNextNode(node); - if ((SINGLE_CHILD_COMPONENT.has(nodeName.escapedText.toString()) || !judgeComponentType(nodeName, node, isCheckType)) + if (SINGLE_CHILD_COMPONENT.has(nodeName.escapedText.toString()) || !judgeComponentType(nodeName, node, isCheckType) && isCheckType.value === COMPONENT_BUTTON) { if (!BlockNode) { return false; @@ -572,7 +607,7 @@ function isNonspecificChildBlock(blockNode: ts.Block, specificChildSet: Set, allComponentNames: Set): boolean { - if (ts.isEtsComponentExpression(node) && node.arguments && + if (ts.isCallExpression(node) && node.arguments && node.arguments.length > 1 && ts.isArrowFunction(node.arguments[1])) { const arrowFunction: ts.ArrowFunction = node.arguments[1] as ts.ArrowFunction; const body: ts.Block | ts.EtsComponentExpression | ts.IfStatement = @@ -739,6 +774,7 @@ function traversalComponentProps(node: ts.StructDeclaration, properties: Set { + const observedProperthCollection: Set = new Set([ + ...stateCollection.get(className), + ...linkCollection.get(className), + ...propCollection.get(className), + ...storageLinkCollection.get(className), + ...storageLinkCollection.get(className), + ...provideCollection.get(className), + ...consumeCollection.get(className), + ...objectLinkCollection.get(className) + ]); + getLocalStorageCollection(className, observedProperthCollection); + return observedProperthCollection; +} + +export function getLocalStorageCollection(componentName: string, collection: Set): void { + if (localStorageLinkCollection.get(componentName)) { + for (const key of localStorageLinkCollection.get(componentName).keys()) { + collection.add(key); + } + } + if (localStoragePropCollection.get(componentName)) { + for (const key of localStoragePropCollection.get(componentName).keys()) { + collection.add(key); + } + } +} diff --git a/compiler/syntax_parser/src/syntax_parser.peg b/compiler/syntax_parser/src/syntax_parser.peg deleted file mode 100644 index 309860e41409dca8248db673107c62ca8e67dbb5..0000000000000000000000000000000000000000 --- a/compiler/syntax_parser/src/syntax_parser.peg +++ /dev/null @@ -1,123 +0,0 @@ -/* - * 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. - */ - -{ - const parse_extend = require('./parse_extend.js'); - - const error_otherParsers = []; - let singleError = function(errMessage, line, column) { - this.errMessage = errMessage; - this.errPosition = { - line: line, - column: column - }; - }; - const collect_extend = { - component: [], - functionName: [], - parameters: [] - }; -} - -start = blocks: block+ -{ - let newContent = ""; - for (let item in blocks) { - if (Array.isArray(blocks[item])) { - newContent += blocks[item].join(''); - } else { - newContent += blocks[item]; - } - } - return { - content: newContent, - location: location(), - collect_extend: collect_extend, - error_otherParsers: error_otherParsers - }; -} - -block = extend/(prefix extend?) -prefix = $((!prefix_extend .)+) -extend = - whiteSpace1:whiteSpace prefix_extend:prefix_extend funcBody_extend:funcBody_extend - whiteSpace2: whiteSpace right:'}' whiteSpace3:whiteSpace -{ - return whiteSpace1 + prefix_extend + funcBody_extend + whiteSpace2 + right + whiteSpace3; -} - -prefix_extend = prefix_extend_one/prefix_extend_another - -//match a kind of extend component -prefix_extend_one = - '@Extend' whiteSpace1:whiteSpace '(' component:component ')' whiteSpace2:whiteSpace 'function' - whiteSpace3:whiteSpace function_name:function_name whiteSpace4:whiteSpace '(' parameters:parameters - ')' whiteSpace5:whiteSpace left:'{' -{ - collect_extend.component.push(component); - collect_extend.functionName.push(function_name); - collect_extend.parameters.push(parameters); - return '@Extend' + whiteSpace1 + whiteSpace2 + 'function' + whiteSpace3 + '__' + component + - '__' + function_name + whiteSpace4 + '(' + parameters + ')' + whiteSpace5 + left + component; -} - -//match another kind of extend component -prefix_extend_another = - '@Extend' whiteSpace1:whiteSpace component:component '.' function_name:function_name - whiteSpace2:whiteSpace '(' parameters:parameters ')' whiteSpace3:whiteSpace left:'{' -{ - collect_extend.component.push(component); - collect_extend.functionName.push(function_name); - collect_extend.parameters.push(parameters); - return '@Extend' + ' function' + whiteSpace1 + '__' + component + '__' + function_name + - whiteSpace2 + '(' + parameters + ')' + whiteSpace3 + left + component; -} - -component = $ [a-zA-Z_]+ -function_name = $ (function_name_head function_name_tail) -function_name_head = $ [a-zA-Z_$]+ -function_name_tail = $ [a-zA-Z0-9_$]* -parameters = $ ([^()]* item* [^()]*) - -//extract Extend internal attribute SyntaxError -funcBody_extend = body:$([^{}]* item* [^{}]*) -{ - try { - parse_extend.parse(body); - return body; - } catch (err) { - let countLines = location().end.line - location().start.line; - if (err.location.start.line === 1) { - err.location.start.column += location().start.column; - } - let supportMessage = " Our rule is .attribute(value) , for example: .width(50) . And you'd better have at least one attribute in Extend Component"; - error_otherParsers.push( - new singleError( - parse_extend.SyntaxError.buildMessage(err.expected, err.found) + supportMessage, - err.location.start.line + location().start.line - 1, - err.location.start.column - ) - ); - let placeHolders = ''; - while (countLines>0) { - placeHolders += '\r\n'; - countLines -= 1; - } - return '()' + placeHolders; - } -} - -item = $ (whiteSpace '{' [^{}]* item* [^{}]* '}' whiteSpace) -whiteSpace = $ [ \t\r\n]* diff --git a/compiler/test/ut/import/importAllEts.ts b/compiler/test/ut/import/importAllEts.ts index 45adf97bfe46a3952b9481dc503e6919057f2bb5..e398ec2ec34cb1c8fff52832b1112c154841a996 100644 --- a/compiler/test/ut/import/importAllEts.ts +++ b/compiler/test/ut/import/importAllEts.ts @@ -98,8 +98,8 @@ function generateId() { const AllComponent = __importStar(require("./test/pages/NamespaceComponent")); const TsModule_1 = __importDefault(require("./test/pages/TsModule")); class ImportTest extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.__myState1 = new ObservedPropertyObject(new TsModule_1.default(1).method(), this, "myState1"); this.__myState2 = new ObservedPropertySimple(0, this, "myState2"); this.__myState3 = new ObservedPropertySimple(false, this, "myState3"); diff --git a/compiler/test/ut/import/importEts.ts b/compiler/test/ut/import/importEts.ts index 41845828170fcea3ee83442b28df91e4c6d837f2..d0b0584043cecdbef55b33a3e7ad60b55896863d 100644 --- a/compiler/test/ut/import/importEts.ts +++ b/compiler/test/ut/import/importEts.ts @@ -132,8 +132,8 @@ const DefaultComponent_1 = __importDefault(require("./test/pages/DefaultComponen const AMDComponentDefault = require("./test/pages/AMDComponent"); const TsModule_1 = __importDefault(require("./test/pages/TsModule")); class ImportTest extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.__myState1 = new ObservedPropertyObject(new TsModule_1.default(1).method(), this, "myState1"); this.__myState2 = new ObservedPropertySimple(0, this, "myState2"); this.__myState3 = new ObservedPropertySimple(false, this, "myState3"); diff --git a/compiler/test/ut/import/importExportEts.ts b/compiler/test/ut/import/importExportEts.ts index 87f220c4816d61090008c4696fb5083d00ef1860..4b32e3ee028c17603d661023b104ad80a30c0cc7 100644 --- a/compiler/test/ut/import/importExportEts.ts +++ b/compiler/test/ut/import/importExportEts.ts @@ -65,8 +65,8 @@ function generateId() { const ExportStarComponent_1 = require("./test/pages/ExportStarComponent"); const TsModule_1 = __importDefault(require("./test/pages/TsModule")); class ImportTest extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.__myState1 = new ObservedPropertyObject(new TsModule_1.default(1).method(), this, "myState1"); this.__myState2 = new ObservedPropertySimple(0, this, "myState2"); this.__myState3 = new ObservedPropertySimple(false, this, "myState3"); diff --git a/compiler/test/ut/import/importExportNest.ts b/compiler/test/ut/import/importExportNest.ts index 917b262683483cc14a94a01f6473107aa41da626..43cf54356d19c9945aa5dc09282d2d26507ba847 100644 --- a/compiler/test/ut/import/importExportNest.ts +++ b/compiler/test/ut/import/importExportNest.ts @@ -64,8 +64,8 @@ function generateId() { } const ImportNestAll_1 = require("./test/pages/ImportNestAll"); class ImportTest extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.__testText1 = new ObservedPropertySimple('Hello', this, "testText1"); this.__testText2 = new ObservedPropertySimple('World', this, "testText2"); this.__testText3 = new ObservedPropertySimple('Test', this, "testText3"); diff --git a/compiler/test/ut/import/importTs.ts b/compiler/test/ut/import/importTs.ts index 96bd6d1e5802567a316ceb36dfe8a3b514d38b66..668ab4763d637f961ea08b2b34864e79ad3a894e 100644 --- a/compiler/test/ut/import/importTs.ts +++ b/compiler/test/ut/import/importTs.ts @@ -65,8 +65,8 @@ function generateId() { const ExportStarComponent_1 = require("./test/pages/ExportStarComponent"); const TsModule_1 = __importDefault(require("./test/pages/TsModule")); class ImportTest extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.__myState1 = new ObservedPropertyObject(new TsModule_1.default(1).method(), this, "myState1"); this.__myState2 = new ObservedPropertySimple(0, this, "myState2"); this.__myState3 = new ObservedPropertySimple(false, this, "myState3"); diff --git a/compiler/test/ut/inner_commponent_transform/$$_component/$$_component.ts b/compiler/test/ut/inner_commponent_transform/$$_component/$$_component.ts index aca5296824784c8c299773b33801433fd9cf6636..790509a2c96f55f9b1c3c4209da83c379b466b7b 100644 --- a/compiler/test/ut/inner_commponent_transform/$$_component/$$_component.ts +++ b/compiler/test/ut/inner_commponent_transform/$$_component/$$_component.ts @@ -83,8 +83,8 @@ const value5 = [true, false]; let value6 = { item1: true }; let isCountDown = false; class HomeComponent extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.value1 = "hello world 1"; this.value2 = "hello world 2"; this.value3 = "hello world 3"; diff --git a/compiler/test/ut/inner_commponent_transform/custom_component/custom_component.ts b/compiler/test/ut/inner_commponent_transform/custom_component/custom_component.ts index 4581aed95bee23243a2df8c3e5897e4a747ae5b4..5e587a6e3c2ea5773c92c20cc564fafce6443269 100644 --- a/compiler/test/ut/inner_commponent_transform/custom_component/custom_component.ts +++ b/compiler/test/ut/inner_commponent_transform/custom_component/custom_component.ts @@ -52,8 +52,8 @@ function generateId() { return "custom_component_" + ++__generate__Id; } class MyComponent extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.updateWithValueParams(params); } updateWithValueParams(params) { @@ -153,8 +153,8 @@ class MyComponent extends View { } } class Banner extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.value = "Hello"; this.updateWithValueParams(params); } diff --git a/compiler/test/ut/inner_commponent_transform/gesture_component/longPressGesture.ts b/compiler/test/ut/inner_commponent_transform/gesture_component/longPressGesture.ts index ec1fc051afe911401007e90bee375ca054426afe..53eff000ef05e45566d0022386a3983f0f6e8c10 100644 --- a/compiler/test/ut/inner_commponent_transform/gesture_component/longPressGesture.ts +++ b/compiler/test/ut/inner_commponent_transform/gesture_component/longPressGesture.ts @@ -43,8 +43,8 @@ function generateId() { return "longPressGesture_" + ++__generate__Id; } class LongPressGestureExample extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.__count = new ObservedPropertySimple(0, this, "count"); this.updateWithValueParams(params); } diff --git a/compiler/test/ut/inner_commponent_transform/gesture_component/panGestrue.ts b/compiler/test/ut/inner_commponent_transform/gesture_component/panGestrue.ts index b2cf0e2d74da3b2b8ead4824a9f93595f40b3a4d..ce9887ec7c39db74163c0ee153f34baa03a7145f 100644 --- a/compiler/test/ut/inner_commponent_transform/gesture_component/panGestrue.ts +++ b/compiler/test/ut/inner_commponent_transform/gesture_component/panGestrue.ts @@ -51,8 +51,8 @@ function generateId() { return "panGestrue_" + ++__generate__Id; } class PanGestureExample extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.__offsetX = new ObservedPropertySimple(0, this, "offsetX"); this.__offsetY = new ObservedPropertySimple(0, this, "offsetY"); this.updateWithValueParams(params); diff --git a/compiler/test/ut/inner_commponent_transform/gesture_component/pinchGesture.ts b/compiler/test/ut/inner_commponent_transform/gesture_component/pinchGesture.ts index 4d2d448724ff08bbcc860c102c88332e00260055..985596ecdbe863564bfe838a997550051e0350ef 100644 --- a/compiler/test/ut/inner_commponent_transform/gesture_component/pinchGesture.ts +++ b/compiler/test/ut/inner_commponent_transform/gesture_component/pinchGesture.ts @@ -47,8 +47,8 @@ function generateId() { return "pinchGesture_" + ++__generate__Id; } class PinchGestureExample extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.__scale = new ObservedPropertySimple(1, this, "scale"); this.updateWithValueParams(params); } diff --git a/compiler/test/ut/inner_commponent_transform/gesture_component/rotationGesture.ts b/compiler/test/ut/inner_commponent_transform/gesture_component/rotationGesture.ts index 61cc82c7f2fa1fd502e02bd57ac96ccdfb357b06..3fb82904814e7d1de6a28fcaadd9438620df7888 100644 --- a/compiler/test/ut/inner_commponent_transform/gesture_component/rotationGesture.ts +++ b/compiler/test/ut/inner_commponent_transform/gesture_component/rotationGesture.ts @@ -47,8 +47,8 @@ function generateId() { return "rotationGesture_" + ++__generate__Id; } class RotationGestureExample extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.__angle = new ObservedPropertySimple(0, this, "angle"); this.updateWithValueParams(params); } diff --git a/compiler/test/ut/inner_commponent_transform/gesture_component/swipeGesture.ts b/compiler/test/ut/inner_commponent_transform/gesture_component/swipeGesture.ts index 92f940ed2a3dc32a4123997b6ee397713b3cf76f..d48922dda4118ba5458b48bd0145fcf51c628060 100644 --- a/compiler/test/ut/inner_commponent_transform/gesture_component/swipeGesture.ts +++ b/compiler/test/ut/inner_commponent_transform/gesture_component/swipeGesture.ts @@ -45,8 +45,8 @@ function generateId() { return "swipeGesture_" + ++__generate__Id; } class SwipeGestureExample extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.__rotateAngle = new ObservedPropertySimple(0, this, "rotateAngle"); this.__speed = new ObservedPropertySimple(1, this, "speed"); this.updateWithValueParams(params); diff --git a/compiler/test/ut/inner_commponent_transform/gesture_component/tapGesture.ts b/compiler/test/ut/inner_commponent_transform/gesture_component/tapGesture.ts index 286243470948f94f5e384d197050b36b956dd309..70696e74c9be013d1e0bdfbccd34aaa27c915273 100644 --- a/compiler/test/ut/inner_commponent_transform/gesture_component/tapGesture.ts +++ b/compiler/test/ut/inner_commponent_transform/gesture_component/tapGesture.ts @@ -41,8 +41,8 @@ function generateId() { return "tapGesture_" + ++__generate__Id; } class TapGestureExample extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.__value = new ObservedPropertySimple('', this, "value"); this.updateWithValueParams(params); } diff --git a/compiler/test/ut/inner_commponent_transform/render_component/forEach/forEach.ts b/compiler/test/ut/inner_commponent_transform/render_component/forEach/forEach.ts index 57b366f947f535eb994971cf09e2af82ba5e0f1b..72f3124988964f2a1ee52175d8f6df64b7020df5 100644 --- a/compiler/test/ut/inner_commponent_transform/render_component/forEach/forEach.ts +++ b/compiler/test/ut/inner_commponent_transform/render_component/forEach/forEach.ts @@ -115,8 +115,8 @@ class Month { } } class MyComponent extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.languages = ['ets', 'js', 'java']; this.weekNames = ['日', '一', '二', '三', '四', '五', '六']; this.__calendar = new ObservedPropertyObject([ diff --git a/compiler/test/ut/inner_commponent_transform/render_component/forEach/forEachTwo.ts b/compiler/test/ut/inner_commponent_transform/render_component/forEach/forEachTwo.ts new file mode 100644 index 0000000000000000000000000000000000000000..708100306c83c1a5a75787719c4a552cbc0f6aec --- /dev/null +++ b/compiler/test/ut/inner_commponent_transform/render_component/forEach/forEachTwo.ts @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2022 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. + */ + +exports.source = ` +@Entry +@Component +struct Index { + @State WIDTH_AND_HEIGHT: Array<{ w: number, h: number }> = [ + { w: 10, h: 10 }, + { w: 20, h: 20 }, + { w: 30, h: 30 }, + { w: 40, h: 40 }, + { w: 50, h: 50 } + ] + build() { + Row() { + Column() { + ForEach(this.WIDTH_AND_HEIGHT, ({ w, h }) => { + Button() + .width(w) + .height(h) + }, item => item.toString()) + } + .width('100%') + } + .height('100%') + } +}` + +exports.expectResult = +`"use strict"; +let __generate__Id = 0; +function generateId() { + return "forEachTwo_" + ++__generate__Id; +} +class Index extends View { + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); + this.__WIDTH_AND_HEIGHT = new ObservedPropertyObject([ + { w: 10, h: 10 }, + { w: 20, h: 20 }, + { w: 30, h: 30 }, + { w: 40, h: 40 }, + { w: 50, h: 50 } + ], this, "WIDTH_AND_HEIGHT"); + this.updateWithValueParams(params); + } + updateWithValueParams(params) { + if (params.WIDTH_AND_HEIGHT !== undefined) { + this.WIDTH_AND_HEIGHT = params.WIDTH_AND_HEIGHT; + } + } + aboutToBeDeleted() { + this.__WIDTH_AND_HEIGHT.aboutToBeDeleted(); + SubscriberManager.Get().delete(this.id()); + } + get WIDTH_AND_HEIGHT() { + return this.__WIDTH_AND_HEIGHT.get(); + } + set WIDTH_AND_HEIGHT(newValue) { + this.__WIDTH_AND_HEIGHT.set(newValue); + } + render() { + Row.create(); + Row.height('100%'); + Column.create(); + Column.width('100%'); + ForEach.create("2", this, ObservedObject.GetRawObject(this.WIDTH_AND_HEIGHT), ({ w, h }) => { + Button.createWithLabel(); + Button.width(w); + Button.height(h); + Button.pop(); + }, item => item.toString()); + ForEach.pop(); + Column.pop(); + Row.pop(); + } +} +loadDocument(new Index("1", undefined, {})); +` diff --git a/compiler/test/ut/inner_commponent_transform/render_component/if/if.ts b/compiler/test/ut/inner_commponent_transform/render_component/if/if.ts index 30ff18c3d69982788f6163e52ff4b172f6ae55b6..368413ba34310ce8445a5933f781f3696477269b 100644 --- a/compiler/test/ut/inner_commponent_transform/render_component/if/if.ts +++ b/compiler/test/ut/inner_commponent_transform/render_component/if/if.ts @@ -61,8 +61,8 @@ function generateId() { const TestComponent_1 = require("./test/pages/TestComponent"); const TsModule_1 = require("./test/pages/TsModule"); class MyComponent extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.pass = true; this.count = 10; this.updateWithValueParams(params); diff --git a/compiler/test/ut/inner_commponent_transform/render_component/lazyForEach/lazyForEach.ts b/compiler/test/ut/inner_commponent_transform/render_component/lazyForEach/lazyForEach.ts index 08b7a3a8f7c2a93118464b73f6766396e89f496c..5e584b1e9aa550f07512923336f2f7838c4afb1b 100644 --- a/compiler/test/ut/inner_commponent_transform/render_component/lazyForEach/lazyForEach.ts +++ b/compiler/test/ut/inner_commponent_transform/render_component/lazyForEach/lazyForEach.ts @@ -182,8 +182,8 @@ class MyDataSource extends BasicDataSource { } } class MyComponent extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.data = new MyDataSource(); this.updateWithValueParams(params); } diff --git a/compiler/test/ut/inner_commponent_transform/simple_component/button/button.ts b/compiler/test/ut/inner_commponent_transform/simple_component/button/button.ts index 885a8aec0ffb6fd539d09d112b589ab9c3db7fa9..6b6d74d06384c484fe96b9a66ced75ad6447ead2 100644 --- a/compiler/test/ut/inner_commponent_transform/simple_component/button/button.ts +++ b/compiler/test/ut/inner_commponent_transform/simple_component/button/button.ts @@ -40,8 +40,8 @@ function generateId() { return "button_" + ++__generate__Id; } class ButtonExample extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.updateWithValueParams(params); } updateWithValueParams(params) { diff --git a/compiler/test/ut/inner_commponent_transform/transition_component/animateTo/animateTo.ts b/compiler/test/ut/inner_commponent_transform/transition_component/animateTo/animateTo.ts index d0cfe72e10a78e4a9049bc0016d05fda790ac431..3399a360d774c7eac2816bb43ee5da6ccfbddf4a 100644 --- a/compiler/test/ut/inner_commponent_transform/transition_component/animateTo/animateTo.ts +++ b/compiler/test/ut/inner_commponent_transform/transition_component/animateTo/animateTo.ts @@ -52,6 +52,26 @@ struct TransitionExample { iterations: 1, // 播放次数 playMode: PlayMode.Normal // 动画模式 }) + Column({space: 5}) { + Column() + .opacity(this.opacity1) + .backgroundColor(this.color) + .animation({duration: 1000}) + .width(this.width1) + .animation({duration: 2000}) + .height(this.height1) + .borderRadius(this.borderRaius1) + .animation({duration: 3000}) + .onClick(() => { + this.color = Color.Green + this.borderRaius1 = 20 + this.opacity1 = 0.5 + this.height1 = 200 + this.width1 = 200 + }) + } + .width("100%") + .height("100%") }.height(400).width("100%").padding({top:100}) } } @@ -64,8 +84,8 @@ function generateId() { return "animateTo_" + ++__generate__Id; } class TransitionExample extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.__btnW = new ObservedPropertySimple(50, this, "btnW"); this.__btnH = new ObservedPropertySimple(50, this, "btnH"); this.__btn1 = new ObservedPropertySimple(false, this, "btn1"); @@ -161,6 +181,30 @@ class TransitionExample extends View { }); Context.animation(null); Button.pop(); + Column.create({ space: 5 }); + Column.width("100%"); + Column.height("100%"); + Column.create(); + Context.animation({ duration: 1000 }); + Column.opacity(this.opacity1); + Column.backgroundColor(this.color); + Context.animation(null); + Context.animation({ duration: 2000 }); + Column.width(this.width1); + Context.animation(null); + Context.animation({ duration: 3000 }); + Column.height(this.height1); + Column.borderRadius(this.borderRaius1); + Context.animation(null); + Column.onClick(() => { + this.color = Color.Green; + this.borderRaius1 = 20; + this.opacity1 = 0.5; + this.height1 = 200; + this.width1 = 200; + }); + Column.pop(); + Column.pop(); Flex.pop(); } } diff --git a/compiler/test/ut/inner_commponent_transform/transition_component/pageTransition/pageTransition.ts b/compiler/test/ut/inner_commponent_transform/transition_component/pageTransition/pageTransition.ts index 47d8c97f302d6cdd150d50a6161ac2103b080edb..b5a3cee5fa90559f1b4642e88bbbcf28b719fff6 100644 --- a/compiler/test/ut/inner_commponent_transform/transition_component/pageTransition/pageTransition.ts +++ b/compiler/test/ut/inner_commponent_transform/transition_component/pageTransition/pageTransition.ts @@ -52,8 +52,8 @@ function generateId() { return "pageTransition_" + ++__generate__Id; } class PageTransitionExample1 extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.__scale = new ObservedPropertySimple(1, this, "scale"); this.__opacity = new ObservedPropertySimple(1, this, "opacity"); this.__active = new ObservedPropertySimple(false, this, "active"); diff --git a/compiler/test/ut/render_decorator/@builder/@builder.ts b/compiler/test/ut/render_decorator/@builder/@builder.ts index 39bce30483d0d7ca21a75d4c8e9c81853a18ba8c..ad993f95bbcb2562cca284379d9cf4e82acf92cb 100644 --- a/compiler/test/ut/render_decorator/@builder/@builder.ts +++ b/compiler/test/ut/render_decorator/@builder/@builder.ts @@ -147,13 +147,13 @@ let __generate__Id = 0; function generateId() { return "@builder_" + ++__generate__Id; } -function noParam(parent = undefined) { +function noParam(parent = null) { Row.create(); Text.create('this is a no param builder'); Text.pop(); Row.pop(); } -function specificParam(label1, label2, parent = undefined) { +function specificParam(label1, label2, parent = null) { Column.create(); Text.create(label1); Text.pop(); @@ -162,8 +162,8 @@ function specificParam(label1, label2, parent = undefined) { Column.pop(); } class MyComponent extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; this.controller = new TabsController(); this.__hideBar = new ObservedPropertySimple(true, this, "hideBar"); @@ -190,12 +190,12 @@ class MyComponent extends View { set hideBar(newValue) { this.__hideBar.set(newValue); } - textBuilder(parent = undefined) { + textBuilder(parent = null) { Text.create("文本"); Text.fontSize(30); Text.pop(); } - NavigationTitlePara(label, parent = undefined) { + NavigationTitlePara(label, parent = null) { Column.create(); Text.create(label); Text.width(80); @@ -203,7 +203,7 @@ class MyComponent extends View { Text.pop(); Column.pop(); } - MenuBuilder(parent = undefined) { + MenuBuilder(parent = null) { Flex.create({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }); Flex.width(100); Text.create('Test menu item 1'); @@ -221,7 +221,7 @@ class MyComponent extends View { Row.create(); Row.padding(10); Row.bindMenu({ builder: () => { - this.NavigationTitlePara("111"); + this.NavigationTitlePara.call(this, "111"); } }); Text.create("Drag Me"); Text.onDragStart((event, extraParams) => { @@ -252,7 +252,7 @@ class MyComponent extends View { Row.create(); Row.padding(10); Navigation.create(); - Navigation.title({ builder: noParam }); + Navigation.title({ builder: noParam.bind(this) }); Navigation.menus({ builder: this.textBuilder.bind(this) }); Navigation.toolBar({ items: [ { value: 'app', text: 'Grid', action: () => { diff --git a/compiler/test/ut/render_decorator/@builder/@builderWithForEach.ts b/compiler/test/ut/render_decorator/@builder/@builderWithForEach.ts new file mode 100644 index 0000000000000000000000000000000000000000..b314b90b875eca5d03b0d5e93cdf12c29b7f3b2c --- /dev/null +++ b/compiler/test/ut/render_decorator/@builder/@builderWithForEach.ts @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2022 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. + */ + +exports.source = ` +@Builder +function ComB(param: string[]) { + ForEach(param, item => { + ComA().backgroundColor('red') + }) +} + +@Entry +@Component +struct Index { + @State arr: string[] = ['1', '2', '3', '4', '5'] + + build() { + Column() { + ComB(this.arr); + } + } +} + +@Component +struct ComA { + build() { + Row() { + Text('自定义组件') + .fontSize(30) + } + } +} +` +exports.expectResult = +`"use strict"; +let __generate__Id = 0; +function generateId() { + return "@builderWithForEach_" + ++__generate__Id; +} +function ComB(param, parent = null) { + ForEach.create("3", parent ? parent : this, ObservedObject.GetRawObject(param), item => { + __Common__.create(); + __Common__.backgroundColor('red'); + let earlierCreatedChild_2 = ((parent ? parent : this) && (parent ? parent : this).findChildById) ? (parent ? parent : this).findChildById(generateId()) : undefined; + if (earlierCreatedChild_2 == undefined) { + View.create(new ComA("@builderWithForEach_" + __generate__Id, parent ? parent : this, {})); + } + else { + earlierCreatedChild_2.updateWithValueParams({}); + if (!earlierCreatedChild_2.needsUpdate()) { + earlierCreatedChild_2.markStatic(); + } + View.create(earlierCreatedChild_2); + } + __Common__.pop(); + }); + ForEach.pop(); +} +class Index extends View { + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); + this.__arr = new ObservedPropertyObject(['1', '2', '3', '4', '5'], this, "arr"); + this.updateWithValueParams(params); + } + updateWithValueParams(params) { + if (params.arr !== undefined) { + this.arr = params.arr; + } + } + aboutToBeDeleted() { + this.__arr.aboutToBeDeleted(); + SubscriberManager.Get().delete(this.id()); + } + get arr() { + return this.__arr.get(); + } + set arr(newValue) { + this.__arr.set(newValue); + } + render() { + Column.create(); + ComB(this.arr, this); + Column.pop(); + } +} +class ComA extends View { + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); + this.updateWithValueParams(params); + } + updateWithValueParams(params) { + } + aboutToBeDeleted() { + SubscriberManager.Get().delete(this.id()); + } + render() { + Row.create(); + Text.create('自定义组件'); + Text.fontSize(30); + Text.pop(); + Row.pop(); + } +} +loadDocument(new Index("1", undefined, {})); +` diff --git a/compiler/test/ut/render_decorator/@builder/@builderWithLinkData.ts b/compiler/test/ut/render_decorator/@builder/@builderWithLinkData.ts index 4f00664325835ffa634bef619de86ebbfe40afc4..a5d64b5d6b18fd1eb8842d8fe1d8a57b7438fa28 100644 --- a/compiler/test/ut/render_decorator/@builder/@builderWithLinkData.ts +++ b/compiler/test/ut/render_decorator/@builder/@builderWithLinkData.ts @@ -44,8 +44,8 @@ function generateId() { return "@builderWithLinkData_" + ++__generate__Id; } class TitleComp extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.__title = new SynchedPropertySimpleTwoWay(params.title, this, "title"); this.updateWithValueParams(params); } @@ -67,8 +67,8 @@ class TitleComp extends View { } } class TestPage extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.__value = new ObservedPropertySimple('hello world', this, "value"); this.updateWithValueParams(params); } @@ -87,7 +87,7 @@ class TestPage extends View { set value(newValue) { this.__value.set(newValue); } - TitleCompView(parent = undefined) { + TitleCompView(parent = null) { let earlierCreatedChild_2 = ((parent ? parent : this) && (parent ? parent : this).findChildById) ? (parent ? parent : this).findChildById(generateId()) : undefined; if (earlierCreatedChild_2 == undefined) { View.create(new TitleComp("@builderWithLinkData_" + __generate__Id, parent ? parent : this, { title: this.__value })); diff --git a/compiler/test/ut/render_decorator/@builderParam/@builderParam.ts b/compiler/test/ut/render_decorator/@builderParam/@builderParam.ts index 0f28ad6401d271545a174c5af8051216385a6178..a7b4d139a3193cdb49eb8c3934ab934193e8248a 100644 --- a/compiler/test/ut/render_decorator/@builderParam/@builderParam.ts +++ b/compiler/test/ut/render_decorator/@builderParam/@builderParam.ts @@ -43,6 +43,13 @@ struct CustomContainer2 { } } +@Builder function specificWithParam(label1: string, label2: string) { + Column() { + Text(label1).fontSize(50) + Text(label2).fontSize(50) + } +} + @Entry @Component struct CustomContainerUser { @@ -65,7 +72,7 @@ struct CustomContainerUser { header: this.text, }){ Column(){ - specificParam("111", "22") + specificWithParam("111", "22") }.onClick(()=>{ this.text = "changeHeader" }) @@ -102,8 +109,8 @@ function generateId() { } const TestComponent_1 = require("./test/pages/TestComponent"); class CustomContainer extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.header = ""; this.footer = ""; this.updateWithValueParams(params); @@ -133,8 +140,8 @@ class CustomContainer extends View { } } class CustomContainer2 extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.header = ""; this.updateWithValueParams(params); } @@ -155,9 +162,19 @@ class CustomContainer2 extends View { Column.pop(); } } +function specificWithParam(label1, label2, parent = null) { + Column.create(); + Text.create(label1); + Text.fontSize(50); + Text.pop(); + Text.create(label2); + Text.fontSize(50); + Text.pop(); + Column.pop(); +} class CustomContainerUser extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.__text = new ObservedPropertySimple('header', this, "text"); this.updateWithValueParams(params); } @@ -176,14 +193,14 @@ class CustomContainerUser extends View { set text(newValue) { this.__text.set(newValue); } - specificParam(parent = undefined) { + specificParam(parent = null) { Column.create(); Text.create("content"); Text.fontSize(50); Text.pop(); Column.pop(); } - callSpecificParam(label1, label2, parent = undefined) { + callSpecificParam(label1, label2, parent = null) { Column.create(); Text.create(label1); Text.fontSize(50); @@ -204,7 +221,7 @@ class CustomContainerUser extends View { Column.onClick(() => { this.text = "changeHeader"; }); - specificParam("111", "22", this); + specificWithParam("111", "22", this); Column.pop(); } })); @@ -217,7 +234,7 @@ class CustomContainerUser extends View { Column.onClick(() => { this.text = "changeHeader"; }); - specificParam("111", "22", this); + specificWithParam("111", "22", this); Column.pop(); } }); diff --git a/compiler/test/ut/render_decorator/@customDialog/@customDialog.ts b/compiler/test/ut/render_decorator/@customDialog/@customDialog.ts index b74df8d4e0037cdd112fcc42283f53063f8d2153..c6363286fb49e5b245e0fa14342515611a65485f 100644 --- a/compiler/test/ut/render_decorator/@customDialog/@customDialog.ts +++ b/compiler/test/ut/render_decorator/@customDialog/@customDialog.ts @@ -105,8 +105,8 @@ function generateId() { return "@customDialog_" + ++__generate__Id; } class DialogExample extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.__count = new SynchedPropertySimpleOneWay(params.count, this, "count"); this.__isPlaying = new SynchedPropertySimpleTwoWay(params.isPlaying, this, "isPlaying"); this.controller = undefined; @@ -184,8 +184,8 @@ class DialogExample extends View { } } class CustomDialogUser extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.__countInitValue = new ObservedPropertySimple(10, this, "countInitValue"); this.__playingInitValue = new ObservedPropertySimple(false, this, "playingInitValue"); this.dialogController = new CustomDialogController({ diff --git a/compiler/test/ut/render_decorator/@extend/@extend.ts b/compiler/test/ut/render_decorator/@extend/@extend.ts index 20815e509296f16b1ad259f0dc86d2d160e404b0..594d83546d60f20fab710ff23b282a4b7d91f892 100644 --- a/compiler/test/ut/render_decorator/@extend/@extend.ts +++ b/compiler/test/ut/render_decorator/@extend/@extend.ts @@ -72,8 +72,8 @@ function __Button__fancybut(color) { Button.height(100); } class FancyUse extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.updateWithValueParams(params); } updateWithValueParams(params) { diff --git a/compiler/test/ut/render_decorator/@preview/@preview.ts b/compiler/test/ut/render_decorator/@preview/@preview.ts index 40147a25a3be8e596ee5dd6f7e3569a93bf6b9ff..8f2706b58798dafca35a3c833f38c8e7b60548ae 100644 --- a/compiler/test/ut/render_decorator/@preview/@preview.ts +++ b/compiler/test/ut/render_decorator/@preview/@preview.ts @@ -43,8 +43,8 @@ function generateId() { return "@preview_" + ++__generate__Id; } class HomePreviewComponent extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.value = "hello world"; this.updateWithValueParams(params); } @@ -63,8 +63,8 @@ class HomePreviewComponent extends View { } } class HomePreviewComponent_Preview extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.updateWithValueParams(params); } updateWithValueParams(params) { diff --git a/compiler/test/ut/render_decorator/@styles/@styles.ts b/compiler/test/ut/render_decorator/@styles/@styles.ts index 61708a1de8486f09269c9ed852bb960319a6ae8a..d1c3aac043cf3fc00360246c4367e251b6fa995c 100644 --- a/compiler/test/ut/render_decorator/@styles/@styles.ts +++ b/compiler/test/ut/render_decorator/@styles/@styles.ts @@ -60,8 +60,8 @@ function generateId() { return "@styles_" + ++__generate__Id; } class FancyUse extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.__enable = new ObservedPropertySimple(true, this, "enable"); this.updateWithValueParams(params); } diff --git a/compiler/test/ut/render_decorator/@styles/@stylesExport.ts b/compiler/test/ut/render_decorator/@styles/@stylesExport.ts index 55acdc9410cabaf1d9084e68a2225aeeeab6ef16..c4a072fdabe4cb8a7552f62da8a4e05d30e1fbf0 100644 --- a/compiler/test/ut/render_decorator/@styles/@stylesExport.ts +++ b/compiler/test/ut/render_decorator/@styles/@stylesExport.ts @@ -63,8 +63,8 @@ function generateId() { return "@stylesExport_" + ++__generate__Id; } class FancyUseExp extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.__enable = new ObservedPropertySimple(true, this, "enable"); this.updateWithValueParams(params); } diff --git a/compiler/test/ut/ui_state_management/application_state_management/@storageLink/@storageLink.ts b/compiler/test/ut/ui_state_management/application_state_management/@storageLink/@storageLink.ts index 3b3983a55711adaea0e350f6fcea24e403607baa..942c8258a3b957425316458356b5b0768c9db85d 100644 --- a/compiler/test/ut/ui_state_management/application_state_management/@storageLink/@storageLink.ts +++ b/compiler/test/ut/ui_state_management/application_state_management/@storageLink/@storageLink.ts @@ -56,8 +56,8 @@ function generateId() { let varA = AppStorage.Link('varA'); let envLang = AppStorage.Prop('languageCode'); class MyComponent extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.__varA = AppStorage.SetAndLink('varA', 2, this, "varA"); this.__lang = AppStorage.SetAndProp('languageCode', 'en', this, "lang"); this.label = 'count'; @@ -82,6 +82,9 @@ class MyComponent extends View { get lang() { return this.__lang.get(); } + set lang(newValue) { + this.__lang.set(newValue); + } aboutToAppear() { this.label = (this.lang === 'zh') ? '数' : 'Count'; } diff --git a/compiler/test/ut/ui_state_management/application_state_management/@storageProp/@storageProp.ts b/compiler/test/ut/ui_state_management/application_state_management/@storageProp/@storageProp.ts index 26b0f63761ca0a6e87147712f3cbf52c292a1a31..b95ca3fd59a4c7fcf7f2aca2746529269efb4611 100644 --- a/compiler/test/ut/ui_state_management/application_state_management/@storageProp/@storageProp.ts +++ b/compiler/test/ut/ui_state_management/application_state_management/@storageProp/@storageProp.ts @@ -56,8 +56,8 @@ function generateId() { let varA = AppStorage.Link('varA'); let envLang = AppStorage.Prop('languageCode'); class MyComponent extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.__varA = AppStorage.SetAndLink('varA', 2, this, "varA"); this.__lang = AppStorage.SetAndProp('languageCode', 'en', this, "lang"); this.label = 'count'; @@ -82,6 +82,9 @@ class MyComponent extends View { get lang() { return this.__lang.get(); } + set lang(newValue) { + this.__lang.set(newValue); + } aboutToAppear() { this.label = (this.lang === 'zh') ? '数' : 'Count'; } diff --git a/compiler/test/ut/ui_state_management/application_state_management/appStorage/appStorage.ts b/compiler/test/ut/ui_state_management/application_state_management/appStorage/appStorage.ts index 3be55c9ab7dcc5b0841875b65dfa9d15427b1065..f26c16c4611de9f050378ae49235039780cdf877 100644 --- a/compiler/test/ut/ui_state_management/application_state_management/appStorage/appStorage.ts +++ b/compiler/test/ut/ui_state_management/application_state_management/appStorage/appStorage.ts @@ -56,8 +56,8 @@ function generateId() { let varA = AppStorage.Link('varA'); let envLang = AppStorage.Prop('languageCode'); class MyComponent extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.__varA = AppStorage.SetAndLink('varA', 2, this, "varA"); this.__lang = AppStorage.SetAndProp('languageCode', 'en', this, "lang"); this.label = 'count'; @@ -82,6 +82,9 @@ class MyComponent extends View { get lang() { return this.__lang.get(); } + set lang(newValue) { + this.__lang.set(newValue); + } aboutToAppear() { this.label = (this.lang === 'zh') ? '数' : 'Count'; } diff --git a/compiler/test/ut/ui_state_management/inner_struct_state_management/@link/@link.ts b/compiler/test/ut/ui_state_management/inner_struct_state_management/@link/@link.ts index 122b8eb5d4e2773fc5cc264a5f82e8e6d3bbc819..767b326e5a072beaa1fa738821e246006d6fb04c 100644 --- a/compiler/test/ut/ui_state_management/inner_struct_state_management/@link/@link.ts +++ b/compiler/test/ut/ui_state_management/inner_struct_state_management/@link/@link.ts @@ -74,8 +74,8 @@ function generateId() { return "@link_" + ++__generate__Id; } class linkComp extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.__buttonPlaying = new SynchedPropertySimpleTwoWay(params.buttonPlaying, this, "buttonPlaying"); this.__items = new SynchedPropertyObjectTwoWay(params.items, this, "items"); this.__obj = new SynchedPropertyObjectTwoWay(params.obj, this, "obj"); @@ -145,8 +145,8 @@ class linkComp extends View { } } class linkPage extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.__isPlaying = new ObservedPropertySimple(false, this, "isPlaying"); this.__itemsArr = new ObservedPropertyObject([1, 2, 3], this, "itemsArr"); this.__peoples = new ObservedPropertyObject([{ name: 'xiaoming', age: 8 }], this, "peoples"); diff --git a/compiler/test/ut/ui_state_management/inner_struct_state_management/@prop/@prop.ts b/compiler/test/ut/ui_state_management/inner_struct_state_management/@prop/@prop.ts index 63fa5a110980c8240f519c8122fa2b6dcd82946f..1264026d68f22d64987ad0484cc6724a1c31baf8 100644 --- a/compiler/test/ut/ui_state_management/inner_struct_state_management/@prop/@prop.ts +++ b/compiler/test/ut/ui_state_management/inner_struct_state_management/@prop/@prop.ts @@ -70,8 +70,8 @@ function generateId() { return "@prop_" + ++__generate__Id; } class ctComponent extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.__name = new SynchedPropertySimpleOneWay(params.name, this, "name"); this.__canPlay = new SynchedPropertySimpleOneWay(params.canPlay, this, "canPlay"); this.__count = new SynchedPropertySimpleOneWay(params.count, this, "count"); @@ -145,8 +145,8 @@ class ctComponent extends View { } } class PageComponent extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.__countDownStartValue = new ObservedPropertySimple(10, this, "countDownStartValue"); this.updateWithValueParams(params); } diff --git a/compiler/test/ut/ui_state_management/inner_struct_state_management/@state/@state.ts b/compiler/test/ut/ui_state_management/inner_struct_state_management/@state/@state.ts index af6344a7f318435e0f5e3d89dfb613a984d5e5a1..4f07058eb58bea491552c9dfc44277acab2b1d0f 100644 --- a/compiler/test/ut/ui_state_management/inner_struct_state_management/@state/@state.ts +++ b/compiler/test/ut/ui_state_management/inner_struct_state_management/@state/@state.ts @@ -67,8 +67,8 @@ class Model { } } class MyComponent extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.__title = new ObservedPropertyObject({ value: 'Hello World' }, this, "title"); this.__count = new ObservedPropertySimple(0, this, "count"); this.toggle = 'Hello World'; @@ -128,8 +128,8 @@ class MyComponent extends View { } } class EntryComponent extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.updateWithValueParams(params); } updateWithValueParams(params) { diff --git a/compiler/test/ut/ui_state_management/others/@consume_@provide/@consume_@provide.ts b/compiler/test/ut/ui_state_management/others/@consume_@provide/@consume_@provide.ts index da7a9fbc04642e07e6be2654500be6ff5d225a2a..17ac942d6cd016c2b7cf968449d7fe57326162d1 100644 --- a/compiler/test/ut/ui_state_management/others/@consume_@provide/@consume_@provide.ts +++ b/compiler/test/ut/ui_state_management/others/@consume_@provide/@consume_@provide.ts @@ -65,8 +65,8 @@ function generateId() { return "@consume_@provide_" + ++__generate__Id; } class CompA extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.__reviewVotes = new ObservedPropertySimple(0, this, "reviewVotes"); this.addProvidedVar("reviewVote", this.__reviewVotes); this.addProvidedVar("reviewVotes", this.__reviewVotes); @@ -112,8 +112,8 @@ class CompA extends View { } } class CompB extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.updateWithValueParams(params); } updateWithValueParams(params) { @@ -135,8 +135,8 @@ class CompB extends View { } } class CompC extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.__reviewVotes = this.initializeConsume("reviewVote", "reviewVotes"); this.updateWithValueParams(params); } diff --git a/compiler/test/ut/ui_state_management/others/@observed_@objectLink/@observed_@objectLink.ts b/compiler/test/ut/ui_state_management/others/@observed_@objectLink/@observed_@objectLink.ts index ff9d97610b1f8ac471ab0bf88a714c5fe5174610..70ee4a38aff0fcebb2f9d6f80574cd3cb47e27a2 100644 --- a/compiler/test/ut/ui_state_management/others/@observed_@objectLink/@observed_@objectLink.ts +++ b/compiler/test/ut/ui_state_management/others/@observed_@objectLink/@observed_@objectLink.ts @@ -87,8 +87,8 @@ ClassB = __decorate([ Observed ], ClassB); class ViewA extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.__varA = new SynchedPropertyNesedObject(params.varA, this, "varA"); this.updateWithValueParams(params); } @@ -110,8 +110,8 @@ class ViewA extends View { } } class ViewB extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.__varB = new ObservedPropertyObject(new ClassB(new ClassA(0)), this, "varB"); this.updateWithValueParams(params); } diff --git a/compiler/test/ut/ui_state_management/others/@watch/@watch.ts b/compiler/test/ut/ui_state_management/others/@watch/@watch.ts index 7d246a6894c6b9d35241d44fef583004f211cbb1..8d11c8af887bf0e80cf825d92472ad176e45b01c 100644 --- a/compiler/test/ut/ui_state_management/others/@watch/@watch.ts +++ b/compiler/test/ut/ui_state_management/others/@watch/@watch.ts @@ -71,15 +71,15 @@ function generateId() { return "@watch_" + ++__generate__Id; } class CompA extends View { - constructor(compilerAssignedUniqueChildId, parent, params) { - super(compilerAssignedUniqueChildId, parent); + constructor(compilerAssignedUniqueChildId, parent, params, localStorage) { + super(compilerAssignedUniqueChildId, parent, localStorage); this.__shopBasket = new ObservedPropertyObject([7, 12, 47, 3], this, "shopBasket"); this.__totalPurchase = new ObservedPropertySimple(0, this, "totalPurchase"); this.__defArray = new ObservedPropertyObject(['c', 'g', 't', 'z'], this, "defArray"); this.__resultTip = new ObservedPropertySimple('', this, "resultTip"); + this.updateWithValueParams(params); this.declareWatch("shopBasket", this.onBasketUpdated); this.declareWatch("defArray", this.onPutItem); - this.updateWithValueParams(params); } updateWithValueParams(params) { if (params.shopBasket !== undefined) { diff --git a/compiler/test/utForPartialUpdate/import/importAllEts.ts b/compiler/test/utForPartialUpdate/import/importAllEts.ts new file mode 100644 index 0000000000000000000000000000000000000000..2375614b56fbb46b66cf690bff0ef882e29c083c --- /dev/null +++ b/compiler/test/utForPartialUpdate/import/importAllEts.ts @@ -0,0 +1,273 @@ +/* + * Copyright (c) 2022 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. + */ + +exports.source = ` +import * as AllComponent from './test/pages/NamespaceComponent' +import TsModule from './test/pages/TsModule' + +@Entry +@Component +struct ImportTest { + @State myState1: any = new TsModule(1).method() + @State myState2: number = 0 + @State myState3: boolean = false + @State myState4: string = 'ImportTest' + + build() { + Column() { + AllComponent.NamespaceComponent1({ + NamespaceComponent1Link1: $myState1, + NamespaceComponent1Link2: $myState2, + NamespaceComponent1Link3: $myState3, + NamespaceComponent1Link4: $myState4, + myVar: 100, + myVar2: 80 + }) + AllComponent.NamespaceComponent1({ + NamespaceComponent1Link1: $myState1, + NamespaceComponent1Link2: $myState2, + NamespaceComponent1Link3: $myState3, + NamespaceComponent1Link4: $myState4, + myVar: 100, + myVar2: 80 + }) + .width(100) + AllComponent.default({ + NamespaceComponent3Link1: $myState1, + NamespaceComponent3Link2: $myState2, + NamespaceComponent3Link3: $myState3, + NamespaceComponent3Link4: $myState4, + myVar: 100, + myVar2: 80 + }) + AllComponent.default({ + NamespaceComponent3Link1: $myState1, + NamespaceComponent3Link2: $myState2, + NamespaceComponent3Link3: $myState3, + NamespaceComponent3Link4: $myState4, + myVar: 100, + myVar2: 80 + }) + .height(200) + } + } +} +` + +exports.expectResult = +`"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const AllComponent = __importStar(require("./test/pages/NamespaceComponent")); +const TsModule_1 = __importDefault(require("./test/pages/TsModule")); +class ImportTest extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.__myState1 = new ObservedPropertyObjectPU(new TsModule_1.default(1).method(), this, "myState1"); + this.__myState2 = new ObservedPropertySimplePU(0, this, "myState2"); + this.__myState3 = new ObservedPropertySimplePU(false, this, "myState3"); + this.__myState4 = new ObservedPropertySimplePU('ImportTest', this, "myState4"); + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + if (params.myState1 !== undefined) { + this.myState1 = params.myState1; + } + if (params.myState2 !== undefined) { + this.myState2 = params.myState2; + } + if (params.myState3 !== undefined) { + this.myState3 = params.myState3; + } + if (params.myState4 !== undefined) { + this.myState4 = params.myState4; + } + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + this.__myState1.purgeDependencyOnElmtId(rmElmtId); + this.__myState2.purgeDependencyOnElmtId(rmElmtId); + this.__myState3.purgeDependencyOnElmtId(rmElmtId); + this.__myState4.purgeDependencyOnElmtId(rmElmtId); + } + aboutToBeDeleted() { + this.__myState1.aboutToBeDeleted(); + this.__myState2.aboutToBeDeleted(); + this.__myState3.aboutToBeDeleted(); + this.__myState4.aboutToBeDeleted(); + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + get myState1() { + return this.__myState1.get(); + } + set myState1(newValue) { + this.__myState1.set(newValue); + } + get myState2() { + return this.__myState2.get(); + } + set myState2(newValue) { + this.__myState2.set(newValue); + } + get myState3() { + return this.__myState3.get(); + } + set myState3(newValue) { + this.__myState3.set(newValue); + } + get myState4() { + return this.__myState4.get(); + } + set myState4(newValue) { + this.__myState4.set(newValue); + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Column.create(); + if (!isInitialRender) { + Column.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + if (isInitialRender) { + ViewPU.create(new AllComponent.NamespaceComponent1(this, { + NamespaceComponent1Link1: this.__myState1, + NamespaceComponent1Link2: this.__myState2, + NamespaceComponent1Link3: this.__myState3, + NamespaceComponent1Link4: this.__myState4, + myVar: 100, + myVar2: 80 + }, undefined, elmtId)); + } + else { + this.updateStateVarsOfChildByElmtId(elmtId, {}); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + } + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + __Common__.create(); + __Common__.width(100); + if (!isInitialRender) { + __Common__.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + if (isInitialRender) { + ViewPU.create(new AllComponent.NamespaceComponent1(this, { + NamespaceComponent1Link1: this.__myState1, + NamespaceComponent1Link2: this.__myState2, + NamespaceComponent1Link3: this.__myState3, + NamespaceComponent1Link4: this.__myState4, + myVar: 100, + myVar2: 80 + }, undefined, elmtId)); + } + else { + this.updateStateVarsOfChildByElmtId(elmtId, {}); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + } + __Common__.pop(); + { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + if (isInitialRender) { + ViewPU.create(new AllComponent.default(this, { + NamespaceComponent3Link1: this.__myState1, + NamespaceComponent3Link2: this.__myState2, + NamespaceComponent3Link3: this.__myState3, + NamespaceComponent3Link4: this.__myState4, + myVar: 100, + myVar2: 80 + }, undefined, elmtId)); + } + else { + this.updateStateVarsOfChildByElmtId(elmtId, {}); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + } + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + __Common__.create(); + __Common__.height(200); + if (!isInitialRender) { + __Common__.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + if (isInitialRender) { + ViewPU.create(new AllComponent.default(this, { + NamespaceComponent3Link1: this.__myState1, + NamespaceComponent3Link2: this.__myState2, + NamespaceComponent3Link3: this.__myState3, + NamespaceComponent3Link4: this.__myState4, + myVar: 100, + myVar2: 80 + }, undefined, elmtId)); + } + else { + this.updateStateVarsOfChildByElmtId(elmtId, {}); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + } + __Common__.pop(); + Column.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +ViewStackProcessor.StartGetAccessRecordingFor(ViewStackProcessor.AllocateNewElmetIdForNextComponent()); +loadDocument(new ImportTest(undefined, {})); +ViewStackProcessor.StopGetAccessRecording(); +` diff --git a/compiler/test/utForPartialUpdate/import/importEts.ts b/compiler/test/utForPartialUpdate/import/importEts.ts new file mode 100644 index 0000000000000000000000000000000000000000..44978135c28c1444ad27cafb291081750c36b348 --- /dev/null +++ b/compiler/test/utForPartialUpdate/import/importEts.ts @@ -0,0 +1,344 @@ +/* + * Copyright (c) 2022 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. + */ + +exports.source = ` +import +LinkComponentDefault, { + LinkComponent as LinkComponent1Ref, + LinkComponent2 as LinkComponent2Ref, + LinkComponent3 +} from './test/pages/LinkComponent' +import DefaultComponent from "./test/pages/DefaultComponent" +import AMDComponentDefault = require('./test/pages/AMDComponent') +import TsModule from './test/pages/TsModule' + +@Entry +@Component +struct ImportTest { + @State myState1: any = new TsModule(1).method() + @State myState2: number = 0 + @State myState3: boolean = false + @State myState4: string = 'ImportTest' + + build() { + Column() { + LinkComponent2Ref({ + LinkComponent2Link1: $myState1, + LinkComponent2Link2: $myState2, + LinkComponent2Link3: $myState3, + LinkComponent2Link4: $myState4, + indexState1: { count: 1 }, + indexState2: 1, + indexState3: true, + indexState4: 'LinkComponent2' + }) + Text('space') + .fontSize(20) + .fontColor(Color.Red) + LinkComponent1Ref({ + LinkComponent1Link1: $myState1, + LinkComponent1Link2: $myState2, + LinkComponent1Link3: $myState3, + LinkComponent1Link4: $myState4, + indexState1: { count: 1 }, + indexState2: 1, + indexState3: true, + indexState4: 'LinkComponent1' + }) + DefaultComponent({ + DefaultComponentLink1: $myState1, + DefaultComponentLink2: $myState2, + DefaultComponentLink3: $myState3, + DefaultComponentLink4: $myState4, + myVar: 100, + myVar2: 100 + }) + LinkComponentDefault({ + LinkComponent3Link1: $myState1, + LinkComponent3Link2: $myState2, + LinkComponent3Link3: $myState3, + LinkComponent3Link4: $myState4, + indexState1: { count: 1 }, + indexState2: 1, + indexState3: true, + indexState4: 'LinkComponent3' + }) + AMDComponentDefault({ + AMDComponentLink1: $myState1, + AMDComponentLink2: $myState2, + AMDComponentLink3: $myState3, + AMDComponentLink4: $myState4, + myVar: 100, + myVar2: 100 + }) + LinkComponent3({ + LinkComponent3Link1: $myState1, + LinkComponent3Link2: $myState2, + LinkComponent3Link3: $myState3, + LinkComponent3Link4: $myState4, + indexState1: { count: 1 }, + indexState2: 1, + indexState3: true, + indexState4: 'LinkComponent1' + }) + } + } +} +` + +exports.expectResult = +`"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const LinkComponent_1 = __importStar(require("./test/pages/LinkComponent")); +const DefaultComponent_1 = __importDefault(require("./test/pages/DefaultComponent")); +const AMDComponentDefault = require("./test/pages/AMDComponent"); +const TsModule_1 = __importDefault(require("./test/pages/TsModule")); +class ImportTest extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.__myState1 = new ObservedPropertyObjectPU(new TsModule_1.default(1).method(), this, "myState1"); + this.__myState2 = new ObservedPropertySimplePU(0, this, "myState2"); + this.__myState3 = new ObservedPropertySimplePU(false, this, "myState3"); + this.__myState4 = new ObservedPropertySimplePU('ImportTest', this, "myState4"); + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + if (params.myState1 !== undefined) { + this.myState1 = params.myState1; + } + if (params.myState2 !== undefined) { + this.myState2 = params.myState2; + } + if (params.myState3 !== undefined) { + this.myState3 = params.myState3; + } + if (params.myState4 !== undefined) { + this.myState4 = params.myState4; + } + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + this.__myState1.purgeDependencyOnElmtId(rmElmtId); + this.__myState2.purgeDependencyOnElmtId(rmElmtId); + this.__myState3.purgeDependencyOnElmtId(rmElmtId); + this.__myState4.purgeDependencyOnElmtId(rmElmtId); + } + aboutToBeDeleted() { + this.__myState1.aboutToBeDeleted(); + this.__myState2.aboutToBeDeleted(); + this.__myState3.aboutToBeDeleted(); + this.__myState4.aboutToBeDeleted(); + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + get myState1() { + return this.__myState1.get(); + } + set myState1(newValue) { + this.__myState1.set(newValue); + } + get myState2() { + return this.__myState2.get(); + } + set myState2(newValue) { + this.__myState2.set(newValue); + } + get myState3() { + return this.__myState3.get(); + } + set myState3(newValue) { + this.__myState3.set(newValue); + } + get myState4() { + return this.__myState4.get(); + } + set myState4(newValue) { + this.__myState4.set(newValue); + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Column.create(); + if (!isInitialRender) { + Column.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + if (isInitialRender) { + ViewPU.create(new LinkComponent_1.LinkComponent2(this, { + LinkComponent2Link1: this.__myState1, + LinkComponent2Link2: this.__myState2, + LinkComponent2Link3: this.__myState3, + LinkComponent2Link4: this.__myState4, + indexState1: { count: 1 }, + indexState2: 1, + indexState3: true, + indexState4: 'LinkComponent2' + }, undefined, elmtId)); + } + else { + this.updateStateVarsOfChildByElmtId(elmtId, {}); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + } + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create('space'); + Text.fontSize(20); + Text.fontColor(Color.Red); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + if (isInitialRender) { + ViewPU.create(new LinkComponent_1.LinkComponent(this, { + LinkComponent1Link1: this.__myState1, + LinkComponent1Link2: this.__myState2, + LinkComponent1Link3: this.__myState3, + LinkComponent1Link4: this.__myState4, + indexState1: { count: 1 }, + indexState2: 1, + indexState3: true, + indexState4: 'LinkComponent1' + }, undefined, elmtId)); + } + else { + this.updateStateVarsOfChildByElmtId(elmtId, {}); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + } + { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + if (isInitialRender) { + ViewPU.create(new DefaultComponent_1.default(this, { + DefaultComponentLink1: this.__myState1, + DefaultComponentLink2: this.__myState2, + DefaultComponentLink3: this.__myState3, + DefaultComponentLink4: this.__myState4, + myVar: 100, + myVar2: 100 + }, undefined, elmtId)); + } + else { + this.updateStateVarsOfChildByElmtId(elmtId, {}); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + } + { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + if (isInitialRender) { + ViewPU.create(new LinkComponent_1.default(this, { + LinkComponent3Link1: this.__myState1, + LinkComponent3Link2: this.__myState2, + LinkComponent3Link3: this.__myState3, + LinkComponent3Link4: this.__myState4, + indexState1: { count: 1 }, + indexState2: 1, + indexState3: true, + indexState4: 'LinkComponent3' + }, undefined, elmtId)); + } + else { + this.updateStateVarsOfChildByElmtId(elmtId, {}); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + } + { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + if (isInitialRender) { + ViewPU.create(new AMDComponentDefault(this, { + AMDComponentLink1: this.__myState1, + AMDComponentLink2: this.__myState2, + AMDComponentLink3: this.__myState3, + AMDComponentLink4: this.__myState4, + myVar: 100, + myVar2: 100 + }, undefined, elmtId)); + } + else { + this.updateStateVarsOfChildByElmtId(elmtId, {}); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + } + { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + if (isInitialRender) { + ViewPU.create(new LinkComponent_1.LinkComponent3(this, { + LinkComponent3Link1: this.__myState1, + LinkComponent3Link2: this.__myState2, + LinkComponent3Link3: this.__myState3, + LinkComponent3Link4: this.__myState4, + indexState1: { count: 1 }, + indexState2: 1, + indexState3: true, + indexState4: 'LinkComponent1' + }, undefined, elmtId)); + } + else { + this.updateStateVarsOfChildByElmtId(elmtId, {}); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + } + Column.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +ViewStackProcessor.StartGetAccessRecordingFor(ViewStackProcessor.AllocateNewElmetIdForNextComponent()); +loadDocument(new ImportTest(undefined, {})); +ViewStackProcessor.StopGetAccessRecording(); +` diff --git a/compiler/test/utForPartialUpdate/import/importExportEts.ts b/compiler/test/utForPartialUpdate/import/importExportEts.ts new file mode 100644 index 0000000000000000000000000000000000000000..0410d7e50c8d66c89e6a89793884aaa62e8aae0b --- /dev/null +++ b/compiler/test/utForPartialUpdate/import/importExportEts.ts @@ -0,0 +1,186 @@ +/* + * Copyright (c) 2022 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. + */ + +exports.source = ` +import { AllStarComponent } from './test/pages/ExportStarComponent' +import TsModule from './test/pages/TsModule' + +@Entry +@Component +struct ImportTest { + @State myState1: any = new TsModule(1).method() + @State myState2: number = 0 + @State myState3: boolean = false + @State myState4: string = 'ImportTest' + + build() { + Column() { + AllStarComponent.ExportComponent({ + ExportComponent1Link1: $myState1, + ExportComponent1Link2: $myState2, + ExportComponent1Link3: $myState3, + ExportComponent1Link4: $myState4, + indexState1: { count: 1 }, + indexState2: 1, + indexState3: true, + indexState4: 'ExportComponent1' + }) + AllStarComponent.default({ + ExportComponent4Link1: $myState1, + ExportComponent4Link2: $myState2, + ExportComponent4Link3: $myState3, + ExportComponent4Link4: $myState4, + indexState1: { count: 1 }, + indexState2: 1, + indexState3: true, + indexState4: 'ExportComponent4' + }) + } + } +} +` + +exports.expectResult = +`"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const ExportStarComponent_1 = require("./test/pages/ExportStarComponent"); +const TsModule_1 = __importDefault(require("./test/pages/TsModule")); +class ImportTest extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.__myState1 = new ObservedPropertyObjectPU(new TsModule_1.default(1).method(), this, "myState1"); + this.__myState2 = new ObservedPropertySimplePU(0, this, "myState2"); + this.__myState3 = new ObservedPropertySimplePU(false, this, "myState3"); + this.__myState4 = new ObservedPropertySimplePU('ImportTest', this, "myState4"); + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + if (params.myState1 !== undefined) { + this.myState1 = params.myState1; + } + if (params.myState2 !== undefined) { + this.myState2 = params.myState2; + } + if (params.myState3 !== undefined) { + this.myState3 = params.myState3; + } + if (params.myState4 !== undefined) { + this.myState4 = params.myState4; + } + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + this.__myState1.purgeDependencyOnElmtId(rmElmtId); + this.__myState2.purgeDependencyOnElmtId(rmElmtId); + this.__myState3.purgeDependencyOnElmtId(rmElmtId); + this.__myState4.purgeDependencyOnElmtId(rmElmtId); + } + aboutToBeDeleted() { + this.__myState1.aboutToBeDeleted(); + this.__myState2.aboutToBeDeleted(); + this.__myState3.aboutToBeDeleted(); + this.__myState4.aboutToBeDeleted(); + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + get myState1() { + return this.__myState1.get(); + } + set myState1(newValue) { + this.__myState1.set(newValue); + } + get myState2() { + return this.__myState2.get(); + } + set myState2(newValue) { + this.__myState2.set(newValue); + } + get myState3() { + return this.__myState3.get(); + } + set myState3(newValue) { + this.__myState3.set(newValue); + } + get myState4() { + return this.__myState4.get(); + } + set myState4(newValue) { + this.__myState4.set(newValue); + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Column.create(); + if (!isInitialRender) { + Column.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + if (isInitialRender) { + ViewPU.create(new ExportStarComponent_1.AllStarComponent.ExportComponent(this, { + ExportComponent1Link1: this.__myState1, + ExportComponent1Link2: this.__myState2, + ExportComponent1Link3: this.__myState3, + ExportComponent1Link4: this.__myState4, + indexState1: { count: 1 }, + indexState2: 1, + indexState3: true, + indexState4: 'ExportComponent1' + }, undefined, elmtId)); + } + else { + this.updateStateVarsOfChildByElmtId(elmtId, {}); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + } + { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + if (isInitialRender) { + ViewPU.create(new ExportStarComponent_1.AllStarComponent.default(this, { + ExportComponent4Link1: this.__myState1, + ExportComponent4Link2: this.__myState2, + ExportComponent4Link3: this.__myState3, + ExportComponent4Link4: this.__myState4, + indexState1: { count: 1 }, + indexState2: 1, + indexState3: true, + indexState4: 'ExportComponent4' + }, undefined, elmtId)); + } + else { + this.updateStateVarsOfChildByElmtId(elmtId, {}); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + } + Column.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +ViewStackProcessor.StartGetAccessRecordingFor(ViewStackProcessor.AllocateNewElmetIdForNextComponent()); +loadDocument(new ImportTest(undefined, {})); +ViewStackProcessor.StopGetAccessRecording(); +` diff --git a/compiler/test/utForPartialUpdate/import/importExportNest.ts b/compiler/test/utForPartialUpdate/import/importExportNest.ts new file mode 100644 index 0000000000000000000000000000000000000000..bf28f430bb593b5326189f3431426608163406ea --- /dev/null +++ b/compiler/test/utForPartialUpdate/import/importExportNest.ts @@ -0,0 +1,274 @@ +/* + * Copyright (c) 2022 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. + */ + +exports.source = ` +import { tExtend, tStyles, DivideTest, Base } from './test/pages/ImportNestAll'; + +@Entry +@Component +struct ImportTest { + @State testText1: string = 'Hello' + @State testText2: string = 'World' + @State testText3: string = 'Test' + @State testText4: string = 'Component' + + @State testState1: string = 'Base' + @State testState2: number = 0 + @State testState3: object = { name: 'Base' } + @State testState4: number = 3 + @State testState5: number = 10 + + build() { + Column() { + Text(this.testText1) + .fontSize(50) + tExtend(20) + Text(this.testText2) + tStyles() + Button(this.testText3) + Text(this.testText4) + .fontSize(50) + + Base({ + testStr: $testState1, + testNum: $testState2, + testObj: $testState3 + }) + DivideTest({ + testNum1: $testState4, + testNum2: $testState5 + }) + } + } +} +` + +exports.expectResult = +`"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const ImportNestAll_1 = require("./test/pages/ImportNestAll"); +class ImportTest extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.__testText1 = new ObservedPropertySimplePU('Hello', this, "testText1"); + this.__testText2 = new ObservedPropertySimplePU('World', this, "testText2"); + this.__testText3 = new ObservedPropertySimplePU('Test', this, "testText3"); + this.__testText4 = new ObservedPropertySimplePU('Component', this, "testText4"); + this.__testState1 = new ObservedPropertySimplePU('Base', this, "testState1"); + this.__testState2 = new ObservedPropertySimplePU(0, this, "testState2"); + this.__testState3 = new ObservedPropertyObjectPU({ name: 'Base' }, this, "testState3"); + this.__testState4 = new ObservedPropertySimplePU(3, this, "testState4"); + this.__testState5 = new ObservedPropertySimplePU(10, this, "testState5"); + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + if (params.testText1 !== undefined) { + this.testText1 = params.testText1; + } + if (params.testText2 !== undefined) { + this.testText2 = params.testText2; + } + if (params.testText3 !== undefined) { + this.testText3 = params.testText3; + } + if (params.testText4 !== undefined) { + this.testText4 = params.testText4; + } + if (params.testState1 !== undefined) { + this.testState1 = params.testState1; + } + if (params.testState2 !== undefined) { + this.testState2 = params.testState2; + } + if (params.testState3 !== undefined) { + this.testState3 = params.testState3; + } + if (params.testState4 !== undefined) { + this.testState4 = params.testState4; + } + if (params.testState5 !== undefined) { + this.testState5 = params.testState5; + } + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + this.__testText1.purgeDependencyOnElmtId(rmElmtId); + this.__testText2.purgeDependencyOnElmtId(rmElmtId); + this.__testText3.purgeDependencyOnElmtId(rmElmtId); + this.__testText4.purgeDependencyOnElmtId(rmElmtId); + this.__testState1.purgeDependencyOnElmtId(rmElmtId); + this.__testState2.purgeDependencyOnElmtId(rmElmtId); + this.__testState3.purgeDependencyOnElmtId(rmElmtId); + this.__testState4.purgeDependencyOnElmtId(rmElmtId); + this.__testState5.purgeDependencyOnElmtId(rmElmtId); + } + aboutToBeDeleted() { + this.__testText1.aboutToBeDeleted(); + this.__testText2.aboutToBeDeleted(); + this.__testText3.aboutToBeDeleted(); + this.__testText4.aboutToBeDeleted(); + this.__testState1.aboutToBeDeleted(); + this.__testState2.aboutToBeDeleted(); + this.__testState3.aboutToBeDeleted(); + this.__testState4.aboutToBeDeleted(); + this.__testState5.aboutToBeDeleted(); + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + get testText1() { + return this.__testText1.get(); + } + set testText1(newValue) { + this.__testText1.set(newValue); + } + get testText2() { + return this.__testText2.get(); + } + set testText2(newValue) { + this.__testText2.set(newValue); + } + get testText3() { + return this.__testText3.get(); + } + set testText3(newValue) { + this.__testText3.set(newValue); + } + get testText4() { + return this.__testText4.get(); + } + set testText4(newValue) { + this.__testText4.set(newValue); + } + get testState1() { + return this.__testState1.get(); + } + set testState1(newValue) { + this.__testState1.set(newValue); + } + get testState2() { + return this.__testState2.get(); + } + set testState2(newValue) { + this.__testState2.set(newValue); + } + get testState3() { + return this.__testState3.get(); + } + set testState3(newValue) { + this.__testState3.set(newValue); + } + get testState4() { + return this.__testState4.get(); + } + set testState4(newValue) { + this.__testState4.set(newValue); + } + get testState5() { + return this.__testState5.get(); + } + set testState5(newValue) { + this.__testState5.set(newValue); + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Column.create(); + if (!isInitialRender) { + Column.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create(this.testText1); + Text.fontSize(50); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + ImportNestAll_1.tExtend(20, this); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create(this.testText2); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + ImportNestAll_1.tStyles(this); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Button.createWithLabel(this.testText3); + if (!isInitialRender) { + Button.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Button.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create(this.testText4); + Text.fontSize(50); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + if (isInitialRender) { + ViewPU.create(new ImportNestAll_1.Base(this, { + testStr: this.__testState1, + testNum: this.__testState2, + testObj: this.__testState3 + }, undefined, elmtId)); + } + else { + this.updateStateVarsOfChildByElmtId(elmtId, {}); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + } + { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + if (isInitialRender) { + ViewPU.create(new ImportNestAll_1.DivideTest(this, { + testNum1: this.__testState4, + testNum2: this.__testState5 + }, undefined, elmtId)); + } + else { + this.updateStateVarsOfChildByElmtId(elmtId, {}); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + } + Column.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +ViewStackProcessor.StartGetAccessRecordingFor(ViewStackProcessor.AllocateNewElmetIdForNextComponent()); +loadDocument(new ImportTest(undefined, {})); +ViewStackProcessor.StopGetAccessRecording(); +` diff --git a/compiler/test/utForPartialUpdate/import/importTs.ts b/compiler/test/utForPartialUpdate/import/importTs.ts new file mode 100644 index 0000000000000000000000000000000000000000..600b2d5551f2823eb40441334398c39b1a8e8c77 --- /dev/null +++ b/compiler/test/utForPartialUpdate/import/importTs.ts @@ -0,0 +1,186 @@ +/* + * Copyright (c) 2022 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. + */ + +exports.source = ` +import { AllStarComponent } from './test/pages/ExportStarComponent' +import TsModule from './test/pages/TsModule' + +@Entry +@Component +struct ImportTest { + @State myState1: any = new TsModule(1).method(); + @State myState2: number = 0 + @State myState3: boolean = false + @State myState4: string = 'ImportTest' + + build() { + Column() { + AllStarComponent.ExportComponent({ + ExportComponent1Link1: $myState1, + ExportComponent1Link2: $myState2, + ExportComponent1Link3: $myState3, + ExportComponent1Link4: $myState4, + indexState1: { count: 1 }, + indexState2: 1, + indexState3: true, + indexState4: 'ExportComponent1' + }) + AllStarComponent.default({ + ExportComponent4Link1: $myState1, + ExportComponent4Link2: $myState2, + ExportComponent4Link3: $myState3, + ExportComponent4Link4: $myState4, + indexState1: { count: 1 }, + indexState2: 1, + indexState3: true, + indexState4: 'ExportComponent4' + }) + } + } +} +` + +exports.expectResult = +`"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const ExportStarComponent_1 = require("./test/pages/ExportStarComponent"); +const TsModule_1 = __importDefault(require("./test/pages/TsModule")); +class ImportTest extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.__myState1 = new ObservedPropertyObjectPU(new TsModule_1.default(1).method(), this, "myState1"); + this.__myState2 = new ObservedPropertySimplePU(0, this, "myState2"); + this.__myState3 = new ObservedPropertySimplePU(false, this, "myState3"); + this.__myState4 = new ObservedPropertySimplePU('ImportTest', this, "myState4"); + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + if (params.myState1 !== undefined) { + this.myState1 = params.myState1; + } + if (params.myState2 !== undefined) { + this.myState2 = params.myState2; + } + if (params.myState3 !== undefined) { + this.myState3 = params.myState3; + } + if (params.myState4 !== undefined) { + this.myState4 = params.myState4; + } + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + this.__myState1.purgeDependencyOnElmtId(rmElmtId); + this.__myState2.purgeDependencyOnElmtId(rmElmtId); + this.__myState3.purgeDependencyOnElmtId(rmElmtId); + this.__myState4.purgeDependencyOnElmtId(rmElmtId); + } + aboutToBeDeleted() { + this.__myState1.aboutToBeDeleted(); + this.__myState2.aboutToBeDeleted(); + this.__myState3.aboutToBeDeleted(); + this.__myState4.aboutToBeDeleted(); + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + get myState1() { + return this.__myState1.get(); + } + set myState1(newValue) { + this.__myState1.set(newValue); + } + get myState2() { + return this.__myState2.get(); + } + set myState2(newValue) { + this.__myState2.set(newValue); + } + get myState3() { + return this.__myState3.get(); + } + set myState3(newValue) { + this.__myState3.set(newValue); + } + get myState4() { + return this.__myState4.get(); + } + set myState4(newValue) { + this.__myState4.set(newValue); + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Column.create(); + if (!isInitialRender) { + Column.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + if (isInitialRender) { + ViewPU.create(new ExportStarComponent_1.AllStarComponent.ExportComponent(this, { + ExportComponent1Link1: this.__myState1, + ExportComponent1Link2: this.__myState2, + ExportComponent1Link3: this.__myState3, + ExportComponent1Link4: this.__myState4, + indexState1: { count: 1 }, + indexState2: 1, + indexState3: true, + indexState4: 'ExportComponent1' + }, undefined, elmtId)); + } + else { + this.updateStateVarsOfChildByElmtId(elmtId, {}); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + } + { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + if (isInitialRender) { + ViewPU.create(new ExportStarComponent_1.AllStarComponent.default(this, { + ExportComponent4Link1: this.__myState1, + ExportComponent4Link2: this.__myState2, + ExportComponent4Link3: this.__myState3, + ExportComponent4Link4: this.__myState4, + indexState1: { count: 1 }, + indexState2: 1, + indexState3: true, + indexState4: 'ExportComponent4' + }, undefined, elmtId)); + } + else { + this.updateStateVarsOfChildByElmtId(elmtId, {}); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + } + Column.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +ViewStackProcessor.StartGetAccessRecordingFor(ViewStackProcessor.AllocateNewElmetIdForNextComponent()); +loadDocument(new ImportTest(undefined, {})); +ViewStackProcessor.StopGetAccessRecording(); +` diff --git a/compiler/test/utForPartialUpdate/inner_component_transform/$$_component/$$_component.ts b/compiler/test/utForPartialUpdate/inner_component_transform/$$_component/$$_component.ts new file mode 100644 index 0000000000000000000000000000000000000000..73a20b7de5d370a1dc91ad25862b9f79f48ef620 --- /dev/null +++ b/compiler/test/utForPartialUpdate/inner_component_transform/$$_component/$$_component.ts @@ -0,0 +1,295 @@ +/* + * Copyright (c) 2022 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. + */ + +exports.source = ` +const value5: boolean[] = [true, false] +let value6: {item1: boolean} = {item1: true} +let isCountDown: boolean = false + +@Entry +@Component +struct HomeComponent { + private value1: string = "hello world 1" + private value2: string = "hello world 2" + private value3: string = "hello world 3" + private value4: boolean = false + private count: number = 1000; + myTimeController: TextTimerController = new TextTimerController(); + @State format: string = "hh:mm:ss:ms" + + build() { + Column() { + Row() { + Text(this.value1) + Radio({value: "Radio", group: "1"}) + .checked($$this.value4) + } + Row() { + Button() { + Text(this.value1) + .bindPopup($$value5[0], {message: "This is $$ for Array"}) + } + .bindPopup($$this.value4, {message: "This is $$ for regular"}) + .width(100) + .height(20) + Text(this.value2) + .fontSize(100) + .bindPopup($$value6.item1, {message: "This is $$ for Obj"}) + Text(this.value3) + Radio({value: "Radio", group: "1"}) + .checked($$value5[0]) + } + .width(20) + Row(){ + TextTimer({controller: this.myTimeController, isCountDown: $$isCountDown, count: $$this.count}) + .format($$this.format) + Button("start") + .onClick(()=>{ + this.myTimeController.start(); + }) + Button("pause") + .onClick(()=>{ + this.myTimeController.pause(); + }) + Button("reset") + .onClick(()=>{ + this.myTimeController.reset(); + }) + } + } + .height(500) + } +} +` + +exports.expectResult = +`"use strict"; +const value5 = [true, false]; +let value6 = { item1: true }; +let isCountDown = false; +class HomeComponent extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.value1 = "hello world 1"; + this.value2 = "hello world 2"; + this.value3 = "hello world 3"; + this.value4 = false; + this.count = 1000; + this.myTimeController = new TextTimerController(); + this.__format = new ObservedPropertySimplePU("hh:mm:ss:ms", this, "format"); + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + if (params.value1 !== undefined) { + this.value1 = params.value1; + } + if (params.value2 !== undefined) { + this.value2 = params.value2; + } + if (params.value3 !== undefined) { + this.value3 = params.value3; + } + if (params.value4 !== undefined) { + this.value4 = params.value4; + } + if (params.count !== undefined) { + this.count = params.count; + } + if (params.myTimeController !== undefined) { + this.myTimeController = params.myTimeController; + } + if (params.format !== undefined) { + this.format = params.format; + } + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + this.__format.purgeDependencyOnElmtId(rmElmtId); + } + aboutToBeDeleted() { + this.__format.aboutToBeDeleted(); + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + get format() { + return this.__format.get(); + } + set format(newValue) { + this.__format.set(newValue); + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Column.create(); + Column.height(500); + if (!isInitialRender) { + Column.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Row.create(); + if (!isInitialRender) { + Row.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create(this.value1); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Radio.create({ value: "Radio", group: "1" }); + Radio.checked(this.value4, newValue => { this.value4 = newValue; }); + if (!isInitialRender) { + Radio.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Row.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Row.create(); + Row.width(20); + if (!isInitialRender) { + Row.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Button.createWithChild(); + Button.bindPopup({ value: this.value4, changeEvent: newValue => { this.value4 = newValue; } }, { message: "This is $$ for regular" }); + Button.width(100); + Button.height(20); + if (!isInitialRender) { + Button.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create(this.value1); + Text.bindPopup({ value: value5[0], changeEvent: newValue => { value5[0] = newValue; } }, { message: "This is $$ for Array" }); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + Button.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create(this.value2); + Text.fontSize(100); + Text.bindPopup({ value: value6.item1, changeEvent: newValue => { value6.item1 = newValue; } }, { message: "This is $$ for Obj" }); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create(this.value3); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Radio.create({ value: "Radio", group: "1" }); + Radio.checked(value5[0], newValue => { value5[0] = newValue; }); + if (!isInitialRender) { + Radio.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Row.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Row.create(); + if (!isInitialRender) { + Row.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + TextTimer.create({ controller: this.myTimeController, isCountDown: { value: isCountDown, changeEvent: newValue => { isCountDown = newValue; } }, count: { value: this.count, changeEvent: newValue => { this.count = newValue; } } }); + TextTimer.format(this.format, newValue => { this.format = newValue; }); + if (!isInitialRender) { + TextTimer.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + TextTimer.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Button.createWithLabel("start"); + Button.onClick(() => { + this.myTimeController.start(); + }); + if (!isInitialRender) { + Button.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Button.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Button.createWithLabel("pause"); + Button.onClick(() => { + this.myTimeController.pause(); + }); + if (!isInitialRender) { + Button.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Button.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Button.createWithLabel("reset"); + Button.onClick(() => { + this.myTimeController.reset(); + }); + if (!isInitialRender) { + Button.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Button.pop(); + Row.pop(); + Column.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +ViewStackProcessor.StartGetAccessRecordingFor(ViewStackProcessor.AllocateNewElmetIdForNextComponent()); +loadDocument(new HomeComponent(undefined, {})); +ViewStackProcessor.StopGetAccessRecording(); +` diff --git a/compiler/test/utForPartialUpdate/inner_component_transform/custom_component/custom_component.ts b/compiler/test/utForPartialUpdate/inner_component_transform/custom_component/custom_component.ts index 598d2a48ad3cb855e4bbc71da9d8f749fcbee950..3a36ebb39888aee7abf32425a0846409527f1b96 100644 --- a/compiler/test/utForPartialUpdate/inner_component_transform/custom_component/custom_component.ts +++ b/compiler/test/utForPartialUpdate/inner_component_transform/custom_component/custom_component.ts @@ -48,12 +48,14 @@ struct Banner { exports.expectResult = `"use strict"; class MyComponent extends ViewPU { - constructor(parent, params, __localStorage) { - super(parent, __localStorage); + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); this.setInitiallyProvidedValue(params); } setInitiallyProvidedValue(params) { } + updateStateVars(params) { + } purgeVariableDependenciesOnElmtId(rmElmtId) { } aboutToBeDeleted() { @@ -70,53 +72,117 @@ class MyComponent extends ViewPU { ViewStackProcessor.StopGetAccessRecording(); }); { - const elmtId = ViewStackProcessor.AllocateNewElmetIdForNextComponent(); - ViewStackProcessor.StartGetAccessRecordingFor(elmtId); - ViewPU.create(new Banner(this, {})); - ViewStackProcessor.StopGetAccessRecording(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + if (isInitialRender) { + ViewPU.create(new Banner(this, {}, undefined, elmtId)); + } + else { + this.updateStateVarsOfChildByElmtId(elmtId, {}); + } + ViewStackProcessor.StopGetAccessRecording(); + }); } - __Common__.create(); - __Common__.width(100); - { - const elmtId = ViewStackProcessor.AllocateNewElmetIdForNextComponent(); + this.observeComponentCreation((elmtId, isInitialRender) => { ViewStackProcessor.StartGetAccessRecordingFor(elmtId); - ViewPU.create(new Banner(this, {})); + __Common__.create(); + __Common__.width(100); + if (!isInitialRender) { + __Common__.pop(); + } ViewStackProcessor.StopGetAccessRecording(); + }); + { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + if (isInitialRender) { + ViewPU.create(new Banner(this, {}, undefined, elmtId)); + } + else { + this.updateStateVarsOfChildByElmtId(elmtId, {}); + } + ViewStackProcessor.StopGetAccessRecording(); + }); } __Common__.pop(); - __Common__.create(); - __Common__.width(100); - __Common__.height(200); - { - const elmtId = ViewStackProcessor.AllocateNewElmetIdForNextComponent(); + this.observeComponentCreation((elmtId, isInitialRender) => { ViewStackProcessor.StartGetAccessRecordingFor(elmtId); - ViewPU.create(new Banner(this, {})); + __Common__.create(); + __Common__.width(100); + __Common__.height(200); + if (!isInitialRender) { + __Common__.pop(); + } ViewStackProcessor.StopGetAccessRecording(); + }); + { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + if (isInitialRender) { + ViewPU.create(new Banner(this, {}, undefined, elmtId)); + } + else { + this.updateStateVarsOfChildByElmtId(elmtId, {}); + } + ViewStackProcessor.StopGetAccessRecording(); + }); } __Common__.pop(); { - const elmtId = ViewStackProcessor.AllocateNewElmetIdForNextComponent(); - ViewStackProcessor.StartGetAccessRecordingFor(elmtId); - ViewPU.create(new Banner(this, { value: "Hello" })); - ViewStackProcessor.StopGetAccessRecording(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + if (isInitialRender) { + ViewPU.create(new Banner(this, { value: "Hello" }, undefined, elmtId)); + } + else { + this.updateStateVarsOfChildByElmtId(elmtId, {}); + } + ViewStackProcessor.StopGetAccessRecording(); + }); } - __Common__.create(); - __Common__.width(100); - { - const elmtId = ViewStackProcessor.AllocateNewElmetIdForNextComponent(); + this.observeComponentCreation((elmtId, isInitialRender) => { ViewStackProcessor.StartGetAccessRecordingFor(elmtId); - ViewPU.create(new Banner(this, { value: "Hello" })); + __Common__.create(); + __Common__.width(100); + if (!isInitialRender) { + __Common__.pop(); + } ViewStackProcessor.StopGetAccessRecording(); + }); + { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + if (isInitialRender) { + ViewPU.create(new Banner(this, { value: "Hello" }, undefined, elmtId)); + } + else { + this.updateStateVarsOfChildByElmtId(elmtId, {}); + } + ViewStackProcessor.StopGetAccessRecording(); + }); } __Common__.pop(); - __Common__.create(); - __Common__.width(100); - __Common__.height(200); - { - const elmtId = ViewStackProcessor.AllocateNewElmetIdForNextComponent(); + this.observeComponentCreation((elmtId, isInitialRender) => { ViewStackProcessor.StartGetAccessRecordingFor(elmtId); - ViewPU.create(new Banner(this, { value: "Hello" })); + __Common__.create(); + __Common__.width(100); + __Common__.height(200); + if (!isInitialRender) { + __Common__.pop(); + } ViewStackProcessor.StopGetAccessRecording(); + }); + { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + if (isInitialRender) { + ViewPU.create(new Banner(this, { value: "Hello" }, undefined, elmtId)); + } + else { + this.updateStateVarsOfChildByElmtId(elmtId, {}); + } + ViewStackProcessor.StopGetAccessRecording(); + }); } __Common__.pop(); Column.pop(); @@ -126,8 +192,8 @@ class MyComponent extends ViewPU { } } class Banner extends ViewPU { - constructor(parent, params, __localStorage) { - super(parent, __localStorage); + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); this.value = "Hello"; this.setInitiallyProvidedValue(params); } @@ -136,10 +202,11 @@ class Banner extends ViewPU { this.value = params.value; } } + updateStateVars(params) { + } purgeVariableDependenciesOnElmtId(rmElmtId) { } aboutToBeDeleted() { - this.value = undefined; SubscriberManager.Get().delete(this.id__()); this.aboutToBeDeletedInternal(); } diff --git a/compiler/test/utForPartialUpdate/inner_component_transform/gesture_component/longPressGesture.ts b/compiler/test/utForPartialUpdate/inner_component_transform/gesture_component/longPressGesture.ts new file mode 100644 index 0000000000000000000000000000000000000000..967d429dedf89c905674e749535bb691f576dedc --- /dev/null +++ b/compiler/test/utForPartialUpdate/inner_component_transform/gesture_component/longPressGesture.ts @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2022 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. + */ + +exports.source = ` +@Entry +@Component +struct LongPressGestureExample { + @State count: number = 0 + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }) { + Text('LongPress onAction:' + this.count) + } + .height(200).width(300).padding(60).border({ width:1 }).margin(30) + .gesture( + LongPressGesture({ repeat: true }) + .onAction((event: GestureEvent) => { + if (event.repeat) { this.count++ } + }) + .onActionEnd(() => { + this.count = 0 + }) + ) + } +}` + +exports.expectResult = +`"use strict"; +class LongPressGestureExample extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.__count = new ObservedPropertySimplePU(0, this, "count"); + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + if (params.count !== undefined) { + this.count = params.count; + } + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + this.__count.purgeDependencyOnElmtId(rmElmtId); + } + aboutToBeDeleted() { + this.__count.aboutToBeDeleted(); + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + get count() { + return this.__count.get(); + } + set count(newValue) { + this.__count.set(newValue); + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Flex.create({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }); + Flex.height(200); + Flex.width(300); + Flex.padding(60); + Flex.border({ width: 1 }); + Flex.margin(30); + Gesture.create(GesturePriority.Low); + LongPressGesture.create({ repeat: true }); + LongPressGesture.onAction((event) => { + if (event.repeat) { + this.count++; + } + }); + LongPressGesture.onActionEnd(() => { + this.count = 0; + }); + LongPressGesture.pop(); + Gesture.pop(); + if (!isInitialRender) { + Flex.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create('LongPress onAction:' + this.count); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + Flex.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +ViewStackProcessor.StartGetAccessRecordingFor(ViewStackProcessor.AllocateNewElmetIdForNextComponent()); +loadDocument(new LongPressGestureExample(undefined, {})); +ViewStackProcessor.StopGetAccessRecording(); +` diff --git a/compiler/test/utForPartialUpdate/inner_component_transform/gesture_component/panGestrue.ts b/compiler/test/utForPartialUpdate/inner_component_transform/gesture_component/panGestrue.ts new file mode 100644 index 0000000000000000000000000000000000000000..771e3899a1df77144426f8527bafa37d2ae3a616 --- /dev/null +++ b/compiler/test/utForPartialUpdate/inner_component_transform/gesture_component/panGestrue.ts @@ -0,0 +1,144 @@ +/* + * Copyright (c) 2022 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. + */ + +exports.source = ` +@Entry +@Component +struct PanGestureExample { + @State offsetX: number = 0 + @State offsetY: number = 0 + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }) { + Text('PanGesture offset X: ' + this.offsetX) + Text('PanGesture offset Y: ' + this.offsetY) + } + .height(100).width(200).padding(20).border({ width: 1 }).margin(80) + .translate({ x: this.offsetX, y: this.offsetY, z: 5 }) + .gesture( + PanGesture({}) + .onActionStart((event: GestureEvent) => { + console.info('Pan start') + }) + .onActionUpdate((event: GestureEvent) => { + this.offsetX = event.offsetX + this.offsetY = event.offsetY + }) + .onActionEnd(() => { + console.info('Pan end') + }) + ) + } +} +` + +exports.expectResult = +`"use strict"; +class PanGestureExample extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.__offsetX = new ObservedPropertySimplePU(0, this, "offsetX"); + this.__offsetY = new ObservedPropertySimplePU(0, this, "offsetY"); + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + if (params.offsetX !== undefined) { + this.offsetX = params.offsetX; + } + if (params.offsetY !== undefined) { + this.offsetY = params.offsetY; + } + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + this.__offsetX.purgeDependencyOnElmtId(rmElmtId); + this.__offsetY.purgeDependencyOnElmtId(rmElmtId); + } + aboutToBeDeleted() { + this.__offsetX.aboutToBeDeleted(); + this.__offsetY.aboutToBeDeleted(); + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + get offsetX() { + return this.__offsetX.get(); + } + set offsetX(newValue) { + this.__offsetX.set(newValue); + } + get offsetY() { + return this.__offsetY.get(); + } + set offsetY(newValue) { + this.__offsetY.set(newValue); + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Flex.create({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }); + Flex.height(100); + Flex.width(200); + Flex.padding(20); + Flex.border({ width: 1 }); + Flex.margin(80); + Flex.translate({ x: this.offsetX, y: this.offsetY, z: 5 }); + Gesture.create(GesturePriority.Low); + PanGesture.create({}); + PanGesture.onActionStart((event) => { + console.info('Pan start'); + }); + PanGesture.onActionUpdate((event) => { + this.offsetX = event.offsetX; + this.offsetY = event.offsetY; + }); + PanGesture.onActionEnd(() => { + console.info('Pan end'); + }); + PanGesture.pop(); + Gesture.pop(); + if (!isInitialRender) { + Flex.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create('PanGesture offset X: ' + this.offsetX); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create('PanGesture offset Y: ' + this.offsetY); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + Flex.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +ViewStackProcessor.StartGetAccessRecordingFor(ViewStackProcessor.AllocateNewElmetIdForNextComponent()); +loadDocument(new PanGestureExample(undefined, {})); +ViewStackProcessor.StopGetAccessRecording(); +` diff --git a/compiler/test/utForPartialUpdate/inner_component_transform/gesture_component/pinchGesture.ts b/compiler/test/utForPartialUpdate/inner_component_transform/gesture_component/pinchGesture.ts new file mode 100644 index 0000000000000000000000000000000000000000..63a7941d04efcf7345562e1d42d59bd928cb1998 --- /dev/null +++ b/compiler/test/utForPartialUpdate/inner_component_transform/gesture_component/pinchGesture.ts @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2022 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. + */ + +exports.source = ` +@Entry +@Component +struct PinchGestureExample { + @State scale2: number = 1 + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }) { + Text('PinchGesture scale:' + this.scale2) + } + .height(100).width(200).padding(20).border({ width: 1 }).margin(80) + .scale({ x: this.scale2, y: this.scale2, z: this.scale2 }) + .gesture( + PinchGesture() + .onActionStart((event: GestureEvent) => { + console.info('Pinch start') + }) + .onActionUpdate((event: GestureEvent) => { + this.scale2 = event.scale + }) + .onActionEnd(() => { + console.info('Pinch end') + }) + ) + } +}` + +exports.expectResult = +`"use strict"; +class PinchGestureExample extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.__scale2 = new ObservedPropertySimplePU(1, this, "scale2"); + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + if (params.scale2 !== undefined) { + this.scale2 = params.scale2; + } + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + this.__scale2.purgeDependencyOnElmtId(rmElmtId); + } + aboutToBeDeleted() { + this.__scale2.aboutToBeDeleted(); + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + get scale2() { + return this.__scale2.get(); + } + set scale2(newValue) { + this.__scale2.set(newValue); + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Flex.create({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }); + Flex.height(100); + Flex.width(200); + Flex.padding(20); + Flex.border({ width: 1 }); + Flex.margin(80); + Flex.scale({ x: this.scale2, y: this.scale2, z: this.scale2 }); + Gesture.create(GesturePriority.Low); + PinchGesture.create(); + PinchGesture.onActionStart((event) => { + console.info('Pinch start'); + }); + PinchGesture.onActionUpdate((event) => { + this.scale2 = event.scale; + }); + PinchGesture.onActionEnd(() => { + console.info('Pinch end'); + }); + PinchGesture.pop(); + Gesture.pop(); + if (!isInitialRender) { + Flex.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create('PinchGesture scale:' + this.scale2); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + Flex.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +ViewStackProcessor.StartGetAccessRecordingFor(ViewStackProcessor.AllocateNewElmetIdForNextComponent()); +loadDocument(new PinchGestureExample(undefined, {})); +ViewStackProcessor.StopGetAccessRecording(); +` diff --git a/compiler/test/utForPartialUpdate/inner_component_transform/gesture_component/rotationGesture.ts b/compiler/test/utForPartialUpdate/inner_component_transform/gesture_component/rotationGesture.ts new file mode 100644 index 0000000000000000000000000000000000000000..0f5a982da4a7e911900053e9287c287bdd052047 --- /dev/null +++ b/compiler/test/utForPartialUpdate/inner_component_transform/gesture_component/rotationGesture.ts @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2022 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. + */ + +exports.source = ` +@Entry +@Component +struct RotationGestureExample { + @State angle: number = 0 + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }) { + Text('RotationGesture angle:' + this.angle) + } + .height(100).width(200).padding(20).border({ width:1 }) + .margin(80).rotate({ x:1, y:2, z:3, angle: this.angle }) + .gesture( + RotationGesture() + .onActionStart((event: GestureEvent) => { + console.log('Rotation start') + }) + .onActionUpdate((event: GestureEvent) => { + this.angle = event.angle + }) + .onActionEnd(() => { + console.log('Rotation end') + }) + ) + } +}` + +exports.expectResult = +`"use strict"; +class RotationGestureExample extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.__angle = new ObservedPropertySimplePU(0, this, "angle"); + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + if (params.angle !== undefined) { + this.angle = params.angle; + } + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + this.__angle.purgeDependencyOnElmtId(rmElmtId); + } + aboutToBeDeleted() { + this.__angle.aboutToBeDeleted(); + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + get angle() { + return this.__angle.get(); + } + set angle(newValue) { + this.__angle.set(newValue); + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Flex.create({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }); + Flex.height(100); + Flex.width(200); + Flex.padding(20); + Flex.border({ width: 1 }); + Flex.margin(80); + Flex.rotate({ x: 1, y: 2, z: 3, angle: this.angle }); + Gesture.create(GesturePriority.Low); + RotationGesture.create(); + RotationGesture.onActionStart((event) => { + console.log('Rotation start'); + }); + RotationGesture.onActionUpdate((event) => { + this.angle = event.angle; + }); + RotationGesture.onActionEnd(() => { + console.log('Rotation end'); + }); + RotationGesture.pop(); + Gesture.pop(); + if (!isInitialRender) { + Flex.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create('RotationGesture angle:' + this.angle); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + Flex.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +ViewStackProcessor.StartGetAccessRecordingFor(ViewStackProcessor.AllocateNewElmetIdForNextComponent()); +loadDocument(new RotationGestureExample(undefined, {})); +ViewStackProcessor.StopGetAccessRecording(); +` diff --git a/compiler/test/utForPartialUpdate/inner_component_transform/gesture_component/swipeGesture.ts b/compiler/test/utForPartialUpdate/inner_component_transform/gesture_component/swipeGesture.ts new file mode 100644 index 0000000000000000000000000000000000000000..5e661bd0e2dfe5a1c793eb1b40d81781eb41858b --- /dev/null +++ b/compiler/test/utForPartialUpdate/inner_component_transform/gesture_component/swipeGesture.ts @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2022 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. + */ + +exports.source = ` +@Entry +@Component +struct SwipeGestureExample { + @State rotateAngle : number = 0 + @State speed : number = 1 + + build() { + Column() { + Text("SwipGesture speed : " + this.speed) + Text("SwipGesture angle : " + this.rotateAngle) + } + .border({width:2}) + .width(260).height(260) + .rotate({x: 0, y: 0, z: 1, angle: this.rotateAngle}) + .gesture( + SwipeGesture({fingers: 1, direction:SwipeDirection.Vertical}) + .onAction((event: GestureEvent) => { + this.speed = event.speed + this.rotateAngle = event.angle + }) + ) + } +}` + +exports.expectResult = +`"use strict"; +class SwipeGestureExample extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.__rotateAngle = new ObservedPropertySimplePU(0, this, "rotateAngle"); + this.__speed = new ObservedPropertySimplePU(1, this, "speed"); + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + if (params.rotateAngle !== undefined) { + this.rotateAngle = params.rotateAngle; + } + if (params.speed !== undefined) { + this.speed = params.speed; + } + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + this.__rotateAngle.purgeDependencyOnElmtId(rmElmtId); + this.__speed.purgeDependencyOnElmtId(rmElmtId); + } + aboutToBeDeleted() { + this.__rotateAngle.aboutToBeDeleted(); + this.__speed.aboutToBeDeleted(); + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + get rotateAngle() { + return this.__rotateAngle.get(); + } + set rotateAngle(newValue) { + this.__rotateAngle.set(newValue); + } + get speed() { + return this.__speed.get(); + } + set speed(newValue) { + this.__speed.set(newValue); + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Column.create(); + Column.border({ width: 2 }); + Column.width(260); + Column.height(260); + Column.rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle }); + Gesture.create(GesturePriority.Low); + SwipeGesture.create({ fingers: 1, direction: SwipeDirection.Vertical }); + SwipeGesture.onAction((event) => { + this.speed = event.speed; + this.rotateAngle = event.angle; + }); + SwipeGesture.pop(); + Gesture.pop(); + if (!isInitialRender) { + Column.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create("SwipGesture speed : " + this.speed); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create("SwipGesture angle : " + this.rotateAngle); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + Column.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +ViewStackProcessor.StartGetAccessRecordingFor(ViewStackProcessor.AllocateNewElmetIdForNextComponent()); +loadDocument(new SwipeGestureExample(undefined, {})); +ViewStackProcessor.StopGetAccessRecording(); +` diff --git a/compiler/test/utForPartialUpdate/inner_component_transform/gesture_component/tapGesture.ts b/compiler/test/utForPartialUpdate/inner_component_transform/gesture_component/tapGesture.ts new file mode 100644 index 0000000000000000000000000000000000000000..8802fc81f7b306a2b43cc7a45bed20eb3b02f21e --- /dev/null +++ b/compiler/test/utForPartialUpdate/inner_component_transform/gesture_component/tapGesture.ts @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2022 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. + */ + +exports.source = ` +@Entry +@Component +struct TapGestureExample { + @State value: string = '' + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }) { + Text('Click twice') + Text(this.value) + } + .height(200).width(300).padding(60).border({ width: 1 }).margin(30) + .gesture( + TapGesture({ count: 2 }) + .onAction(() => { + this.value = 'TapGesture onAction' + }) + ) + } +}` + +exports.expectResult = +`"use strict"; +class TapGestureExample extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.__value = new ObservedPropertySimplePU('', this, "value"); + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + if (params.value !== undefined) { + this.value = params.value; + } + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + this.__value.purgeDependencyOnElmtId(rmElmtId); + } + aboutToBeDeleted() { + this.__value.aboutToBeDeleted(); + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + get value() { + return this.__value.get(); + } + set value(newValue) { + this.__value.set(newValue); + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Flex.create({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }); + Flex.height(200); + Flex.width(300); + Flex.padding(60); + Flex.border({ width: 1 }); + Flex.margin(30); + Gesture.create(GesturePriority.Low); + TapGesture.create({ count: 2 }); + TapGesture.onAction(() => { + this.value = 'TapGesture onAction'; + }); + TapGesture.pop(); + Gesture.pop(); + if (!isInitialRender) { + Flex.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create('Click twice'); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create(this.value); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + Flex.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +ViewStackProcessor.StartGetAccessRecordingFor(ViewStackProcessor.AllocateNewElmetIdForNextComponent()); +loadDocument(new TapGestureExample(undefined, {})); +ViewStackProcessor.StopGetAccessRecording(); +` diff --git a/compiler/test/utForPartialUpdate/inner_component_transform/render_component/foreach/forEachTwo.ts b/compiler/test/utForPartialUpdate/inner_component_transform/render_component/foreach/forEachTwo.ts new file mode 100644 index 0000000000000000000000000000000000000000..8a4a3862d43e61b135fcfda9629c0afcc0da9e00 --- /dev/null +++ b/compiler/test/utForPartialUpdate/inner_component_transform/render_component/foreach/forEachTwo.ts @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2022 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. + */ + +exports.source = ` +@Entry +@Component +struct Index { + @State WIDTH_AND_HEIGHT: Array<{ w: number, h: number }> = [ + { w: 10, h: 10 }, + { w: 20, h: 20 }, + { w: 30, h: 30 }, + { w: 40, h: 40 }, + { w: 50, h: 50 } + ] + build() { + Row() { + Column() { + ForEach(this.WIDTH_AND_HEIGHT, ({ w, h }) => { + Button() + .width(w) + .height(h) + }, item => item.toString()) + } + .width('100%') + } + .height('100%') + } +}` + +exports.expectResult = +`"use strict"; +class Index extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.__WIDTH_AND_HEIGHT = new ObservedPropertyObjectPU([ + { w: 10, h: 10 }, + { w: 20, h: 20 }, + { w: 30, h: 30 }, + { w: 40, h: 40 }, + { w: 50, h: 50 } + ], this, "WIDTH_AND_HEIGHT"); + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + if (params.WIDTH_AND_HEIGHT !== undefined) { + this.WIDTH_AND_HEIGHT = params.WIDTH_AND_HEIGHT; + } + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + this.__WIDTH_AND_HEIGHT.purgeDependencyOnElmtId(rmElmtId); + } + aboutToBeDeleted() { + this.__WIDTH_AND_HEIGHT.aboutToBeDeleted(); + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + get WIDTH_AND_HEIGHT() { + return this.__WIDTH_AND_HEIGHT.get(); + } + set WIDTH_AND_HEIGHT(newValue) { + this.__WIDTH_AND_HEIGHT.set(newValue); + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Row.create(); + Row.height('100%'); + if (!isInitialRender) { + Row.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Column.create(); + Column.width('100%'); + if (!isInitialRender) { + Column.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + ForEach.create(); + const forEachItemGenFunction = _item => { + const { w, h } = _item; + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Button.createWithLabel(); + Button.width(w); + Button.height(h); + if (!isInitialRender) { + Button.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Button.pop(); + }; + this.forEachUpdateFunction(elmtId, this.WIDTH_AND_HEIGHT, forEachItemGenFunction, item => item.toString(), false, false); + if (!isInitialRender) { + ForEach.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + ForEach.pop(); + Column.pop(); + Row.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +ViewStackProcessor.StartGetAccessRecordingFor(ViewStackProcessor.AllocateNewElmetIdForNextComponent()); +loadDocument(new Index(undefined, {})); +ViewStackProcessor.StopGetAccessRecording(); +` diff --git a/compiler/test/utForPartialUpdate/inner_component_transform/render_component/foreach/foreach.ts b/compiler/test/utForPartialUpdate/inner_component_transform/render_component/foreach/foreach.ts index 09e3232932d373bf8e14df0d4554d2e4360923c1..3c1de015296527850381695204585df1066e3f0a 100644 --- a/compiler/test/utForPartialUpdate/inner_component_transform/render_component/foreach/foreach.ts +++ b/compiler/test/utForPartialUpdate/inner_component_transform/render_component/foreach/foreach.ts @@ -17,6 +17,79 @@ exports.source = ` @Entry @Component struct ParentView { + @State arr: string[] = ['1', '2', '3']; + build() { + List() { + ForEach(this.arr, + item => { + Text(item) + } + ) + } + } +} + +@Component +struct ParentView1 { + @State arr: string[] = ['1', '2', '3']; + build() { + List() { + ForEach(this.arr, + (item, index) => { + Text(item) + } + ) + } + } +} + +@Component +struct ParentView2 { + @State arr: string[] = ['1', '2', '3']; + build() { + List() { + ForEach(this.arr, + (item, index) => { + Text(item) + }, + item => item.toString() + ) + } + } +} + +@Component +struct ParentView3 { + @State arr: string[] = ['1', '2', '3']; + build() { + List() { + ForEach(this.arr, + (item, index) => { + Text(item) + }, + (item, index) => item.toString() + ) + } + } +} + +@Component +struct ParentView4 { + @State arr: string[] = ['1', '2', '3']; + build() { + List() { + ForEach(this.arr, + item => { + Text(item) + }, + (item, index) => item.toString() + ) + } + } +} + +@Component +struct ParentView5 { @State arr: string[] = ['1', '2', '3']; build() { List() { @@ -33,8 +106,264 @@ struct ParentView { exports.expectResult = `"use strict"; class ParentView extends ViewPU { - constructor(parent, params, __localStorage) { - super(parent, __localStorage); + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.__arr = new ObservedPropertyObjectPU(['1', '2', '3'], this, "arr"); + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + if (params.arr !== undefined) { + this.arr = params.arr; + } + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + this.__arr.purgeDependencyOnElmtId(rmElmtId); + } + aboutToBeDeleted() { + this.__arr.aboutToBeDeleted(); + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + get arr() { + return this.__arr.get(); + } + set arr(newValue) { + this.__arr.set(newValue); + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + List.create(); + if (!isInitialRender) { + List.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + ForEach.create(); + const forEachItemGenFunction = _item => { + const item = _item; + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create(item); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + }; + this.forEachUpdateFunction(elmtId, this.arr, forEachItemGenFunction); + if (!isInitialRender) { + ForEach.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + ForEach.pop(); + List.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +class ParentView1 extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.__arr = new ObservedPropertyObjectPU(['1', '2', '3'], this, "arr"); + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + if (params.arr !== undefined) { + this.arr = params.arr; + } + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + this.__arr.purgeDependencyOnElmtId(rmElmtId); + } + aboutToBeDeleted() { + this.__arr.aboutToBeDeleted(); + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + get arr() { + return this.__arr.get(); + } + set arr(newValue) { + this.__arr.set(newValue); + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + List.create(); + if (!isInitialRender) { + List.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + ForEach.create(); + const forEachItemGenFunction = (_item, index) => { + const item = _item; + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create(item); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + }; + this.forEachUpdateFunction(elmtId, this.arr, forEachItemGenFunction, undefined, true, false); + if (!isInitialRender) { + ForEach.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + ForEach.pop(); + List.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +class ParentView2 extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.__arr = new ObservedPropertyObjectPU(['1', '2', '3'], this, "arr"); + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + if (params.arr !== undefined) { + this.arr = params.arr; + } + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + this.__arr.purgeDependencyOnElmtId(rmElmtId); + } + aboutToBeDeleted() { + this.__arr.aboutToBeDeleted(); + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + get arr() { + return this.__arr.get(); + } + set arr(newValue) { + this.__arr.set(newValue); + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + List.create(); + if (!isInitialRender) { + List.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + ForEach.create(); + const forEachItemGenFunction = (_item, index) => { + const item = _item; + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create(item); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + }; + this.forEachUpdateFunction(elmtId, this.arr, forEachItemGenFunction, item => item.toString(), true, false); + if (!isInitialRender) { + ForEach.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + ForEach.pop(); + List.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +class ParentView3 extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.__arr = new ObservedPropertyObjectPU(['1', '2', '3'], this, "arr"); + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + if (params.arr !== undefined) { + this.arr = params.arr; + } + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + this.__arr.purgeDependencyOnElmtId(rmElmtId); + } + aboutToBeDeleted() { + this.__arr.aboutToBeDeleted(); + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + get arr() { + return this.__arr.get(); + } + set arr(newValue) { + this.__arr.set(newValue); + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + List.create(); + if (!isInitialRender) { + List.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + ForEach.create(); + const forEachItemGenFunction = (_item, index) => { + const item = _item; + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create(item); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + }; + this.forEachUpdateFunction(elmtId, this.arr, forEachItemGenFunction, (item, index) => item.toString(), true, true); + if (!isInitialRender) { + ForEach.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + ForEach.pop(); + List.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +class ParentView4 extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); this.__arr = new ObservedPropertyObjectPU(['1', '2', '3'], this, "arr"); this.setInitiallyProvidedValue(params); } @@ -43,6 +372,72 @@ class ParentView extends ViewPU { this.arr = params.arr; } } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + this.__arr.purgeDependencyOnElmtId(rmElmtId); + } + aboutToBeDeleted() { + this.__arr.aboutToBeDeleted(); + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + get arr() { + return this.__arr.get(); + } + set arr(newValue) { + this.__arr.set(newValue); + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + List.create(); + if (!isInitialRender) { + List.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + ForEach.create(); + const forEachItemGenFunction = _item => { + const item = _item; + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create(item); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + }; + this.forEachUpdateFunction(elmtId, this.arr, forEachItemGenFunction, (item, index) => item.toString(), false, true); + if (!isInitialRender) { + ForEach.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + ForEach.pop(); + List.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +class ParentView5 extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.__arr = new ObservedPropertyObjectPU(['1', '2', '3'], this, "arr"); + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + if (params.arr !== undefined) { + this.arr = params.arr; + } + } + updateStateVars(params) { + } purgeVariableDependenciesOnElmtId(rmElmtId) { this.__arr.purgeDependencyOnElmtId(rmElmtId); } @@ -81,8 +476,7 @@ class ParentView extends ViewPU { }); Text.pop(); }; - const forEachItemIdFunc = item => item.toString(); - this.forEachUpdateFunction(elmtId, this.arr, forEachItemGenFunction, forEachItemIdFunc); + this.forEachUpdateFunction(elmtId, this.arr, forEachItemGenFunction, item => item.toString(), false, false); if (!isInitialRender) { ForEach.pop(); } @@ -92,7 +486,6 @@ class ParentView extends ViewPU { List.pop(); } rerender() { - this.__arr.markDependentElementsDirty(this); this.updateDirtyElements(); } } diff --git a/compiler/test/utForPartialUpdate/inner_component_transform/render_component/if/if.ts b/compiler/test/utForPartialUpdate/inner_component_transform/render_component/if/if.ts index 6a79a064893ca767316e42d706f87cfec7d79c24..ee5996686a30a37b45cfd109a60a2af8b77de891 100644 --- a/compiler/test/utForPartialUpdate/inner_component_transform/render_component/if/if.ts +++ b/compiler/test/utForPartialUpdate/inner_component_transform/render_component/if/if.ts @@ -32,6 +32,9 @@ struct IFView { } else { Text('toggle no thing') } + if (this.toggle1) { + Text('toggle1 Single') + } } } } @@ -39,8 +42,8 @@ struct IFView { exports.expectResult = `"use strict"; class IFView extends ViewPU { - constructor(parent, params, __localStorage) { - super(parent, __localStorage); + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); this.__toggle1 = new ObservedPropertySimplePU(false, this, "toggle1"); this.__toggle2 = new ObservedPropertySimplePU(false, this, "toggle2"); this.__toggle3 = new ObservedPropertySimplePU(false, this, "toggle3"); @@ -57,6 +60,8 @@ class IFView extends ViewPU { this.toggle3 = params.toggle3; } } + updateStateVars(params) { + } purgeVariableDependenciesOnElmtId(rmElmtId) { this.__toggle1.purgeDependencyOnElmtId(rmElmtId); this.__toggle2.purgeDependencyOnElmtId(rmElmtId); @@ -100,52 +105,81 @@ class IFView extends ViewPU { ViewStackProcessor.StartGetAccessRecordingFor(elmtId); If.create(); if (this.toggle1) { - If.branchId(0); - this.observeComponentCreation((elmtId, isInitialRender) => { - ViewStackProcessor.StartGetAccessRecordingFor(elmtId); - Text.create('toggle1'); - if (!isInitialRender) { - Text.pop(); - } - ViewStackProcessor.StopGetAccessRecording(); + this.ifElseBranchUpdateFunction(0, () => { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create('toggle1'); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); }); - Text.pop(); } else if (this.toggle2) { - If.branchId(1); - this.observeComponentCreation((elmtId, isInitialRender) => { - ViewStackProcessor.StartGetAccessRecordingFor(elmtId); - Text.create('toggle2'); - if (!isInitialRender) { - Text.pop(); - } - ViewStackProcessor.StopGetAccessRecording(); + this.ifElseBranchUpdateFunction(1, () => { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create('toggle2'); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); }); - Text.pop(); } else if (this.toggle3) { - If.branchId(2); - this.observeComponentCreation((elmtId, isInitialRender) => { - ViewStackProcessor.StartGetAccessRecordingFor(elmtId); - Text.create('toggle3'); - if (!isInitialRender) { - Text.pop(); - } - ViewStackProcessor.StopGetAccessRecording(); + this.ifElseBranchUpdateFunction(2, () => { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create('toggle3'); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); }); - Text.pop(); } else { - If.branchId(3); - this.observeComponentCreation((elmtId, isInitialRender) => { - ViewStackProcessor.StartGetAccessRecordingFor(elmtId); - Text.create('toggle no thing'); - if (!isInitialRender) { - Text.pop(); - } - ViewStackProcessor.StopGetAccessRecording(); + this.ifElseBranchUpdateFunction(3, () => { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create('toggle no thing'); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); }); - Text.pop(); + } + if (!isInitialRender) { + If.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + If.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + If.create(); + if (this.toggle1) { + this.ifElseBranchUpdateFunction(0, () => { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create('toggle1 Single'); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + }); + } + else { + If.branchId(1); } if (!isInitialRender) { If.pop(); @@ -156,9 +190,6 @@ class IFView extends ViewPU { Column.pop(); } rerender() { - this.__toggle1.markDependentElementsDirty(this); - this.__toggle2.markDependentElementsDirty(this); - this.__toggle3.markDependentElementsDirty(this); this.updateDirtyElements(); } } diff --git a/compiler/test/utForPartialUpdate/inner_component_transform/render_component/item/GridItem.ts b/compiler/test/utForPartialUpdate/inner_component_transform/render_component/item/GridItem.ts index 2988c7fb81975bc60b7623ce63f3c19b6b8e6ca9..3c148a3c48f47880873b1061d6760b73ed277a1c 100644 --- a/compiler/test/utForPartialUpdate/inner_component_transform/render_component/item/GridItem.ts +++ b/compiler/test/utForPartialUpdate/inner_component_transform/render_component/item/GridItem.ts @@ -29,12 +29,14 @@ struct ParentView { exports.expectResult = `"use strict"; class ParentView extends ViewPU { - constructor(parent, params, __localStorage) { - super(parent, __localStorage); + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); this.setInitiallyProvidedValue(params); } setInitiallyProvidedValue(params) { } + updateStateVars(params) { + } purgeVariableDependenciesOnElmtId(rmElmtId) { } aboutToBeDeleted() { diff --git a/compiler/test/utForPartialUpdate/inner_component_transform/render_component/item/ListItem.ts b/compiler/test/utForPartialUpdate/inner_component_transform/render_component/item/ListItem.ts index ae8cbcd813e9722025d6467ace3e80ba2cfc0da1..6a612e647b45373eec391a099ff9164126d7ac35 100644 --- a/compiler/test/utForPartialUpdate/inner_component_transform/render_component/item/ListItem.ts +++ b/compiler/test/utForPartialUpdate/inner_component_transform/render_component/item/ListItem.ts @@ -29,12 +29,14 @@ struct ParentView { exports.expectResult = `"use strict"; class ParentView extends ViewPU { - constructor(parent, params, __localStorage) { - super(parent, __localStorage); + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); this.setInitiallyProvidedValue(params); } setInitiallyProvidedValue(params) { } + updateStateVars(params) { + } purgeVariableDependenciesOnElmtId(rmElmtId) { } aboutToBeDeleted() { diff --git a/compiler/test/utForPartialUpdate/inner_component_transform/render_component/lazyforeach/lazyforeach.ts b/compiler/test/utForPartialUpdate/inner_component_transform/render_component/lazyforeach/lazyforeach.ts index 102dd68528f5e062dad6f1849120de1b02a10721..1c7a7475c6a1a6673b2aa645bd5dc058ed82eeb2 100644 --- a/compiler/test/utForPartialUpdate/inner_component_transform/render_component/lazyforeach/lazyforeach.ts +++ b/compiler/test/utForPartialUpdate/inner_component_transform/render_component/lazyforeach/lazyforeach.ts @@ -174,8 +174,8 @@ class MyDataSource extends BasicDataSource { } } class Test extends ViewPU { - constructor(parent, params, __localStorage) { - super(parent, __localStorage); + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); this.data = new MyDataSource(); this.setInitiallyProvidedValue(params); } @@ -184,10 +184,11 @@ class Test extends ViewPU { this.data = params.data; } } + updateStateVars(params) { + } purgeVariableDependenciesOnElmtId(rmElmtId) { } aboutToBeDeleted() { - this.data = undefined; SubscriberManager.Get().delete(this.id__()); this.aboutToBeDeletedInternal(); } diff --git a/compiler/test/utForPartialUpdate/inner_component_transform/render_component/tab/tab.ts b/compiler/test/utForPartialUpdate/inner_component_transform/render_component/tab/tab.ts index f531e5653452dfb69e3642b06186cebe0550ad65..750b231e164bdbd9d18646d5685a2f16838e177b 100644 --- a/compiler/test/utForPartialUpdate/inner_component_transform/render_component/tab/tab.ts +++ b/compiler/test/utForPartialUpdate/inner_component_transform/render_component/tab/tab.ts @@ -54,8 +54,8 @@ struct TabSimple { exports.expectResult = `"use strict"; class TabSimple extends ViewPU { - constructor(parent, params, __localStorage) { - super(parent, __localStorage); + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); this.controller = new TabsController(); this.setInitiallyProvidedValue(params); } @@ -64,10 +64,11 @@ class TabSimple extends ViewPU { this.controller = params.controller; } } + updateStateVars(params) { + } purgeVariableDependenciesOnElmtId(rmElmtId) { } aboutToBeDeleted() { - this.controller = undefined; SubscriberManager.Get().delete(this.id__()); this.aboutToBeDeletedInternal(); } diff --git a/compiler/test/utForPartialUpdate/inner_component_transform/simple_component/button/button.ts b/compiler/test/utForPartialUpdate/inner_component_transform/simple_component/button/button.ts new file mode 100644 index 0000000000000000000000000000000000000000..fd232815a23a8ac4c14971823127222814099f24 --- /dev/null +++ b/compiler/test/utForPartialUpdate/inner_component_transform/simple_component/button/button.ts @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2022 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. + */ + +exports.source = ` +@Entry +@Component +struct ButtonExample { + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.SpaceBetween }) { + Flex({ alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }) { + Button('Ok', { type: ButtonType.Normal, stateEffect: true }).borderRadius(8).backgroundColor(0x317aff).width(90) + Button({ type: ButtonType.Normal, stateEffect: true }) { + Row() { + Text('loading').fontSize(12).fontColor(0xffffff).margin({ left: 5, right: 12 }) + }.alignItems(VerticalAlign.Center) + }.borderRadius(8).backgroundColor(0x317aff).width(90) + Button('Disable', { type: ButtonType.Normal, stateEffect: false }).opacity(0.5) + .borderRadius(8).backgroundColor(0x317aff).width(90) + } + } + } +} +` +exports.expectResult = +`"use strict"; +class ButtonExample extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + } + aboutToBeDeleted() { + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Flex.create({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.SpaceBetween }); + if (!isInitialRender) { + Flex.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Flex.create({ alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }); + if (!isInitialRender) { + Flex.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Button.createWithLabel('Ok', { type: ButtonType.Normal, stateEffect: true }); + Button.borderRadius(8); + Button.backgroundColor(0x317aff); + Button.width(90); + if (!isInitialRender) { + Button.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Button.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Button.createWithChild({ type: ButtonType.Normal, stateEffect: true }); + Button.borderRadius(8); + Button.backgroundColor(0x317aff); + Button.width(90); + if (!isInitialRender) { + Button.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Row.create(); + Row.alignItems(VerticalAlign.Center); + if (!isInitialRender) { + Row.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create('loading'); + Text.fontSize(12); + Text.fontColor(0xffffff); + Text.margin({ left: 5, right: 12 }); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + Row.pop(); + Button.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Button.createWithLabel('Disable', { type: ButtonType.Normal, stateEffect: false }); + Button.opacity(0.5); + Button.borderRadius(8); + Button.backgroundColor(0x317aff); + Button.width(90); + if (!isInitialRender) { + Button.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Button.pop(); + Flex.pop(); + Flex.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +ViewStackProcessor.StartGetAccessRecordingFor(ViewStackProcessor.AllocateNewElmetIdForNextComponent()); +loadDocument(new ButtonExample(undefined, {})); +ViewStackProcessor.StopGetAccessRecording(); +` diff --git a/compiler/test/utForPartialUpdate/inner_component_transform/transition_component/animateTo/animateTo.ts b/compiler/test/utForPartialUpdate/inner_component_transform/transition_component/animateTo/animateTo.ts new file mode 100644 index 0000000000000000000000000000000000000000..a830d6143fe6672a0387c9ddb86e0895a11b0cc7 --- /dev/null +++ b/compiler/test/utForPartialUpdate/inner_component_transform/transition_component/animateTo/animateTo.ts @@ -0,0 +1,275 @@ +/* + * Copyright (c) 2022 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. + */ + +exports.source = ` +@Entry +@Component +struct TransitionExample { + @State btnW: number = 50 + @State btnH: number = 50 + @State btn1: boolean = false + @State show: string = "show" + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center,}) { + Button(this.show) + .onClick(() => { + animateTo({ duration: 1000 }, () => { + this.btn1 = !this.btn1 + if(this.btn1){ + this.show = "hide" + }else{ + this.show = "show" + } + }) + }) + if (this.btn1) { + Button() + .width("80%").height(30) + .transition({ type: TransitionType.Insert, scale: {x:0,y:1.0}}) + .transition({ type: TransitionType.Delete, scale: { x: 1.0, y: 0.0 }}) + } + Button('animation') + .width(this.btnW).height(this.btnH) + .onClick(() => { + this.btnW += 50 + }) + .animation({ + duration: 1000, // 动画时长 + curve: Curve.EaseOut, // 动画曲线 + delay: 200, // 动画延迟 + iterations: 1, // 播放次数 + playMode: PlayMode.Normal // 动画模式 + }) + Column({space: 5}) { + Column() + .opacity(this.opacity1) + .backgroundColor(this.color) + .animation({duration: 1000}) + .width(this.width1) + .animation({duration: 2000}) + .height(this.height1) + .borderRadius(this.borderRaius1) + .animation({duration: 3000}) + .onClick(() => { + this.color = Color.Green + this.borderRaius1 = 20 + this.opacity1 = 0.5 + this.height1 = 200 + this.width1 = 200 + }) + } + .width("100%") + .height("100%") + }.height(400).width("100%").padding({top:100}) + } +} +` + +exports.expectResult = +`"use strict"; +class TransitionExample extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.__btnW = new ObservedPropertySimplePU(50, this, "btnW"); + this.__btnH = new ObservedPropertySimplePU(50, this, "btnH"); + this.__btn1 = new ObservedPropertySimplePU(false, this, "btn1"); + this.__show = new ObservedPropertySimplePU("show", this, "show"); + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + if (params.btnW !== undefined) { + this.btnW = params.btnW; + } + if (params.btnH !== undefined) { + this.btnH = params.btnH; + } + if (params.btn1 !== undefined) { + this.btn1 = params.btn1; + } + if (params.show !== undefined) { + this.show = params.show; + } + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + this.__btnW.purgeDependencyOnElmtId(rmElmtId); + this.__btnH.purgeDependencyOnElmtId(rmElmtId); + this.__btn1.purgeDependencyOnElmtId(rmElmtId); + this.__show.purgeDependencyOnElmtId(rmElmtId); + } + aboutToBeDeleted() { + this.__btnW.aboutToBeDeleted(); + this.__btnH.aboutToBeDeleted(); + this.__btn1.aboutToBeDeleted(); + this.__show.aboutToBeDeleted(); + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + get btnW() { + return this.__btnW.get(); + } + set btnW(newValue) { + this.__btnW.set(newValue); + } + get btnH() { + return this.__btnH.get(); + } + set btnH(newValue) { + this.__btnH.set(newValue); + } + get btn1() { + return this.__btn1.get(); + } + set btn1(newValue) { + this.__btn1.set(newValue); + } + get show() { + return this.__show.get(); + } + set show(newValue) { + this.__show.set(newValue); + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Flex.create({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, }); + Flex.height(400); + Flex.width("100%"); + Flex.padding({ top: 100 }); + if (!isInitialRender) { + Flex.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Button.createWithLabel(this.show); + Button.onClick(() => { + Context.animateTo({ duration: 1000 }, () => { + this.btn1 = !this.btn1; + if (this.btn1) { + this.show = "hide"; + } + else { + this.show = "show"; + } + }); + }); + if (!isInitialRender) { + Button.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Button.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + If.create(); + if (this.btn1) { + this.ifElseBranchUpdateFunction(0, () => { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Button.createWithLabel(); + Button.width("80%"); + Button.height(30); + Button.transition({ type: TransitionType.Insert, scale: { x: 0, y: 1.0 } }); + Button.transition({ type: TransitionType.Delete, scale: { x: 1.0, y: 0.0 } }); + if (!isInitialRender) { + Button.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Button.pop(); + }); + } + else { + If.branchId(1); + } + if (!isInitialRender) { + If.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + If.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Button.createWithLabel('animation'); + Context.animation({ + duration: 1000, + curve: Curve.EaseOut, + delay: 200, + iterations: 1, + playMode: PlayMode.Normal // 动画模式 + }); + Button.width(this.btnW); + Button.height(this.btnH); + Button.onClick(() => { + this.btnW += 50; + }); + Context.animation(null); + if (!isInitialRender) { + Button.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Button.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Column.create({ space: 5 }); + Column.width("100%"); + Column.height("100%"); + if (!isInitialRender) { + Column.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Column.create(); + Context.animation({ duration: 1000 }); + Column.opacity(this.opacity1); + Column.backgroundColor(this.color); + Context.animation(null); + Context.animation({ duration: 2000 }); + Column.width(this.width1); + Context.animation(null); + Context.animation({ duration: 3000 }); + Column.height(this.height1); + Column.borderRadius(this.borderRaius1); + Context.animation(null); + Column.onClick(() => { + this.color = Color.Green; + this.borderRaius1 = 20; + this.opacity1 = 0.5; + this.height1 = 200; + this.width1 = 200; + }); + if (!isInitialRender) { + Column.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Column.pop(); + Column.pop(); + Flex.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +ViewStackProcessor.StartGetAccessRecordingFor(ViewStackProcessor.AllocateNewElmetIdForNextComponent()); +loadDocument(new TransitionExample(undefined, {})); +ViewStackProcessor.StopGetAccessRecording(); +` diff --git a/compiler/test/utForPartialUpdate/inner_component_transform/transition_component/pageTransition/pageTransition.ts b/compiler/test/utForPartialUpdate/inner_component_transform/transition_component/pageTransition/pageTransition.ts new file mode 100644 index 0000000000000000000000000000000000000000..5f984260b0da410331cb2642b6d941c0712f3326 --- /dev/null +++ b/compiler/test/utForPartialUpdate/inner_component_transform/transition_component/pageTransition/pageTransition.ts @@ -0,0 +1,170 @@ +/* + * Copyright (c) 2022 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. + */ + +exports.source = ` +@Entry +@Component +struct PageTransitionExample1 { + @State scale2: number = 1 + @State opacity2: number = 1 + @State active: boolean = false + build() { + Column() { + Navigator({ target: 'pages/page1', type: NavigationType.Push }) { + Text('page transition').width("100%").height("100%") + } + .onClick(() => { + this.active = true + }) + }.scale({ x: this.scale2 }).opacity(this.opacity2) + } + pageTransition() { + PageTransitionEnter({ duration: 1200, curve: Curve.Linear }) + .onEnter((type: RouteType, progress: number) => { + this.scale2 = 1 + this.opacity2 = progress + }) + PageTransitionExit({ duration: 1500, curve: Curve.Ease }) + .onExit((type: RouteType, progress: number) => { + this.scale2 = 1 - progress + this.opacity2 = 1 + }) + } +} +` + +exports.expectResult = +`"use strict"; +class PageTransitionExample1 extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.__scale2 = new ObservedPropertySimplePU(1, this, "scale2"); + this.__opacity2 = new ObservedPropertySimplePU(1, this, "opacity2"); + this.__active = new ObservedPropertySimplePU(false, this, "active"); + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + if (params.scale2 !== undefined) { + this.scale2 = params.scale2; + } + if (params.opacity2 !== undefined) { + this.opacity2 = params.opacity2; + } + if (params.active !== undefined) { + this.active = params.active; + } + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + this.__scale2.purgeDependencyOnElmtId(rmElmtId); + this.__opacity2.purgeDependencyOnElmtId(rmElmtId); + this.__active.purgeDependencyOnElmtId(rmElmtId); + } + aboutToBeDeleted() { + this.__scale2.aboutToBeDeleted(); + this.__opacity2.aboutToBeDeleted(); + this.__active.aboutToBeDeleted(); + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + get scale2() { + return this.__scale2.get(); + } + set scale2(newValue) { + this.__scale2.set(newValue); + } + get opacity2() { + return this.__opacity2.get(); + } + set opacity2(newValue) { + this.__opacity2.set(newValue); + } + get active() { + return this.__active.get(); + } + set active(newValue) { + this.__active.set(newValue); + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Column.create(); + Column.scale({ x: this.scale2 }); + Column.opacity(this.opacity2); + if (!isInitialRender) { + Column.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Navigator.create({ target: 'pages/page1', type: NavigationType.Push }); + Navigator.onClick(() => { + this.active = true; + }); + if (!isInitialRender) { + Navigator.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create('page transition'); + Text.width("100%"); + Text.height("100%"); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + Navigator.pop(); + Column.pop(); + } + pageTransition() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + PageTransition.create(); + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + PageTransitionEnter.create({ duration: 1200, curve: Curve.Linear }); + PageTransitionEnter.onEnter((type, progress) => { + this.scale2 = 1; + this.opacity2 = progress; + }); + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + PageTransitionExit.create({ duration: 1500, curve: Curve.Ease }); + PageTransitionExit.onExit((type, progress) => { + this.scale2 = 1 - progress; + this.opacity2 = 1; + }); + ViewStackProcessor.StopGetAccessRecording(); + }); + PageTransition.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +ViewStackProcessor.StartGetAccessRecordingFor(ViewStackProcessor.AllocateNewElmetIdForNextComponent()); +loadDocument(new PageTransitionExample1(undefined, {})); +ViewStackProcessor.StopGetAccessRecording(); +` diff --git a/compiler/test/utForPartialUpdate/render_decorator/@builder/@builder.ts b/compiler/test/utForPartialUpdate/render_decorator/@builder/@builder.ts new file mode 100644 index 0000000000000000000000000000000000000000..52cfc5bf7db9394ea2f786f1c0b194401c1a660b --- /dev/null +++ b/compiler/test/utForPartialUpdate/render_decorator/@builder/@builder.ts @@ -0,0 +1,624 @@ +/* + * Copyright (c) 2022 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. + */ + +exports.source = ` +@Builder function noParam(){ + Row(){ + Text('this is a no param builder') + } +} +@Builder function specificParam(label1: string, label2: string) { + Column() { + Text(label1) + Text(label2) + } +} +@Entry +@Component +struct MyComponent { + private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + private controller: TabsController = new TabsController() + @State hideBar: boolean = true + @Builder textBuilder() { + Text("文本") + .fontSize(30) + } + @Builder NavigationTitlePara(label:string) { + Column() { + Text(label) + .width(80) + .bindMenu(this.textBuilder) + } + } + @Builder MenuBuilder() { + Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { + Text('Test menu item 1') + .fontSize(20) + Divider().height(10) + Text('Test menu item 2') + .fontSize(20) + }.width(100) + } + + build() { + Column() { + Row(){ + Text("Drag Me") + .onDragStart((event: DragEvent, extraParams: string) => { + console.log('Text onDragStarts, ' + extraParams) + }) + specificParam('test1', 'test2') + } + .padding(10) + .bindMenu(this.NavigationTitlePara("111")) + Row(){ + Text('Test Text') + } + .padding(10) + .bindPopup(false, { + builder: this.MenuBuilder, + onStateChange: (e) => { + if(!e.isVisible){ + console.warn(JSON.stringify(e.isVisible)) + } + } + }) + Row() { + Text('rightclick for menu') + } + .padding(10) + .bindContextMenu(this.MenuBuilder, ResponseType.RightClick) + Row(){ + Navigation() { + List({ space: 5, initialIndex: 0 }) { + ForEach(this.arr, (item) => { + ListItem() { + Text('' + item) + .width('90%') + .height(80) + .backgroundColor('#3366CC') + .borderRadius(15) + .fontSize(16) + .textAlign(TextAlign.Center) + }.editable(true) + }, item => item) + } + .listDirection(Axis.Vertical) + .height(300) + .margin({ top: 10, left: 18 }) + .width('100%') + Button(this.hideBar ? "tool bar" : "hide bar") + .onClick(() => { + this.hideBar = !this.hideBar + }) + .margin({ left: 135, top: 60 }) + } + .title(noParam) + .menus(this.textBuilder) + .toolBar({ items: [ + { value: 'app', text: 'Grid', action: () => { + console.log("app") + } }, + { value: 'add', text: 'Add', action: () => { + console.log("add") + } }, + { value: 'collect', text: 'Collect', action: () => { + console.log("collect") + } }] }) + .hideToolBar(this.hideBar) + } + .padding(10) + Row(){ + Tabs({ barPosition: BarPosition.Start, controller: this.controller }) { + TabContent() { + Text('111').width('100%').height('20').backgroundColor(Color.Pink) + } + .tabBar('pink') + TabContent() { + Text('222').width('100%').height('20').backgroundColor(Color.Yellow) + } + .tabBar('yellow') + TabContent() { + Text('333').width('100%').height('20').backgroundColor(Color.Blue) + } + .tabBar('blue') + } + } + .padding(10) + } + } +} +` +exports.expectResult = +`"use strict"; +function noParam(parent = null) { + (parent ? parent : this).observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Row.create(); + if (!isInitialRender) { + Row.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + (parent ? parent : this).observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create('this is a no param builder'); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + Row.pop(); +} +function specificParam(label1, label2, parent = null) { + (parent ? parent : this).observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Column.create(); + if (!isInitialRender) { + Column.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + (parent ? parent : this).observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create(label1); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + (parent ? parent : this).observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create(label2); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + Column.pop(); +} +class MyComponent extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; + this.controller = new TabsController(); + this.__hideBar = new ObservedPropertySimplePU(true, this, "hideBar"); + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + if (params.arr !== undefined) { + this.arr = params.arr; + } + if (params.controller !== undefined) { + this.controller = params.controller; + } + if (params.hideBar !== undefined) { + this.hideBar = params.hideBar; + } + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + this.__hideBar.purgeDependencyOnElmtId(rmElmtId); + } + aboutToBeDeleted() { + this.__hideBar.aboutToBeDeleted(); + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + get hideBar() { + return this.__hideBar.get(); + } + set hideBar(newValue) { + this.__hideBar.set(newValue); + } + textBuilder(parent = null) { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create("文本"); + Text.fontSize(30); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + } + NavigationTitlePara(label, parent = null) { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Column.create(); + if (!isInitialRender) { + Column.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create(label); + Text.width(80); + Text.bindMenu({ builder: this.textBuilder.bind(this) }); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + Column.pop(); + } + MenuBuilder(parent = null) { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Flex.create({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }); + Flex.width(100); + if (!isInitialRender) { + Flex.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create('Test menu item 1'); + Text.fontSize(20); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Divider.create(); + Divider.height(10); + if (!isInitialRender) { + Divider.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create('Test menu item 2'); + Text.fontSize(20); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + Flex.pop(); + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Column.create(); + if (!isInitialRender) { + Column.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Row.create(); + Row.padding(10); + Row.bindMenu({ builder: () => { + this.NavigationTitlePara.call(this, "111"); + } }); + if (!isInitialRender) { + Row.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create("Drag Me"); + Text.onDragStart((event, extraParams) => { + console.log('Text onDragStarts, ' + extraParams); + }); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + specificParam('test1', 'test2', this); + Row.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Row.create(); + Row.padding(10); + Row.bindPopup(false, { + builder: { builder: this.MenuBuilder.bind(this) }, + onStateChange: (e) => { + if (!e.isVisible) { + console.warn(JSON.stringify(e.isVisible)); + } + } + }); + if (!isInitialRender) { + Row.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create('Test Text'); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + Row.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Row.create(); + Row.padding(10); + Row.bindContextMenu({ builder: this.MenuBuilder.bind(this) }, ResponseType.RightClick); + if (!isInitialRender) { + Row.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create('rightclick for menu'); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + Row.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Row.create(); + Row.padding(10); + if (!isInitialRender) { + Row.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Navigation.create(); + Navigation.title({ builder: noParam.bind(this) }); + Navigation.menus({ builder: this.textBuilder.bind(this) }); + Navigation.toolBar({ items: [ + { value: 'app', text: 'Grid', action: () => { + console.log("app"); + } }, + { value: 'add', text: 'Add', action: () => { + console.log("add"); + } }, + { value: 'collect', text: 'Collect', action: () => { + console.log("collect"); + } } + ] }); + Navigation.hideToolBar(this.hideBar); + if (!isInitialRender) { + Navigation.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + List.create({ space: 5, initialIndex: 0 }); + List.listDirection(Axis.Vertical); + List.height(300); + List.margin({ top: 10, left: 18 }); + List.width('100%'); + if (!isInitialRender) { + List.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + ForEach.create(); + const forEachItemGenFunction = _item => { + const item = _item; + { + const isLazyCreate = true; + const itemCreation = (elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + ListItem.create(deepRenderFunction, isLazyCreate); + ListItem.editable(true); + if (!isInitialRender) { + ListItem.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }; + const observedShallowRender = () => { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + ListItem.create(deepRenderFunction, isLazyCreate); + if (!isInitialRender) { + ListItem.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + ListItem.pop(); + }; + const observedDeepRender = () => { + this.observeComponentCreation(itemCreation); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create('' + item); + Text.width('90%'); + Text.height(80); + Text.backgroundColor('#3366CC'); + Text.borderRadius(15); + Text.fontSize(16); + Text.textAlign(TextAlign.Center); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + ListItem.pop(); + }; + const deepRenderFunction = (elmtId, isInitialRender) => { + itemCreation(elmtId, isInitialRender); + this.updateFuncByElmtId.set(elmtId, itemCreation); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create('' + item); + Text.width('90%'); + Text.height(80); + Text.backgroundColor('#3366CC'); + Text.borderRadius(15); + Text.fontSize(16); + Text.textAlign(TextAlign.Center); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + ListItem.pop(); + }; + if (isLazyCreate) { + observedShallowRender(); + } + else { + observedDeepRender(); + } + } + }; + this.forEachUpdateFunction(elmtId, this.arr, forEachItemGenFunction, item => item, false, false); + if (!isInitialRender) { + ForEach.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + ForEach.pop(); + List.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Button.createWithLabel(this.hideBar ? "tool bar" : "hide bar"); + Button.onClick(() => { + this.hideBar = !this.hideBar; + }); + Button.margin({ left: 135, top: 60 }); + if (!isInitialRender) { + Button.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Button.pop(); + Navigation.pop(); + Row.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Row.create(); + Row.padding(10); + if (!isInitialRender) { + Row.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Tabs.create({ barPosition: BarPosition.Start, controller: this.controller }); + if (!isInitialRender) { + Tabs.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + TabContent.create(() => { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create('111'); + Text.width('100%'); + Text.height('20'); + Text.backgroundColor(Color.Pink); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + }); + TabContent.tabBar('pink'); + if (!isInitialRender) { + TabContent.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + TabContent.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + TabContent.create(() => { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create('222'); + Text.width('100%'); + Text.height('20'); + Text.backgroundColor(Color.Yellow); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + }); + TabContent.tabBar('yellow'); + if (!isInitialRender) { + TabContent.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + TabContent.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + TabContent.create(() => { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create('333'); + Text.width('100%'); + Text.height('20'); + Text.backgroundColor(Color.Blue); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + }); + TabContent.tabBar('blue'); + if (!isInitialRender) { + TabContent.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + TabContent.pop(); + Tabs.pop(); + Row.pop(); + Column.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +ViewStackProcessor.StartGetAccessRecordingFor(ViewStackProcessor.AllocateNewElmetIdForNextComponent()); +loadDocument(new MyComponent(undefined, {})); +ViewStackProcessor.StopGetAccessRecording(); +` diff --git a/compiler/test/utForPartialUpdate/render_decorator/@builder/@builderWithComponent.ts b/compiler/test/utForPartialUpdate/render_decorator/@builder/@builderWithComponent.ts new file mode 100644 index 0000000000000000000000000000000000000000..bcff54b58afc14d2dd7e32cce0376ac73cc15b88 --- /dev/null +++ b/compiler/test/utForPartialUpdate/render_decorator/@builder/@builderWithComponent.ts @@ -0,0 +1,152 @@ +/* + * Copyright (c) 2022 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. + */ + +exports.source = ` +@Builder +function myBuilder() { + child(); +} + +@Entry +@Component +struct Index { + @Builder Builder1() { + child() + } + build() { + Row() { + myBuilder(); + this.Builder1(); + child(); + } + } +} + +@Component +struct child{ + build() { + Text('Hello') + } +} +` + +exports.expectResult = +`"use strict"; +function myBuilder(parent = null) { + { + (parent ? parent : this).observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + if (isInitialRender) { + ViewPU.create(new child(parent ? parent : this, {}, undefined, elmtId)); + } + else { + (parent ? parent : this).updateStateVarsOfChildByElmtId(elmtId, {}); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + } +} +class Index extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + } + aboutToBeDeleted() { + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + Builder1(parent = null) { + { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + if (isInitialRender) { + ViewPU.create(new child(this, {}, undefined, elmtId)); + } + else { + this.updateStateVarsOfChildByElmtId(elmtId, {}); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + } + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Row.create(); + if (!isInitialRender) { + Row.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + myBuilder(this); + this.Builder1(this); + { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + if (isInitialRender) { + ViewPU.create(new child(this, {}, undefined, elmtId)); + } + else { + this.updateStateVarsOfChildByElmtId(elmtId, {}); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + } + Row.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +class child extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + } + aboutToBeDeleted() { + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create('Hello'); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +ViewStackProcessor.StartGetAccessRecordingFor(ViewStackProcessor.AllocateNewElmetIdForNextComponent()); +loadDocument(new Index(undefined, {})); +ViewStackProcessor.StopGetAccessRecording(); +` \ No newline at end of file diff --git a/compiler/test/utForPartialUpdate/render_decorator/@builder/@builderWithForEach.ts b/compiler/test/utForPartialUpdate/render_decorator/@builder/@builderWithForEach.ts new file mode 100644 index 0000000000000000000000000000000000000000..9c02a207f75bb17f1e7e887aa119018fe3e10552 --- /dev/null +++ b/compiler/test/utForPartialUpdate/render_decorator/@builder/@builderWithForEach.ts @@ -0,0 +1,171 @@ +/* + * Copyright (c) 2022 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. + */ + +exports.source = ` +@Builder +function ComB(param: string[]) { + ForEach(param, item => { + ComA().backgroundColor('red') + }) +} + +@Entry +@Component +struct Index { + @State arr: string[] = ['1', '2', '3', '4', '5'] + + build() { + Column() { + ComB(this.arr); + } + } +} + +@Component +struct ComA { + build() { + Row() { + Text('自定义组件') + .fontSize(30) + } + } +} +` +exports.expectResult = +`"use strict"; +function ComB(param, parent = null) { + (parent ? parent : this).observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + ForEach.create(); + const forEachItemGenFunction = _item => { + const item = _item; + (parent ? parent : this).observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + __Common__.create(); + __Common__.backgroundColor('red'); + if (!isInitialRender) { + __Common__.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + { + (parent ? parent : this).observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + if (isInitialRender) { + ViewPU.create(new ComA(parent ? parent : this, {}, undefined, elmtId)); + } + else { + (parent ? parent : this).updateStateVarsOfChildByElmtId(elmtId, {}); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + } + __Common__.pop(); + }; + (parent ? parent : this).forEachUpdateFunction(elmtId, param, forEachItemGenFunction); + if (!isInitialRender) { + ForEach.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + ForEach.pop(); +} +class Index extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.__arr = new ObservedPropertyObjectPU(['1', '2', '3', '4', '5'], this, "arr"); + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + if (params.arr !== undefined) { + this.arr = params.arr; + } + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + this.__arr.purgeDependencyOnElmtId(rmElmtId); + } + aboutToBeDeleted() { + this.__arr.aboutToBeDeleted(); + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + get arr() { + return this.__arr.get(); + } + set arr(newValue) { + this.__arr.set(newValue); + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Column.create(); + if (!isInitialRender) { + Column.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + ComB(this.arr, this); + Column.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +class ComA extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + } + aboutToBeDeleted() { + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Row.create(); + if (!isInitialRender) { + Row.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create('自定义组件'); + Text.fontSize(30); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + Row.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +ViewStackProcessor.StartGetAccessRecordingFor(ViewStackProcessor.AllocateNewElmetIdForNextComponent()); +loadDocument(new Index(undefined, {})); +ViewStackProcessor.StopGetAccessRecording(); +` diff --git a/compiler/test/utForPartialUpdate/render_decorator/@builder/@builderWithLinkData.ts b/compiler/test/utForPartialUpdate/render_decorator/@builder/@builderWithLinkData.ts new file mode 100644 index 0000000000000000000000000000000000000000..784ac7dc68feb16193ce6031e207c9066d7413a7 --- /dev/null +++ b/compiler/test/utForPartialUpdate/render_decorator/@builder/@builderWithLinkData.ts @@ -0,0 +1,141 @@ +/* + * Copyright (c) 2022 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. + */ + +exports.source = ` +@Component +struct TitleComp { + @Link title: string + build() { + Text(this.title) + } +} + +@Entry +@Component +struct TestPage{ + @State value: string = 'hello world' + @Builder + TitleCompView() { + TitleComp({title: $value}) + } + build() { + Flex() { + this.TitleCompView() + } + } +} +` +exports.expectResult = +`"use strict"; +class TitleComp extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.__title = new SynchedPropertySimpleTwoWayPU(params.title, this, "title"); + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + this.__title.purgeDependencyOnElmtId(rmElmtId); + } + aboutToBeDeleted() { + this.__title.aboutToBeDeleted(); + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + get title() { + return this.__title.get(); + } + set title(newValue) { + this.__title.set(newValue); + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create(this.title); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +class TestPage extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.__value = new ObservedPropertySimplePU('hello world', this, "value"); + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + if (params.value !== undefined) { + this.value = params.value; + } + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + this.__value.purgeDependencyOnElmtId(rmElmtId); + } + aboutToBeDeleted() { + this.__value.aboutToBeDeleted(); + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + get value() { + return this.__value.get(); + } + set value(newValue) { + this.__value.set(newValue); + } + TitleCompView(parent = null) { + { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + if (isInitialRender) { + ViewPU.create(new TitleComp(this, { title: this.__value }, undefined, elmtId)); + } + else { + this.updateStateVarsOfChildByElmtId(elmtId, {}); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + } + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Flex.create(); + if (!isInitialRender) { + Flex.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.TitleCompView(this); + Flex.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +ViewStackProcessor.StartGetAccessRecordingFor(ViewStackProcessor.AllocateNewElmetIdForNextComponent()); +loadDocument(new TestPage(undefined, {})); +ViewStackProcessor.StopGetAccessRecording(); +` diff --git a/compiler/test/utForPartialUpdate/render_decorator/@builderParam/@builderParam.ts b/compiler/test/utForPartialUpdate/render_decorator/@builderParam/@builderParam.ts new file mode 100644 index 0000000000000000000000000000000000000000..9742eed764d07afe65dda7dc0005ecf84b1f2555 --- /dev/null +++ b/compiler/test/utForPartialUpdate/render_decorator/@builderParam/@builderParam.ts @@ -0,0 +1,433 @@ +/* + * Copyright (c) 2022 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. + */ + +exports.source = ` +import { CustomContainerExport } from './test/pages/TestComponent'; +@Component +struct CustomContainer { + header: string = ""; + @BuilderParam content: () => void; + @BuilderParam callContent: any; + footer: string = ""; + build() { + Column() { + Text(this.header) + this.content() + this.callContent() + Text(this.footer) + } + } +} + +@Component +struct CustomContainer2 { + header: string = ""; + @BuilderParam content: () => void; + build() { + Column() { + Text(this.header) + this.content() + } + } +} + +@Builder function specificWithParam(label1: string, label2: string) { + Column() { + Text(label1).fontSize(50) + Text(label2).fontSize(50) + } +} + +@Entry +@Component +struct CustomContainerUser { + @State text: string = 'header' + @Builder specificParam() { + Column() { + Text("content").fontSize(50) + } + } + @Builder callSpecificParam(label1: string, label2: string) { + Column() { + Text(label1).fontSize(50) + Text(label2).fontSize(50) + } + } + + build() { + Column() { + CustomContainerExport({ + header: this.text, + }){ + Column(){ + specificWithParam("111", "22") + }.onClick(()=>{ + this.text = "changeHeader" + }) + } + Row(){ + CustomContainer({ + header: this.text, + content: this.specificParam, + callContent: this.callSpecificParam("callContent1", 'callContent2'), + footer: "Footer", + }) + } + Row(){ + CustomContainer2({ + header: this.text, + }){ + Column(){ + this.callSpecificParam("111", '222') + }.onClick(()=>{ + this.text = "changeHeader" + }) + } + } + } + } +} +` +exports.expectResult = +`"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const TestComponent_1 = require("./test/pages/TestComponent"); +class CustomContainer extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.header = ""; + this.footer = ""; + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + if (params.header !== undefined) { + this.header = params.header; + } + this.content = params.content; + this.callContent = params.callContent; + if (params.footer !== undefined) { + this.footer = params.footer; + } + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + } + aboutToBeDeleted() { + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Column.create(); + if (!isInitialRender) { + Column.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create(this.header); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + this.content(this); + this.callContent(this); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create(this.footer); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + Column.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +class CustomContainer2 extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.header = ""; + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + if (params.header !== undefined) { + this.header = params.header; + } + this.content = params.content; + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + } + aboutToBeDeleted() { + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Column.create(); + if (!isInitialRender) { + Column.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create(this.header); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + this.content(this); + Column.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +function specificWithParam(label1, label2, parent = null) { + (parent ? parent : this).observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Column.create(); + if (!isInitialRender) { + Column.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + (parent ? parent : this).observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create(label1); + Text.fontSize(50); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + (parent ? parent : this).observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create(label2); + Text.fontSize(50); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + Column.pop(); +} +class CustomContainerUser extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.__text = new ObservedPropertySimplePU('header', this, "text"); + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + if (params.text !== undefined) { + this.text = params.text; + } + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + this.__text.purgeDependencyOnElmtId(rmElmtId); + } + aboutToBeDeleted() { + this.__text.aboutToBeDeleted(); + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + get text() { + return this.__text.get(); + } + set text(newValue) { + this.__text.set(newValue); + } + specificParam(parent = null) { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Column.create(); + if (!isInitialRender) { + Column.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create("content"); + Text.fontSize(50); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + Column.pop(); + } + callSpecificParam(label1, label2, parent = null) { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Column.create(); + if (!isInitialRender) { + Column.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create(label1); + Text.fontSize(50); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create(label2); + Text.fontSize(50); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + Column.pop(); + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Column.create(); + if (!isInitialRender) { + Column.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + if (isInitialRender) { + ViewPU.create(new TestComponent_1.CustomContainerExport(this, { + header: this.text, + closer: () => { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Column.create(); + Column.onClick(() => { + this.text = "changeHeader"; + }); + if (!isInitialRender) { + Column.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + specificWithParam("111", "22", this); + Column.pop(); + } + }, undefined, elmtId)); + } + else { + this.updateStateVarsOfChildByElmtId(elmtId, {}); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + } + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Row.create(); + if (!isInitialRender) { + Row.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + if (isInitialRender) { + ViewPU.create(new CustomContainer(this, { + header: this.text, + content: this.specificParam, + callContent: this.callSpecificParam("callContent1", 'callContent2'), + footer: "Footer", + }, undefined, elmtId)); + } + else { + this.updateStateVarsOfChildByElmtId(elmtId, {}); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + } + Row.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Row.create(); + if (!isInitialRender) { + Row.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + if (isInitialRender) { + ViewPU.create(new CustomContainer2(this, { + header: this.text, + content: () => { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Column.create(); + Column.onClick(() => { + this.text = "changeHeader"; + }); + if (!isInitialRender) { + Column.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.callSpecificParam("111", '222', this); + Column.pop(); + } + }, undefined, elmtId)); + } + else { + this.updateStateVarsOfChildByElmtId(elmtId, {}); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + } + Row.pop(); + Column.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +ViewStackProcessor.StartGetAccessRecordingFor(ViewStackProcessor.AllocateNewElmetIdForNextComponent()); +loadDocument(new CustomContainerUser(undefined, {})); +ViewStackProcessor.StopGetAccessRecording(); +` diff --git a/compiler/test/utForPartialUpdate/render_decorator/@customDialog/@customDialog.ts b/compiler/test/utForPartialUpdate/render_decorator/@customDialog/@customDialog.ts new file mode 100644 index 0000000000000000000000000000000000000000..e3d874bbcb960d1827a186353c928304127df2e6 --- /dev/null +++ b/compiler/test/utForPartialUpdate/render_decorator/@customDialog/@customDialog.ts @@ -0,0 +1,375 @@ +/* + * Copyright (c) 2022 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. + */ + +exports.source = ` +@CustomDialog +struct DialogExample { + @Prop count: number + @Link isPlaying: boolean + controller: CustomDialogController; + termsToAccept: string = "" + action1: () => void; + action2: (x: number, s: string) => void; + + build() { + Column(){ + Row(){ + Button('current count is: ' + this.count) + .onClick(() => { + this.count++; + }) + } + Row(){ + Button(this.isPlaying ? 'play' : 'pause') + .onClick(() => { + this.isPlaying = !this.isPlaying; + }) + } + Row() { + Button ("Option A") + .onClick(() => { + this.controller.close(); + this.action1(); + }) + Button ("Option B") + .onClick(() => { + this.controller.close(); + this.action2(47, "Option B is great choice"); + }) + } + } + } +} + +@Entry +@Component +struct CustomDialogUser { + @State countInitValue: number = 10; + @State playingInitValue: boolean = false; + dialogController : CustomDialogController = new CustomDialogController({ + builder: DialogExample({ + termsToAccept: "Please accept the terms.", + action1: this.onAccept, + action2: this.existApp, + count: this.countInitValue, + isPlaying: $playingInitValue + }), + cancel: this.existApp, + autoCancel: false + }); + + onAccept() { + console.log("onAccept"); + } + existApp() { + console.log("Cancel dialog!"); + } + + build() { + Column() { + Text('current countInitValue is: ' + this.countInitValue) + .fontSize(20) + Text('current playingInitValue is: ' + this.playingInitValue) + .fontSize(20) + Button("Click to open Dialog -1") + .onClick(() => { + this.countInitValue--; + this.dialogController.open() + }) + Button("Click to close Dialog +1") + .onClick(() => { + this.countInitValue++; + this.dialogController.close() + }) + } + } +} +` + +exports.expectResult = +`"use strict"; +class DialogExample extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.__count = new SynchedPropertySimpleOneWayPU(params.count, this, "count"); + this.__isPlaying = new SynchedPropertySimpleTwoWayPU(params.isPlaying, this, "isPlaying"); + this.controller = undefined; + this.termsToAccept = ""; + this.action1 = undefined; + this.action2 = undefined; + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + if (params.controller !== undefined) { + this.controller = params.controller; + } + if (params.termsToAccept !== undefined) { + this.termsToAccept = params.termsToAccept; + } + if (params.action1 !== undefined) { + this.action1 = params.action1; + } + if (params.action2 !== undefined) { + this.action2 = params.action2; + } + } + updateStateVars(params) { + this.__count.reset(params.count); + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + this.__count.purgeDependencyOnElmtId(rmElmtId); + this.__isPlaying.purgeDependencyOnElmtId(rmElmtId); + } + aboutToBeDeleted() { + this.__count.aboutToBeDeleted(); + this.__isPlaying.aboutToBeDeleted(); + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + get count() { + return this.__count.get(); + } + set count(newValue) { + this.__count.set(newValue); + } + get isPlaying() { + return this.__isPlaying.get(); + } + set isPlaying(newValue) { + this.__isPlaying.set(newValue); + } + setController(ctr) { + this.controller = ctr; + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Column.create(); + if (!isInitialRender) { + Column.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Row.create(); + if (!isInitialRender) { + Row.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Button.createWithLabel('current count is: ' + this.count); + Button.onClick(() => { + this.count++; + }); + if (!isInitialRender) { + Button.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Button.pop(); + Row.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Row.create(); + if (!isInitialRender) { + Row.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Button.createWithLabel(this.isPlaying ? 'play' : 'pause'); + Button.onClick(() => { + this.isPlaying = !this.isPlaying; + }); + if (!isInitialRender) { + Button.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Button.pop(); + Row.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Row.create(); + if (!isInitialRender) { + Row.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Button.createWithLabel("Option A"); + Button.onClick(() => { + this.controller.close(); + this.action1(); + }); + if (!isInitialRender) { + Button.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Button.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Button.createWithLabel("Option B"); + Button.onClick(() => { + this.controller.close(); + this.action2(47, "Option B is great choice"); + }); + if (!isInitialRender) { + Button.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Button.pop(); + Row.pop(); + Column.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +class CustomDialogUser extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.__countInitValue = new ObservedPropertySimplePU(10, this, "countInitValue"); + this.__playingInitValue = new ObservedPropertySimplePU(false, this, "playingInitValue"); + this.dialogController = new CustomDialogController({ + builder: () => { + let jsDialog = new DialogExample(this, { + termsToAccept: "Please accept the terms.", + action1: this.onAccept, + action2: this.existApp, + count: this.countInitValue, + isPlaying: this.__playingInitValue + }); + jsDialog.setController(this.dialogController); + ViewPU.create(jsDialog); + }, + cancel: this.existApp, + autoCancel: false + }, this); + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + if (params.countInitValue !== undefined) { + this.countInitValue = params.countInitValue; + } + if (params.playingInitValue !== undefined) { + this.playingInitValue = params.playingInitValue; + } + if (params.dialogController !== undefined) { + this.dialogController = params.dialogController; + } + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + this.__countInitValue.purgeDependencyOnElmtId(rmElmtId); + this.__playingInitValue.purgeDependencyOnElmtId(rmElmtId); + } + aboutToBeDeleted() { + this.__countInitValue.aboutToBeDeleted(); + this.__playingInitValue.aboutToBeDeleted(); + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + get countInitValue() { + return this.__countInitValue.get(); + } + set countInitValue(newValue) { + this.__countInitValue.set(newValue); + } + get playingInitValue() { + return this.__playingInitValue.get(); + } + set playingInitValue(newValue) { + this.__playingInitValue.set(newValue); + } + onAccept() { + console.log("onAccept"); + } + existApp() { + console.log("Cancel dialog!"); + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Column.create(); + if (!isInitialRender) { + Column.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create('current countInitValue is: ' + this.countInitValue); + Text.fontSize(20); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create('current playingInitValue is: ' + this.playingInitValue); + Text.fontSize(20); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Button.createWithLabel("Click to open Dialog -1"); + Button.onClick(() => { + this.countInitValue--; + this.dialogController.open(); + }); + if (!isInitialRender) { + Button.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Button.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Button.createWithLabel("Click to close Dialog +1"); + Button.onClick(() => { + this.countInitValue++; + this.dialogController.close(); + }); + if (!isInitialRender) { + Button.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Button.pop(); + Column.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +ViewStackProcessor.StartGetAccessRecordingFor(ViewStackProcessor.AllocateNewElmetIdForNextComponent()); +loadDocument(new CustomDialogUser(undefined, {})); +ViewStackProcessor.StopGetAccessRecording(); +` diff --git a/compiler/test/utForPartialUpdate/render_decorator/@extend/@extend.ts b/compiler/test/utForPartialUpdate/render_decorator/@extend/@extend.ts new file mode 100644 index 0000000000000000000000000000000000000000..277c6df189ee1c74dbe13bc991ee5f9580fb1b8d --- /dev/null +++ b/compiler/test/utForPartialUpdate/render_decorator/@extend/@extend.ts @@ -0,0 +1,166 @@ +/* + * Copyright (c) 2022 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. + */ + +exports.source = ` +@Extend Text.fancy(color:string){ + .backgroundColor(color) +} + +@Extend Text.superFancy(size:number){ + .fontSize(size) + .fancy(Color.Red) +} + +@Extend(Button) function fancybut(color:string|Color){ + .backgroundColor(color) + .width(200) + .height(100) +} + +@Entry +@Component +struct FancyUse { + build() { + Column(){ + Row() { + Text("Just Fancy").fancy(Color.Yellow) + Text("Super Fancy Text").superFancy(24) + Button("Fancy Button").fancybut(Color.Green) + } + Row({ space: 10 }) { + Text("Fancy") + .fancytext(24) + } + } + } +} + +@Extend(Text) function fancytext(fontSize: number) { + .fontColor(Color.Red) + .fontSize(fontSize) + .fontStyle(FontStyle.Italic) +} +` +exports.expectResult = +`"use strict"; +function __Text__fancy(color) { + Text.backgroundColor(color); +} +function __Text__superFancy(size) { + Text.fontSize(size); + __Text__fancy(Color.Red); +} +function __Button__fancybut(color) { + Button.backgroundColor(color); + Button.width(200); + Button.height(100); +} +class FancyUse extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + } + aboutToBeDeleted() { + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Column.create(); + if (!isInitialRender) { + Column.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Row.create(); + if (!isInitialRender) { + Row.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create("Just Fancy"); + __Text__fancy(Color.Yellow); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create("Super Fancy Text"); + __Text__superFancy(24); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Button.createWithLabel("Fancy Button"); + __Button__fancybut(Color.Green); + if (!isInitialRender) { + Button.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Button.pop(); + Row.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Row.create({ space: 10 }); + if (!isInitialRender) { + Row.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create("Fancy"); + __Text__fancytext(24); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + Row.pop(); + Column.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +function __Text__fancytext(fontSize) { + Text.fontColor(Color.Red); + Text.fontSize(fontSize); + Text.fontStyle(FontStyle.Italic); +} +ViewStackProcessor.StartGetAccessRecordingFor(ViewStackProcessor.AllocateNewElmetIdForNextComponent()); +loadDocument(new FancyUse(undefined, {})); +ViewStackProcessor.StopGetAccessRecording(); +` diff --git a/compiler/test/utForPartialUpdate/render_decorator/@preview/@preview.ts b/compiler/test/utForPartialUpdate/render_decorator/@preview/@preview.ts new file mode 100644 index 0000000000000000000000000000000000000000..e04a568556d7d3b97b9cc646c5be8cdcae9e5fbd --- /dev/null +++ b/compiler/test/utForPartialUpdate/render_decorator/@preview/@preview.ts @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2022 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. + */ + +exports.source = ` +@Entry +@Component +struct HomePreviewComponent { + private value: string = "hello world" + + build() { + Text(this.value) + .fontSize(50) + } +} + +@Preview +@Component +struct HomePreviewComponent_Preview { + build() { + Column() { + HomePreviewComponent(); + } + } +} +` + +exports.expectResult = +`"use strict"; +class HomePreviewComponent extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.value = "hello world"; + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + if (params.value !== undefined) { + this.value = params.value; + } + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + } + aboutToBeDeleted() { + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create(this.value); + Text.fontSize(50); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +class HomePreviewComponent_Preview extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + } + aboutToBeDeleted() { + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Column.create(); + if (!isInitialRender) { + Column.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + if (isInitialRender) { + ViewPU.create(new HomePreviewComponent(this, {}, undefined, elmtId)); + } + else { + this.updateStateVarsOfChildByElmtId(elmtId, {}); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + } + Column.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +ViewStackProcessor.StartGetAccessRecordingFor(ViewStackProcessor.AllocateNewElmetIdForNextComponent()); +loadDocument(new HomePreviewComponent(undefined, {})); +ViewStackProcessor.StopGetAccessRecording(); +` diff --git a/compiler/test/utForPartialUpdate/render_decorator/@styles/@styles.ts b/compiler/test/utForPartialUpdate/render_decorator/@styles/@styles.ts new file mode 100644 index 0000000000000000000000000000000000000000..8f96dc319683c408aa03efc7a1d1abad7c0567db --- /dev/null +++ b/compiler/test/utForPartialUpdate/render_decorator/@styles/@styles.ts @@ -0,0 +1,156 @@ +/* + * Copyright (c) 2022 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. + */ + +exports.source = ` +@Styles function globalFancy() { + .backgroundColor(Color.Red) +} + +@Entry +@Component +struct FancyUse { + @State enable: boolean = true + @Styles componentFancy() { + .backgroundColor(Color.Blue) + } + build() { + Column({ space: 10 }) { + Text("Fancy") + .globalFancy() + .width(100) + .height(100) + Text("Fancy") + .componentFancy() + .width(100) + .height(100) + Button() { + Text("Fancy") + } + .enabled(this.enable) + .onClick(() => { + this.enable = false + }) + .stateStyles({ + normal: { + .backgroundColor(Color.Green) + }, + disabled: this.componentFancy, + pressed: globalFancy + }) + } + } +}` + +exports.expectResult = +`"use strict"; +class FancyUse extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.__enable = new ObservedPropertySimplePU(true, this, "enable"); + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + if (params.enable !== undefined) { + this.enable = params.enable; + } + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + this.__enable.purgeDependencyOnElmtId(rmElmtId); + } + aboutToBeDeleted() { + this.__enable.aboutToBeDeleted(); + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + get enable() { + return this.__enable.get(); + } + set enable(newValue) { + this.__enable.set(newValue); + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Column.create({ space: 10 }); + if (!isInitialRender) { + Column.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create("Fancy"); + Text.backgroundColor(Color.Red); + Text.width(100); + Text.height(100); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create("Fancy"); + Text.backgroundColor(Color.Blue); + Text.width(100); + Text.height(100); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Button.createWithChild(); + Button.enabled(this.enable); + Button.onClick(() => { + this.enable = false; + }); + ViewStackProcessor.visualState("normal"); + Button.backgroundColor(Color.Green); + ViewStackProcessor.visualState("disabled"); + Button.backgroundColor(Color.Blue); + ViewStackProcessor.visualState("pressed"); + Button.backgroundColor(Color.Red); + ViewStackProcessor.visualState(); + if (!isInitialRender) { + Button.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create("Fancy"); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + Button.pop(); + Column.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +ViewStackProcessor.StartGetAccessRecordingFor(ViewStackProcessor.AllocateNewElmetIdForNextComponent()); +loadDocument(new FancyUse(undefined, {})); +ViewStackProcessor.StopGetAccessRecording(); +` diff --git a/compiler/test/utForPartialUpdate/render_decorator/@styles/@stylesExport.ts b/compiler/test/utForPartialUpdate/render_decorator/@styles/@stylesExport.ts new file mode 100644 index 0000000000000000000000000000000000000000..1388e7fbe8f6eb54d8f1d478207235bdd3dcbb57 --- /dev/null +++ b/compiler/test/utForPartialUpdate/render_decorator/@styles/@stylesExport.ts @@ -0,0 +1,160 @@ +/* + * Copyright (c) 2022 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. + */ + +exports.source = ` +@Styles function globalFancy() { + .backgroundColor(Color.Red) +} + +@Entry +@Component +export struct FancyUseExp { + @State enable: boolean = true + @Styles componentFancy() { + .backgroundColor(Color.Blue) + } + build() { + Column({ space: 10 }) { + Text("Fancy") + .globalFancy() + .width(100) + .height(100) + Text("Fancy") + .componentFancy() + .width(100) + .height(100) + Button() { + Text("Fancy") + } + .enabled(this.enable) + .onClick(() => { + this.enable = false + }) + .stateStyles({ + normal: { + .backgroundColor(Color.Green) + }, + disabled: this.componentFancy, + pressed: globalFancy + }) + } + } +} +` + +exports.expectResult = +`"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FancyUseExp = void 0; +class FancyUseExp extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.__enable = new ObservedPropertySimplePU(true, this, "enable"); + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + if (params.enable !== undefined) { + this.enable = params.enable; + } + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + this.__enable.purgeDependencyOnElmtId(rmElmtId); + } + aboutToBeDeleted() { + this.__enable.aboutToBeDeleted(); + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + get enable() { + return this.__enable.get(); + } + set enable(newValue) { + this.__enable.set(newValue); + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Column.create({ space: 10 }); + if (!isInitialRender) { + Column.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create("Fancy"); + Text.backgroundColor(Color.Red); + Text.width(100); + Text.height(100); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create("Fancy"); + Text.backgroundColor(Color.Blue); + Text.width(100); + Text.height(100); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Button.createWithChild(); + Button.enabled(this.enable); + Button.onClick(() => { + this.enable = false; + }); + ViewStackProcessor.visualState("normal"); + Button.backgroundColor(Color.Green); + ViewStackProcessor.visualState("disabled"); + Button.backgroundColor(Color.Blue); + ViewStackProcessor.visualState("pressed"); + Button.backgroundColor(Color.Red); + ViewStackProcessor.visualState(); + if (!isInitialRender) { + Button.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create("Fancy"); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + Button.pop(); + Column.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +exports.FancyUseExp = FancyUseExp; +ViewStackProcessor.StartGetAccessRecordingFor(ViewStackProcessor.AllocateNewElmetIdForNextComponent()); +loadDocument(new FancyUseExp(undefined, {})); +ViewStackProcessor.StopGetAccessRecording(); +` diff --git a/compiler/test/utForPartialUpdate/ui_state_management/application_state_management/@storageLink/@storageLink.ts b/compiler/test/utForPartialUpdate/ui_state_management/application_state_management/@storageLink/@storageLink.ts new file mode 100644 index 0000000000000000000000000000000000000000..1c054fd1267ef137b9f02f837e3c08620a2d3dc8 --- /dev/null +++ b/compiler/test/utForPartialUpdate/ui_state_management/application_state_management/@storageLink/@storageLink.ts @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2022 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. + */ + +exports.source = ` +let varA = AppStorage.Link('varA') +let envLang = AppStorage.Prop('languageCode') + +@Entry +@Component +struct MyComponent { + @StorageLink('varA') varA: number = 2 + @StorageProp('languageCode') lang: string = 'en' + private label: string = 'count' + + private aboutToAppear() { + this.label = (this.lang === 'zh') ? '数' : 'Count' + } + + build() { + Row({ space: 20 }) { + Button(this.label + ': ' + this.varA) + .onClick(() => { + AppStorage.Set('varA', AppStorage.Get('varA') + 1) + }) + Button('lang: ' + this.lang) + .onClick(() => { + if (this.lang === 'zh') { + AppStorage.Set('languageCode', 'en') + } else { + AppStorage.Set('languageCode', 'zh') + } + this.label = (this.lang === 'zh') ? '数' : 'Count' + }) + } + } +} +` +exports.expectResult = +`"use strict"; +let varA = AppStorage.Link('varA'); +let envLang = AppStorage.Prop('languageCode'); +class MyComponent extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.__varA = this.createStorageLink('varA', 2, "varA"); + this.__lang = this.createStorageProp('languageCode', 'en', "lang"); + this.label = 'count'; + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + if (params.label !== undefined) { + this.label = params.label; + } + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + } + aboutToBeDeleted() { + this.__varA.aboutToBeDeleted(); + this.__lang.aboutToBeDeleted(); + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + get varA() { + return this.__varA.get(); + } + set varA(newValue) { + this.__varA.set(newValue); + } + get lang() { + return this.__lang.get(); + } + set lang(newValue) { + this.__lang.set(newValue); + } + aboutToAppear() { + this.label = (this.lang === 'zh') ? '数' : 'Count'; + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Row.create({ space: 20 }); + if (!isInitialRender) { + Row.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Button.createWithLabel(this.label + ': ' + this.varA); + Button.onClick(() => { + AppStorage.Set('varA', AppStorage.Get('varA') + 1); + }); + if (!isInitialRender) { + Button.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Button.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Button.createWithLabel('lang: ' + this.lang); + Button.onClick(() => { + if (this.lang === 'zh') { + AppStorage.Set('languageCode', 'en'); + } + else { + AppStorage.Set('languageCode', 'zh'); + } + this.label = (this.lang === 'zh') ? '数' : 'Count'; + }); + if (!isInitialRender) { + Button.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Button.pop(); + Row.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +ViewStackProcessor.StartGetAccessRecordingFor(ViewStackProcessor.AllocateNewElmetIdForNextComponent()); +loadDocument(new MyComponent(undefined, {})); +ViewStackProcessor.StopGetAccessRecording(); +` diff --git a/compiler/test/utForPartialUpdate/ui_state_management/application_state_management/@storageProp/@storageProp.ts b/compiler/test/utForPartialUpdate/ui_state_management/application_state_management/@storageProp/@storageProp.ts new file mode 100644 index 0000000000000000000000000000000000000000..1c054fd1267ef137b9f02f837e3c08620a2d3dc8 --- /dev/null +++ b/compiler/test/utForPartialUpdate/ui_state_management/application_state_management/@storageProp/@storageProp.ts @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2022 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. + */ + +exports.source = ` +let varA = AppStorage.Link('varA') +let envLang = AppStorage.Prop('languageCode') + +@Entry +@Component +struct MyComponent { + @StorageLink('varA') varA: number = 2 + @StorageProp('languageCode') lang: string = 'en' + private label: string = 'count' + + private aboutToAppear() { + this.label = (this.lang === 'zh') ? '数' : 'Count' + } + + build() { + Row({ space: 20 }) { + Button(this.label + ': ' + this.varA) + .onClick(() => { + AppStorage.Set('varA', AppStorage.Get('varA') + 1) + }) + Button('lang: ' + this.lang) + .onClick(() => { + if (this.lang === 'zh') { + AppStorage.Set('languageCode', 'en') + } else { + AppStorage.Set('languageCode', 'zh') + } + this.label = (this.lang === 'zh') ? '数' : 'Count' + }) + } + } +} +` +exports.expectResult = +`"use strict"; +let varA = AppStorage.Link('varA'); +let envLang = AppStorage.Prop('languageCode'); +class MyComponent extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.__varA = this.createStorageLink('varA', 2, "varA"); + this.__lang = this.createStorageProp('languageCode', 'en', "lang"); + this.label = 'count'; + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + if (params.label !== undefined) { + this.label = params.label; + } + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + } + aboutToBeDeleted() { + this.__varA.aboutToBeDeleted(); + this.__lang.aboutToBeDeleted(); + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + get varA() { + return this.__varA.get(); + } + set varA(newValue) { + this.__varA.set(newValue); + } + get lang() { + return this.__lang.get(); + } + set lang(newValue) { + this.__lang.set(newValue); + } + aboutToAppear() { + this.label = (this.lang === 'zh') ? '数' : 'Count'; + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Row.create({ space: 20 }); + if (!isInitialRender) { + Row.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Button.createWithLabel(this.label + ': ' + this.varA); + Button.onClick(() => { + AppStorage.Set('varA', AppStorage.Get('varA') + 1); + }); + if (!isInitialRender) { + Button.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Button.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Button.createWithLabel('lang: ' + this.lang); + Button.onClick(() => { + if (this.lang === 'zh') { + AppStorage.Set('languageCode', 'en'); + } + else { + AppStorage.Set('languageCode', 'zh'); + } + this.label = (this.lang === 'zh') ? '数' : 'Count'; + }); + if (!isInitialRender) { + Button.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Button.pop(); + Row.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +ViewStackProcessor.StartGetAccessRecordingFor(ViewStackProcessor.AllocateNewElmetIdForNextComponent()); +loadDocument(new MyComponent(undefined, {})); +ViewStackProcessor.StopGetAccessRecording(); +` diff --git a/compiler/test/utForPartialUpdate/ui_state_management/application_state_management/appStorage/appStorage.ts b/compiler/test/utForPartialUpdate/ui_state_management/application_state_management/appStorage/appStorage.ts new file mode 100644 index 0000000000000000000000000000000000000000..1c054fd1267ef137b9f02f837e3c08620a2d3dc8 --- /dev/null +++ b/compiler/test/utForPartialUpdate/ui_state_management/application_state_management/appStorage/appStorage.ts @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2022 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. + */ + +exports.source = ` +let varA = AppStorage.Link('varA') +let envLang = AppStorage.Prop('languageCode') + +@Entry +@Component +struct MyComponent { + @StorageLink('varA') varA: number = 2 + @StorageProp('languageCode') lang: string = 'en' + private label: string = 'count' + + private aboutToAppear() { + this.label = (this.lang === 'zh') ? '数' : 'Count' + } + + build() { + Row({ space: 20 }) { + Button(this.label + ': ' + this.varA) + .onClick(() => { + AppStorage.Set('varA', AppStorage.Get('varA') + 1) + }) + Button('lang: ' + this.lang) + .onClick(() => { + if (this.lang === 'zh') { + AppStorage.Set('languageCode', 'en') + } else { + AppStorage.Set('languageCode', 'zh') + } + this.label = (this.lang === 'zh') ? '数' : 'Count' + }) + } + } +} +` +exports.expectResult = +`"use strict"; +let varA = AppStorage.Link('varA'); +let envLang = AppStorage.Prop('languageCode'); +class MyComponent extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.__varA = this.createStorageLink('varA', 2, "varA"); + this.__lang = this.createStorageProp('languageCode', 'en', "lang"); + this.label = 'count'; + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + if (params.label !== undefined) { + this.label = params.label; + } + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + } + aboutToBeDeleted() { + this.__varA.aboutToBeDeleted(); + this.__lang.aboutToBeDeleted(); + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + get varA() { + return this.__varA.get(); + } + set varA(newValue) { + this.__varA.set(newValue); + } + get lang() { + return this.__lang.get(); + } + set lang(newValue) { + this.__lang.set(newValue); + } + aboutToAppear() { + this.label = (this.lang === 'zh') ? '数' : 'Count'; + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Row.create({ space: 20 }); + if (!isInitialRender) { + Row.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Button.createWithLabel(this.label + ': ' + this.varA); + Button.onClick(() => { + AppStorage.Set('varA', AppStorage.Get('varA') + 1); + }); + if (!isInitialRender) { + Button.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Button.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Button.createWithLabel('lang: ' + this.lang); + Button.onClick(() => { + if (this.lang === 'zh') { + AppStorage.Set('languageCode', 'en'); + } + else { + AppStorage.Set('languageCode', 'zh'); + } + this.label = (this.lang === 'zh') ? '数' : 'Count'; + }); + if (!isInitialRender) { + Button.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Button.pop(); + Row.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +ViewStackProcessor.StartGetAccessRecordingFor(ViewStackProcessor.AllocateNewElmetIdForNextComponent()); +loadDocument(new MyComponent(undefined, {})); +ViewStackProcessor.StopGetAccessRecording(); +` diff --git a/compiler/test/utForPartialUpdate/ui_state_management/application_state_management/localStorage/localStorage.ts b/compiler/test/utForPartialUpdate/ui_state_management/application_state_management/localStorage/localStorage.ts new file mode 100644 index 0000000000000000000000000000000000000000..daaaeb1b40ed5f2e29dd9210c4b9d252d8553772 --- /dev/null +++ b/compiler/test/utForPartialUpdate/ui_state_management/application_state_management/localStorage/localStorage.ts @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2022 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. + */ + +exports.source = ` +let storage = LocalStorage.GetShared(); + +class ClassA { + public id: number = 1; + public type: number = 2; + public a: string = "aaa"; + constructor(a: string){ + this.a = a; + } +} + +@Entry(storage) +@Component +struct LocalStorageComponent { + @LocalStorageLink("storageSimpleProp") simpleVarName: number = 0; + @LocalStorageProp("storageObjectProp") objectName: ClassA = new ClassA("x"); + build() { + Column() { + Text(this.objectName.a) + .onClick(()=>{ + this.simpleVarName +=1; + this.objectName.a = this.objectName.a === 'x' ? 'yex' : 'no'; + }) + } + .height(500) + } +} +` +exports.expectResult = +`"use strict"; +let storage = LocalStorage.GetShared(); +class ClassA { + constructor(a) { + this.id = 1; + this.type = 2; + this.a = "aaa"; + this.a = a; + } +} +class LocalStorageComponent extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.__simpleVarName = this.createLocalStorageLink("storageSimpleProp", 0, "simpleVarName"); + this.__objectName = this.createLocalStorageProp("storageObjectProp", new ClassA("x"), "objectName"); + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + } + aboutToBeDeleted() { + this.__simpleVarName.aboutToBeDeleted(); + this.__objectName.aboutToBeDeleted(); + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + get simpleVarName() { + return this.__simpleVarName.get(); + } + set simpleVarName(newValue) { + this.__simpleVarName.set(newValue); + } + get objectName() { + return this.__objectName.get(); + } + set objectName(newValue) { + this.__objectName.set(newValue); + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Column.create(); + Column.height(500); + if (!isInitialRender) { + Column.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create(this.objectName.a); + Text.onClick(() => { + this.simpleVarName += 1; + this.objectName.a = this.objectName.a === 'x' ? 'yex' : 'no'; + }); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + Column.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +ViewStackProcessor.StartGetAccessRecordingFor(ViewStackProcessor.AllocateNewElmetIdForNextComponent()); +loadDocument(new LocalStorageComponent(undefined, {}, storage)); +ViewStackProcessor.StopGetAccessRecording(); +` diff --git a/compiler/test/utForPartialUpdate/ui_state_management/inner_struct_state_management/@link/@link.ts b/compiler/test/utForPartialUpdate/ui_state_management/inner_struct_state_management/@link/@link.ts index aaef837eb2aa12496968b1935a95a03d59eda6b7..b4715466e2761cbe5f04f13b4d7eb3350dc894a4 100644 --- a/compiler/test/utForPartialUpdate/ui_state_management/inner_struct_state_management/@link/@link.ts +++ b/compiler/test/utForPartialUpdate/ui_state_management/inner_struct_state_management/@link/@link.ts @@ -36,13 +36,15 @@ struct ParentComponent { exports.expectResult = `"use strict"; class LinkComponent extends ViewPU { - constructor(parent, params, __localStorage) { - super(parent, __localStorage); + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); this.__counter = new SynchedPropertySimpleTwoWayPU(params.counter, this, "counter"); this.setInitiallyProvidedValue(params); } setInitiallyProvidedValue(params) { } + updateStateVars(params) { + } purgeVariableDependenciesOnElmtId(rmElmtId) { this.__counter.purgeDependencyOnElmtId(rmElmtId); } @@ -69,13 +71,12 @@ class LinkComponent extends ViewPU { Text.pop(); } rerender() { - this.__counter.markDependentElementsDirty(this); this.updateDirtyElements(); } } class ParentComponent extends ViewPU { - constructor(parent, params, __localStorage) { - super(parent, __localStorage); + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); this.__value = new ObservedPropertySimplePU('first init content', this, "value"); this.setInitiallyProvidedValue(params); } @@ -84,6 +85,8 @@ class ParentComponent extends ViewPU { this.value = params.value; } } + updateStateVars(params) { + } purgeVariableDependenciesOnElmtId(rmElmtId) { this.__value.purgeDependencyOnElmtId(rmElmtId); } @@ -108,15 +111,20 @@ class ParentComponent extends ViewPU { ViewStackProcessor.StopGetAccessRecording(); }); { - const elmtId = ViewStackProcessor.AllocateNewElmetIdForNextComponent(); - ViewStackProcessor.StartGetAccessRecordingFor(elmtId); - ViewPU.create(new LinkComponent(this, { counter: this.__value })); - ViewStackProcessor.StopGetAccessRecording(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + if (isInitialRender) { + ViewPU.create(new LinkComponent(this, { counter: this.__value }, undefined, elmtId)); + } + else { + this.updateStateVarsOfChildByElmtId(elmtId, {}); + } + ViewStackProcessor.StopGetAccessRecording(); + }); } Column.pop(); } rerender() { - this.__value.markDependentElementsDirty(this); this.updateDirtyElements(); } } diff --git a/compiler/test/utForPartialUpdate/ui_state_management/inner_struct_state_management/@objectLink/@objectLink.ts b/compiler/test/utForPartialUpdate/ui_state_management/inner_struct_state_management/@objectLink/@objectLink.ts index 1b92a8899daed1bb38cef68ce5bc195b6d5e3111..c519833ccb86d184a110a9066bee656220d06728 100644 --- a/compiler/test/utForPartialUpdate/ui_state_management/inner_struct_state_management/@objectLink/@objectLink.ts +++ b/compiler/test/utForPartialUpdate/ui_state_management/inner_struct_state_management/@objectLink/@objectLink.ts @@ -72,14 +72,17 @@ Model = __decorate([ Observed ], Model); class CustomText extends ViewPU { - constructor(parent, params, __localStorage) { - super(parent, __localStorage); + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); this.__model = new SynchedPropertyNesedObjectPU(params.model, this, "model"); this.setInitiallyProvidedValue(params); } setInitiallyProvidedValue(params) { this.__model.set(params.model); } + updateStateVars(params) { + this.__model.set(params.model); + } purgeVariableDependenciesOnElmtId(rmElmtId) { this.__model.purgeDependencyOnElmtId(rmElmtId); } @@ -112,13 +115,12 @@ class CustomText extends ViewPU { Row.pop(); } rerender() { - this.__model.markDependentElementsDirty(this); this.updateDirtyElements(); } } class Parent extends ViewPU { - constructor(parent, params, __localStorage) { - super(parent, __localStorage); + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); this.nextId = 1; this.__models = new ObservedPropertyObjectPU([new Model('0', '#ffffff'), new Model('1', '#fff456')], this, "models"); this.setInitiallyProvidedValue(params); @@ -131,11 +133,12 @@ class Parent extends ViewPU { this.models = params.models; } } + updateStateVars(params) { + } purgeVariableDependenciesOnElmtId(rmElmtId) { this.__models.purgeDependencyOnElmtId(rmElmtId); } aboutToBeDeleted() { - this.nextId = undefined; this.__models.aboutToBeDeleted(); SubscriberManager.Get().delete(this.id__()); this.aboutToBeDeletedInternal(); @@ -161,14 +164,21 @@ class Parent extends ViewPU { const forEachItemGenFunction = _item => { const item = _item; { - const elmtId = ViewStackProcessor.AllocateNewElmetIdForNextComponent(); - ViewStackProcessor.StartGetAccessRecordingFor(elmtId); - ViewPU.create(new CustomText(this, { model: item })); - ViewStackProcessor.StopGetAccessRecording(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + if (isInitialRender) { + ViewPU.create(new CustomText(this, { model: item }, undefined, elmtId)); + } + else { + this.updateStateVarsOfChildByElmtId(elmtId, { + model: item + }); + } + ViewStackProcessor.StopGetAccessRecording(); + }); } }; - const forEachItemIdFunc = item => item.text; - this.forEachUpdateFunction(elmtId, this.models, forEachItemGenFunction, forEachItemIdFunc); + this.forEachUpdateFunction(elmtId, this.models, forEachItemGenFunction, (item) => item.text, false, false); if (!isInitialRender) { ForEach.pop(); } @@ -178,7 +188,6 @@ class Parent extends ViewPU { Column.pop(); } rerender() { - this.__models.markDependentElementsDirty(this); this.updateDirtyElements(); } } diff --git a/compiler/test/utForPartialUpdate/ui_state_management/inner_struct_state_management/@prop/@prop.ts b/compiler/test/utForPartialUpdate/ui_state_management/inner_struct_state_management/@prop/@prop.ts index a74de3a6623df5e588c7627e5390542fb621f7db..1866cba72caa80e4b5892b73371b3b3fe6e68dd4 100644 --- a/compiler/test/utForPartialUpdate/ui_state_management/inner_struct_state_management/@prop/@prop.ts +++ b/compiler/test/utForPartialUpdate/ui_state_management/inner_struct_state_management/@prop/@prop.ts @@ -15,112 +15,132 @@ exports.source = ` @Component -struct PropComponent { - @Prop counter: string - build() { - Text(this.counter) +struct CustomX{ + @Prop fruit:string='香蕉' + build(){ + } } - @Entry @Component -struct ParentComponent { - @State value: string = 'first init content'; +struct CustomY { + @State parentFruit: string = '苹果' build() { - Column() { - PropComponent({counter: this.value}) + Row() { + CustomX({fruit:this.parentFruit}) + CustomX({}) } } } ` exports.expectResult = `"use strict"; -class PropComponent extends ViewPU { - constructor(parent, params, __localStorage) { - super(parent, __localStorage); - this.__counter = new SynchedPropertySimpleOneWayPU(params.counter, this, "counter"); +class CustomX extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.__fruit = new SynchedPropertySimpleOneWayPU(params.fruit, this, "fruit"); this.setInitiallyProvidedValue(params); } setInitiallyProvidedValue(params) { + if (params.fruit !== undefined) { + this.__fruit.set(params.fruit); + } + else { + this.__fruit.set('香蕉'); + } + } + updateStateVars(params) { + this.__fruit.reset(params.fruit); } purgeVariableDependenciesOnElmtId(rmElmtId) { - this.__counter.purgeDependencyOnElmtId(rmElmtId); + this.__fruit.purgeDependencyOnElmtId(rmElmtId); } aboutToBeDeleted() { - this.__counter.aboutToBeDeleted(); + this.__fruit.aboutToBeDeleted(); SubscriberManager.Get().delete(this.id__()); this.aboutToBeDeletedInternal(); } - get counter() { - return this.__counter.get(); + get fruit() { + return this.__fruit.get(); } - set counter(newValue) { - this.__counter.set(newValue); + set fruit(newValue) { + this.__fruit.set(newValue); } initialRender() { - this.observeComponentCreation((elmtId, isInitialRender) => { - ViewStackProcessor.StartGetAccessRecordingFor(elmtId); - Text.create(this.counter); - if (!isInitialRender) { - Text.pop(); - } - ViewStackProcessor.StopGetAccessRecording(); - }); - Text.pop(); } rerender() { - this.__counter.markDependentElementsDirty(this); this.updateDirtyElements(); } } -class ParentComponent extends ViewPU { - constructor(parent, params, __localStorage) { - super(parent, __localStorage); - this.__value = new ObservedPropertySimplePU('first init content', this, "value"); +class CustomY extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.__parentFruit = new ObservedPropertySimplePU('苹果', this, "parentFruit"); this.setInitiallyProvidedValue(params); } setInitiallyProvidedValue(params) { - if (params.value !== undefined) { - this.value = params.value; + if (params.parentFruit !== undefined) { + this.parentFruit = params.parentFruit; } } + updateStateVars(params) { + } purgeVariableDependenciesOnElmtId(rmElmtId) { - this.__value.purgeDependencyOnElmtId(rmElmtId); + this.__parentFruit.purgeDependencyOnElmtId(rmElmtId); } aboutToBeDeleted() { - this.__value.aboutToBeDeleted(); + this.__parentFruit.aboutToBeDeleted(); SubscriberManager.Get().delete(this.id__()); this.aboutToBeDeletedInternal(); } - get value() { - return this.__value.get(); + get parentFruit() { + return this.__parentFruit.get(); } - set value(newValue) { - this.__value.set(newValue); + set parentFruit(newValue) { + this.__parentFruit.set(newValue); } initialRender() { this.observeComponentCreation((elmtId, isInitialRender) => { ViewStackProcessor.StartGetAccessRecordingFor(elmtId); - Column.create(); + Row.create(); if (!isInitialRender) { - Column.pop(); + Row.pop(); } ViewStackProcessor.StopGetAccessRecording(); }); { - const elmtId = ViewStackProcessor.AllocateNewElmetIdForNextComponent(); - ViewStackProcessor.StartGetAccessRecordingFor(elmtId); - ViewPU.create(new PropComponent(this, { counter: this.__value })); - ViewStackProcessor.StopGetAccessRecording(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + if (isInitialRender) { + ViewPU.create(new CustomX(this, { fruit: this.parentFruit }, undefined, elmtId)); + } + else { + this.updateStateVarsOfChildByElmtId(elmtId, { + fruit: this.parentFruit + }); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + } + { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + if (isInitialRender) { + ViewPU.create(new CustomX(this, {}, undefined, elmtId)); + } + else { + this.updateStateVarsOfChildByElmtId(elmtId, {}); + } + ViewStackProcessor.StopGetAccessRecording(); + }); } - Column.pop(); + Row.pop(); } rerender() { - this.__value.markDependentElementsDirty(this); this.updateDirtyElements(); } } ViewStackProcessor.StartGetAccessRecordingFor(ViewStackProcessor.AllocateNewElmetIdForNextComponent()); -loadDocument(new ParentComponent(undefined, {})); +loadDocument(new CustomY(undefined, {})); ViewStackProcessor.StopGetAccessRecording(); ` \ No newline at end of file diff --git a/compiler/test/utForPartialUpdate/ui_state_management/inner_struct_state_management/@prop/@propComplexType.ts b/compiler/test/utForPartialUpdate/ui_state_management/inner_struct_state_management/@prop/@propComplexType.ts new file mode 100644 index 0000000000000000000000000000000000000000..b5a3458b1de8f108b419552e7ccce70bc1e0a41e --- /dev/null +++ b/compiler/test/utForPartialUpdate/ui_state_management/inner_struct_state_management/@prop/@propComplexType.ts @@ -0,0 +1,197 @@ +/* + * Copyright (c) 2022 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. + */ + +exports.source = ` +var nextID: number = 0 + +@Observed +class ClassA { + public name: string + public c: number + public id: number + + constructor(c: number, name: string = 'OK') { + this.name = name + this.c = c + this.id = nextID++ + } +} +@Component +struct CustomX{ + @Prop fruit:ClassA = new ClassA(1) + build(){ + Row() { + Text(JSON.stringify(this.fruit.c)) + } + } +} +@Entry +@Component +struct Index { + @State arrA:ClassA[] = [new ClassA(0), new ClassA(0)]; + build() { + Row() { + CustomX({fruit:this.arrA[0]}) + CustomX({}) + } + } +} +` +exports.expectResult = +`"use strict"; +var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var nextID = 0; +let ClassA = class ClassA { + constructor(c, name = 'OK') { + this.name = name; + this.c = c; + this.id = nextID++; + } +}; +ClassA = __decorate([ + Observed +], ClassA); +class CustomX extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.__fruit = new SynchedPropertyObjectOneWayPU(params.fruit, this, "fruit"); + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + if (params.fruit !== undefined) { + this.__fruit.set(params.fruit); + } + else { + this.__fruit.set(new ClassA(1)); + } + } + updateStateVars(params) { + this.__fruit.reset(params.fruit); + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + this.__fruit.purgeDependencyOnElmtId(rmElmtId); + } + aboutToBeDeleted() { + this.__fruit.aboutToBeDeleted(); + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + get fruit() { + return this.__fruit.get(); + } + set fruit(newValue) { + this.__fruit.set(newValue); + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Row.create(); + if (!isInitialRender) { + Row.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create(JSON.stringify(this.fruit.c)); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + Row.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +class Index extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.__arrA = new ObservedPropertyObjectPU([new ClassA(0), new ClassA(0)], this, "arrA"); + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + if (params.arrA !== undefined) { + this.arrA = params.arrA; + } + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + this.__arrA.purgeDependencyOnElmtId(rmElmtId); + } + aboutToBeDeleted() { + this.__arrA.aboutToBeDeleted(); + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + get arrA() { + return this.__arrA.get(); + } + set arrA(newValue) { + this.__arrA.set(newValue); + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Row.create(); + if (!isInitialRender) { + Row.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + if (isInitialRender) { + ViewPU.create(new CustomX(this, { fruit: this.arrA[0] }, undefined, elmtId)); + } + else { + this.updateStateVarsOfChildByElmtId(elmtId, { + fruit: this.arrA[0] + }); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + } + { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + if (isInitialRender) { + ViewPU.create(new CustomX(this, {}, undefined, elmtId)); + } + else { + this.updateStateVarsOfChildByElmtId(elmtId, {}); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + } + Row.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +ViewStackProcessor.StartGetAccessRecordingFor(ViewStackProcessor.AllocateNewElmetIdForNextComponent()); +loadDocument(new Index(undefined, {})); +ViewStackProcessor.StopGetAccessRecording(); +` \ No newline at end of file diff --git a/compiler/test/utForPartialUpdate/ui_state_management/inner_struct_state_management/@state/@state.ts b/compiler/test/utForPartialUpdate/ui_state_management/inner_struct_state_management/@state/@state.ts index c895d07dc65cb043746fd95b71075e4eb857f835..a6dc74c936ba487a7c920f69885ff1b00f347afd 100644 --- a/compiler/test/utForPartialUpdate/ui_state_management/inner_struct_state_management/@state/@state.ts +++ b/compiler/test/utForPartialUpdate/ui_state_management/inner_struct_state_management/@state/@state.ts @@ -28,8 +28,8 @@ struct StatePage { exports.expectResult = `"use strict"; class StatePage extends ViewPU { - constructor(parent, params, __localStorage) { - super(parent, __localStorage); + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); this.__counter = new ObservedPropertySimplePU(0, this, "counter"); this.setInitiallyProvidedValue(params); } @@ -38,6 +38,8 @@ class StatePage extends ViewPU { this.counter = params.counter; } } + updateStateVars(params) { + } purgeVariableDependenciesOnElmtId(rmElmtId) { this.__counter.purgeDependencyOnElmtId(rmElmtId); } @@ -73,7 +75,6 @@ class StatePage extends ViewPU { Column.pop(); } rerender() { - this.__counter.markDependentElementsDirty(this); this.updateDirtyElements(); } } diff --git a/compiler/test/utForPartialUpdate/ui_state_management/others/@consume_@provide/@consume_@provide.ts b/compiler/test/utForPartialUpdate/ui_state_management/others/@consume_@provide/@consume_@provide.ts new file mode 100644 index 0000000000000000000000000000000000000000..97f905a2e1003958bbdf01850d721c719f5ff26e --- /dev/null +++ b/compiler/test/utForPartialUpdate/ui_state_management/others/@consume_@provide/@consume_@provide.ts @@ -0,0 +1,245 @@ +/* + * Copyright (c) 2022 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. + */ + +exports.source = ` +@Entry +@Component +struct CompA { + @Provide("reviewVote") reviewVotes : number = 0; + + build() { + Column() { + CompB() + Button() { + Text('' + this.reviewVotes) + .fontSize(30) + } + .onClick(() => { + this.reviewVotes += 1; + }) + } + } +} + +@Component +struct CompB { + build() { + Column() { + CompC() + } + } +} + +@Component +struct CompC { + @Consume("reviewVote") reviewVotes : number; + build() { + Column() { + Button() { + Text('' + this.reviewVotes) + .fontSize(30) + } + .onClick(() => { + this.reviewVotes += 1; + }) + } + } +} +` +exports.expectResult = +`"use strict"; +class CompA extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.__reviewVotes = new ObservedPropertySimplePU(0, this, "reviewVotes"); + this.addProvidedVar("reviewVote", this.__reviewVotes); + this.addProvidedVar("reviewVotes", this.__reviewVotes); + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + if (params.reviewVotes !== undefined) { + this.reviewVotes = params.reviewVotes; + } + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + } + aboutToBeDeleted() { + this.__reviewVotes.aboutToBeDeleted(); + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + get reviewVotes() { + return this.__reviewVotes.get(); + } + set reviewVotes(newValue) { + this.__reviewVotes.set(newValue); + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Column.create(); + if (!isInitialRender) { + Column.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + if (isInitialRender) { + ViewPU.create(new CompB(this, {}, undefined, elmtId)); + } + else { + this.updateStateVarsOfChildByElmtId(elmtId, {}); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + } + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Button.createWithChild(); + Button.onClick(() => { + this.reviewVotes += 1; + }); + if (!isInitialRender) { + Button.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create('' + this.reviewVotes); + Text.fontSize(30); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + Button.pop(); + Column.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +class CompB extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + } + aboutToBeDeleted() { + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Column.create(); + if (!isInitialRender) { + Column.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + if (isInitialRender) { + ViewPU.create(new CompC(this, {}, undefined, elmtId)); + } + else { + this.updateStateVarsOfChildByElmtId(elmtId, {}); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + } + Column.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +class CompC extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.__reviewVotes = this.initializeConsume("reviewVote", "reviewVotes"); + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + } + aboutToBeDeleted() { + this.__reviewVotes.aboutToBeDeleted(); + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + get reviewVotes() { + return this.__reviewVotes.get(); + } + set reviewVotes(newValue) { + this.__reviewVotes.set(newValue); + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Column.create(); + if (!isInitialRender) { + Column.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Button.createWithChild(); + Button.onClick(() => { + this.reviewVotes += 1; + }); + if (!isInitialRender) { + Button.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create('' + this.reviewVotes); + Text.fontSize(30); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + Button.pop(); + Column.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +ViewStackProcessor.StartGetAccessRecordingFor(ViewStackProcessor.AllocateNewElmetIdForNextComponent()); +loadDocument(new CompA(undefined, {})); +ViewStackProcessor.StopGetAccessRecording(); +` diff --git a/compiler/test/utForPartialUpdate/ui_state_management/others/@observed_@objectLink/@observed_@objectLink.ts b/compiler/test/utForPartialUpdate/ui_state_management/others/@observed_@objectLink/@observed_@objectLink.ts new file mode 100644 index 0000000000000000000000000000000000000000..b9347bcf462086409de11553f9a47eede7baa89c --- /dev/null +++ b/compiler/test/utForPartialUpdate/ui_state_management/others/@observed_@objectLink/@observed_@objectLink.ts @@ -0,0 +1,209 @@ +/* + * Copyright (c) 2022 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. + */ + +exports.source = ` +let NextID : number = 0; + +@Observed class ClassA { + public id : number; + public c: number; + constructor(c: number) { + this.id = NextID++; + this.c = c; + } +} + +@Observed class ClassB { + public a: ClassA; + constructor(a: ClassA) { + this.a = a; + } +} + +@Component +struct ViewA { + @ObjectLink varA : ClassA; + build() { + Row() { + Text('ViewA-' + this.varA.id) + } + } +} + +@Entry +@Component +struct ViewB { + @State varB : ClassB = new ClassB(new ClassA(0)); + build() { + Column() { + Row() { + ViewA({ varA: this.varB.a }) + Text('ViewB') + } + } + } +} +` +exports.expectResult = +`"use strict"; +var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +let NextID = 0; +let ClassA = class ClassA { + constructor(c) { + this.id = NextID++; + this.c = c; + } +}; +ClassA = __decorate([ + Observed +], ClassA); +let ClassB = class ClassB { + constructor(a) { + this.a = a; + } +}; +ClassB = __decorate([ + Observed +], ClassB); +class ViewA extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.__varA = new SynchedPropertyNesedObjectPU(params.varA, this, "varA"); + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + this.__varA.set(params.varA); + } + updateStateVars(params) { + this.__varA.set(params.varA); + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + this.__varA.purgeDependencyOnElmtId(rmElmtId); + } + aboutToBeDeleted() { + this.__varA.aboutToBeDeleted(); + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + get varA() { + return this.__varA.get(); + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Row.create(); + if (!isInitialRender) { + Row.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create('ViewA-' + this.varA.id); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + Row.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +class ViewB extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.__varB = new ObservedPropertyObjectPU(new ClassB(new ClassA(0)), this, "varB"); + this.setInitiallyProvidedValue(params); + } + setInitiallyProvidedValue(params) { + if (params.varB !== undefined) { + this.varB = params.varB; + } + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + this.__varB.purgeDependencyOnElmtId(rmElmtId); + } + aboutToBeDeleted() { + this.__varB.aboutToBeDeleted(); + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + get varB() { + return this.__varB.get(); + } + set varB(newValue) { + this.__varB.set(newValue); + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Column.create(); + if (!isInitialRender) { + Column.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Row.create(); + if (!isInitialRender) { + Row.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + if (isInitialRender) { + ViewPU.create(new ViewA(this, { varA: this.varB.a }, undefined, elmtId)); + } + else { + this.updateStateVarsOfChildByElmtId(elmtId, { + varA: this.varB.a + }); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + } + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create('ViewB'); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + Row.pop(); + Column.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +ViewStackProcessor.StartGetAccessRecordingFor(ViewStackProcessor.AllocateNewElmetIdForNextComponent()); +loadDocument(new ViewB(undefined, {})); +ViewStackProcessor.StopGetAccessRecording(); +` diff --git a/compiler/test/utForPartialUpdate/ui_state_management/others/@watch/@watch.ts b/compiler/test/utForPartialUpdate/ui_state_management/others/@watch/@watch.ts new file mode 100644 index 0000000000000000000000000000000000000000..cbbe23cb68f276d9f63a353d6133b6ddebf0a91e --- /dev/null +++ b/compiler/test/utForPartialUpdate/ui_state_management/others/@watch/@watch.ts @@ -0,0 +1,220 @@ +/* + * Copyright (c) 2022 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. + */ + +exports.source = ` +@Entry +@Component +struct CompA { + @State @Watch("onBasketUpdated") shopBasket: Array = [ 7, 12, 47, 3 ]; + @State totalPurchase: number = 0; + @State @Watch('onPutItem') defArray: Array = ['c', 'g', 't', 'z']; + @State resultTip: string = ''; + + updateTotal() : number { + let sum = 0; + this.shopBasket.forEach((i) => { sum += i; }); + this.totalPurchase = (sum < 100) ? sum : 0.9 * sum; + return this.totalPurchase; + } + + onBasketUpdated(propName: string) : void { + animateTo({duration: 1000}, () => { + this.updateTotal(); + }) + } + + updateTip() : string { + let tempArray = this.defArray.slice(0, -1); + let addItem = this.defArray[this.defArray.length -1]; + this.resultTip = tempArray.includes(addItem) ? + 'add item invalid' : + 'congratulations! add item success'; + return this.resultTip; + } + + onPutItem(propName: string) : void { + this.updateTip(); + } + + build() { + Column(){ + Button("add to basket").onClick(() => { + this.shopBasket.push(Math.round(100 * Math.random())) + }) + Text('totalPurchase: ' + this.totalPurchase).fontSize(20) + Button("put item").onClick(() => { + let alList = 'abcdefghijklmnopqrstuvwxyz'; + let ranItem = alList[Math.floor(Math.random() * 26)]; + this.defArray.push(ranItem) + }) + Text('tips: ' + this.resultTip).fontSize(20) + } + } +} +` +exports.expectResult = +`"use strict"; +class CompA extends ViewPU { + constructor(parent, params, __localStorage, elmtId = -1) { + super(parent, __localStorage, elmtId); + this.__shopBasket = new ObservedPropertyObjectPU([7, 12, 47, 3], this, "shopBasket"); + this.__totalPurchase = new ObservedPropertySimplePU(0, this, "totalPurchase"); + this.__defArray = new ObservedPropertyObjectPU(['c', 'g', 't', 'z'], this, "defArray"); + this.__resultTip = new ObservedPropertySimplePU('', this, "resultTip"); + this.setInitiallyProvidedValue(params); + this.declareWatch("shopBasket", this.onBasketUpdated); + this.declareWatch("defArray", this.onPutItem); + } + setInitiallyProvidedValue(params) { + if (params.shopBasket !== undefined) { + this.shopBasket = params.shopBasket; + } + if (params.totalPurchase !== undefined) { + this.totalPurchase = params.totalPurchase; + } + if (params.defArray !== undefined) { + this.defArray = params.defArray; + } + if (params.resultTip !== undefined) { + this.resultTip = params.resultTip; + } + } + updateStateVars(params) { + } + purgeVariableDependenciesOnElmtId(rmElmtId) { + this.__shopBasket.purgeDependencyOnElmtId(rmElmtId); + this.__totalPurchase.purgeDependencyOnElmtId(rmElmtId); + this.__defArray.purgeDependencyOnElmtId(rmElmtId); + this.__resultTip.purgeDependencyOnElmtId(rmElmtId); + } + aboutToBeDeleted() { + this.__shopBasket.aboutToBeDeleted(); + this.__totalPurchase.aboutToBeDeleted(); + this.__defArray.aboutToBeDeleted(); + this.__resultTip.aboutToBeDeleted(); + SubscriberManager.Get().delete(this.id__()); + this.aboutToBeDeletedInternal(); + } + get shopBasket() { + return this.__shopBasket.get(); + } + set shopBasket(newValue) { + this.__shopBasket.set(newValue); + } + get totalPurchase() { + return this.__totalPurchase.get(); + } + set totalPurchase(newValue) { + this.__totalPurchase.set(newValue); + } + get defArray() { + return this.__defArray.get(); + } + set defArray(newValue) { + this.__defArray.set(newValue); + } + get resultTip() { + return this.__resultTip.get(); + } + set resultTip(newValue) { + this.__resultTip.set(newValue); + } + updateTotal() { + let sum = 0; + this.shopBasket.forEach((i) => { sum += i; }); + this.totalPurchase = (sum < 100) ? sum : 0.9 * sum; + return this.totalPurchase; + } + onBasketUpdated(propName) { + Context.animateTo({ duration: 1000 }, () => { + this.updateTotal(); + }); + } + updateTip() { + let tempArray = this.defArray.slice(0, -1); + let addItem = this.defArray[this.defArray.length - 1]; + this.resultTip = tempArray.includes(addItem) ? + 'add item invalid' : + 'congratulations! add item success'; + return this.resultTip; + } + onPutItem(propName) { + this.updateTip(); + } + initialRender() { + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Column.create(); + if (!isInitialRender) { + Column.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Button.createWithLabel("add to basket"); + Button.onClick(() => { + this.shopBasket.push(Math.round(100 * Math.random())); + }); + if (!isInitialRender) { + Button.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Button.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create('totalPurchase: ' + this.totalPurchase); + Text.fontSize(20); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Button.createWithLabel("put item"); + Button.onClick(() => { + let alList = 'abcdefghijklmnopqrstuvwxyz'; + let ranItem = alList[Math.floor(Math.random() * 26)]; + this.defArray.push(ranItem); + }); + if (!isInitialRender) { + Button.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Button.pop(); + this.observeComponentCreation((elmtId, isInitialRender) => { + ViewStackProcessor.StartGetAccessRecordingFor(elmtId); + Text.create('tips: ' + this.resultTip); + Text.fontSize(20); + if (!isInitialRender) { + Text.pop(); + } + ViewStackProcessor.StopGetAccessRecording(); + }); + Text.pop(); + Column.pop(); + } + rerender() { + this.updateDirtyElements(); + } +} +ViewStackProcessor.StartGetAccessRecordingFor(ViewStackProcessor.AllocateNewElmetIdForNextComponent()); +loadDocument(new CompA(undefined, {})); +ViewStackProcessor.StopGetAccessRecording(); +` diff --git a/compiler/tsconfig.esm.json b/compiler/tsconfig.esm.json index 0e29e51184350e31dbdb563de4cc5e6176fe55ed..8be10953933ca0820c9a4d7fb048af26b6af0daf 100644 --- a/compiler/tsconfig.esm.json +++ b/compiler/tsconfig.esm.json @@ -1,7 +1,91 @@ { "compileOnSave": false, "compilerOptions": { - "ets": { + "ets": { + "emitDecorators":[ + { + "name":"Entry", + "emitParameters" : true + }, + { + "name":"Component", + "emitParameters" : false + }, + { + "name":"CustomDialog", + "emitParameters" : false + }, + { + "name":"Consume", + "emitParameters" : true + }, + { + "name":"Link", + "emitParameters" : false + }, + { + "name":"LocalStorageLink", + "emitParameters" : true + }, + { + "name":"LocalStorageProp", + "emitParameters" : true + }, + { + "name":"ObjectLink", + "emitParameters" : false + }, + { + "name":"Prop", + "emitParameters" : false + }, + { + "name":"Provide", + "emitParameters" : true + }, + { + "name":"State", + "emitParameters" : false + }, + { + "name":"StorageLink", + "emitParameters" : true + }, + { + "name":"StorageProp", + "emitParameters" : true + }, + { + "name":"Builder", + "emitParameters" : false + }, + { + "name":"BuilderParam", + "emitParameters" : false + }, + { + "name":"Observed", + "emitParameters" : false + } + ], + "propertyDecorators": [ + { + "name": "Link", + "needInitialization": false + }, + { + "name": "Prop", + "needInitialization": false + }, + { + "name": "ObjectLink", + "needInitialization": false + }, + { + "name": "Consume", + "needInitialization": false + } + ], "render": { "method": ["build", "pageTransition"], "decorator": "Builder" @@ -45,6 +129,8 @@ "LoadingProgress", "Marquee", "Menu", + "NavDestination", + "NavRouter", "Navigation", "Navigator", "Option", @@ -96,7 +182,9 @@ "Web", "XComponent", "GridRow", - "GridCol" + "GridCol", + "WaterFlow", + "FlowItem" ], "extend": { "decorator": "Extend", @@ -291,6 +379,16 @@ "type": "MenuAttribute", "instance": "MenuInstance" }, + { + "name": "NavDestination", + "type": "NavDestinationAttribute", + "instance": "NavDestinationInstance" + }, + { + "name": "NavRouter", + "type": "NavRouterAttribute", + "instance": "NavRouterInstance" + }, { "name": "Navigation", "type": "NavigationAttribute", @@ -550,6 +648,16 @@ "name": "GridCol", "type": "GridColAttribute", "instance": "GridColInterface" + }, + { + "name": "WaterFlow", + "type": "WaterFlowAttribute", + "instance": "WaterFlowInterface" + }, + { + "name": "FlowItem", + "type": "FlowItemAttribute", + "instance": "FlowItemInterface" } ] }, @@ -562,12 +670,15 @@ }, "property": "stateStyles" }, + "concurrent": { + "decorator": "Concurrent" + }, "customComponent": "CustomComponent", }, "allowJs": true, "allowSyntheticDefaultImports": true, "esModuleInterop": true, - "importsNotUsedAsValues": "preserve", + "importsNotUsedAsValues": "remove", "noImplicitAny": false, "noUnusedLocals": false, "noUnusedParameters": false, @@ -588,4 +699,4 @@ "exclude": [ "node_modules" ] -} \ No newline at end of file +} diff --git a/compiler/tsconfig.json b/compiler/tsconfig.json index 65cd87bc31fd72b5e0748c80ed65c1cbaa7c4ac0..fffacc7d91f25b6aa66e39cc40bba8778c3eab4a 100644 --- a/compiler/tsconfig.json +++ b/compiler/tsconfig.json @@ -1,7 +1,91 @@ { "compileOnSave": false, "compilerOptions": { - "ets": { + "ets": { + "emitDecorators":[ + { + "name":"Entry", + "emitParameters" : true + }, + { + "name":"Component", + "emitParameters" : false + }, + { + "name":"CustomDialog", + "emitParameters" : false + }, + { + "name":"Consume", + "emitParameters" : true + }, + { + "name":"Link", + "emitParameters" : false + }, + { + "name":"LocalStorageLink", + "emitParameters" : true + }, + { + "name":"LocalStorageProp", + "emitParameters" : true + }, + { + "name":"ObjectLink", + "emitParameters" : false + }, + { + "name":"Prop", + "emitParameters" : false + }, + { + "name":"Provide", + "emitParameters" : true + }, + { + "name":"State", + "emitParameters" : false + }, + { + "name":"StorageLink", + "emitParameters" : true + }, + { + "name":"StorageProp", + "emitParameters" : true + }, + { + "name":"Builder", + "emitParameters" : false + }, + { + "name":"BuilderParam", + "emitParameters" : false + }, + { + "name":"Observed", + "emitParameters" : false + } + ], + "propertyDecorators": [ + { + "name": "Link", + "needInitialization": false + }, + { + "name": "Prop", + "needInitialization": false + }, + { + "name": "ObjectLink", + "needInitialization": false + }, + { + "name": "Consume", + "needInitialization": false + } + ], "render": { "method": ["build", "pageTransition"], "decorator": "Builder" @@ -45,6 +129,10 @@ "LoadingProgress", "Marquee", "Menu", + "MenuItem", + "MenuItemGroup", + "NavDestination", + "NavRouter", "Navigation", "Navigator", "Option", @@ -96,7 +184,9 @@ "Web", "XComponent", "GridRow", - "GridCol" + "GridCol", + "WaterFlow", + "FlowItem" ], "extend": { "decorator": "Extend", @@ -291,6 +381,26 @@ "type": "MenuAttribute", "instance": "MenuInstance" }, + { + "name": "MenuItem", + "type": "MenuItemAttribute", + "instance": "MenuItemInstance" + }, + { + "name": "MenuItemGroup", + "type": "MenuItemGroupAttribute", + "instance": "MenuItemGroupInstance" + }, + { + "name": "NavDestination", + "type": "NavDestinationAttribute", + "instance": "NavDestinationInstance" + }, + { + "name": "NavRouter", + "type": "NavRouterAttribute", + "instance": "NavRouterInstance" + }, { "name": "Navigation", "type": "NavigationAttribute", @@ -550,6 +660,16 @@ "name": "GridCol", "type": "GridColAttribute", "instance": "GridColInterface" + }, + { + "name": "WaterFlow", + "type": "WaterFlowAttribute", + "instance": "WaterFlowInterface" + }, + { + "name": "FlowItem", + "type": "FlowItemAttribute", + "instance": "FlowItemInterface" } ] }, @@ -562,6 +682,9 @@ }, "property": "stateStyles" }, + "concurrent": { + "decorator": "Concurrent" + }, "customComponent": "CustomComponent", }, "allowJs": true, @@ -588,4 +711,4 @@ "exclude": [ "node_modules" ] -} \ No newline at end of file +} diff --git a/compiler/webpack.config.js b/compiler/webpack.config.js index 0dadde6073867eaca8a7da4524d4e2ea7c4376b8..e78c5447604fe919849ce440b408716cb30a6d08 100644 --- a/compiler/webpack.config.js +++ b/compiler/webpack.config.js @@ -19,7 +19,6 @@ const CopyPlugin = require('copy-webpack-plugin'); const Webpack = require('webpack'); const { CleanWebpackPlugin } = require('clean-webpack-plugin'); const { GenAbcPlugin } = require('./lib/gen_abc_plugin'); -const { OHMResolverPlugin } = require('./lib/resolve_ohm_url'); const buildPipeServer = require('./server/build_pipe_server'); const { @@ -30,13 +29,19 @@ const { readWorkerFile, loadModuleInfo, checkAppResourcePath, - addSDKBuildDependencies + addSDKBuildDependencies, + readPatchConfig, + getCleanConfig } = require('./main'); const { ResultStates } = require('./lib/compile_info'); const { processUISyntax } = require('./lib/process_ui_syntax'); -const { IGNORE_ERROR_CODE } = require('./lib/utils'); -const { BUILD_SHARE_PATH } = require('./lib/pre_define'); -const { processJs } = require('./lib/process_js_ast'); +const { + IGNORE_ERROR_CODE, + removeDir, + mkdirsSync, + getResolveModules +} = require('./lib/utils'); +const { BUILD_SHARE_PATH, PREBUILDMODE_JSON } = require('./lib/pre_define'); process.env.watchMode = (process.env.watchMode && process.env.watchMode === 'true') || 'false'; function initConfig(config) { @@ -76,18 +81,16 @@ function initConfig(config) { { loader: 'ts-loader', options: { + reportFiles: ['*.js'], onlyCompileBundledFiles: true, transpileOnly: true, - configFile: path.resolve(__dirname, 'tsconfig.json'), + configFile: path.resolve(__dirname, + projectConfig.compileMode === 'esmodule' ? 'tsconfig.esm.json' : 'tsconfig.json'), getCustomTransformers(program) { let transformerOperation = { before: [processUISyntax(program)], after: [] }; - if (projectConfig.compileMode === 'esmodule' && projectConfig.processTs === false - && process.env.compilerType && process.env.compilerType === 'ark') { - transformerOperation.after.push(processJs(program)); - } return transformerOperation; }, @@ -97,31 +100,15 @@ function initConfig(config) { { loader: path.resolve(__dirname, 'lib/pre_process.js') } ] }, - { - test: /\.js$/, - use: [ - { - loader: 'babel-loader', - options: { - plugins: [ - '@babel/plugin-transform-modules-commonjs', - '@babel/plugin-proposal-class-properties' - ], - compact: false - }, - }, - { loader: path.resolve(__dirname, 'lib/process_js_file.js')}, - { loader: path.resolve(__dirname, 'lib/process_system_module.js') } - ] - } + setJsConfigRule() ] }, node: { global: false }, resolve: { - plugins: [new OHMResolverPlugin()], - extensions: ['.js', '.ets', '.ts', '.d.ts'], + symlinks: projectConfig.compileMode === 'esmodule' ? false : true, + extensions: ['.js', '.ets', '.ts', '.d.ts', '.d.ets'], modules: [ projectPath, './node_modules', @@ -139,29 +126,70 @@ function initConfig(config) { new ResultStates() ] }); + setModuleJsonConfigRule(config); if (!projectConfig.xtsMode) { config.cache = { type: "filesystem", - cacheDirectory: path.resolve(projectConfig.cachePath, '.ets_cache') + cacheDirectory: path.resolve(projectConfig.cachePath, '.ets_cache', + path.basename(projectConfig.projectPath)) }; } if (!projectConfig.aceModuleJsonPath) { - config.resolve.modules.push(path.join(projectPath, '../../../../../')); - config.resolve.modules.push(path.resolve(projectPath, '../../../../node_modules')); - config.resolve.modules.push(path.resolve(projectPath, '../../../../../node_modules')); - config.resolve.modules.push(path.resolve(projectPath, '../../')); + config.resolve.modules.push(...getResolveModules(projectPath, true)); existsPackageJson(config, path.resolve(projectPath, '../../../../../package.json'), path.resolve(projectPath, '../../../../package.json')); } else { - config.resolve.modules.push(path.join(projectPath, '../../../../')); - config.resolve.modules.push(path.resolve(projectPath, '../../../node_modules')); - config.resolve.modules.push(path.resolve(projectPath, '../../../../node_modules')); - config.resolve.modules.push(path.resolve(projectPath, '../')); + config.resolve.modules.push(...getResolveModules(projectPath, false)); existsPackageJson(config, path.resolve(projectPath, '../../../../package.json'), path.resolve(projectPath, '../../../package.json')); } } +function setJsConfigRule() { + const jsRule = { + test: /\.js$/, + use: [ + { loader: path.resolve(__dirname, 'lib/process_source_file.js') }, + { + loader: 'babel-loader', + options: { + plugins: ['@babel/plugin-proposal-class-properties'], + compact: false + } + }, + { loader: path.resolve(__dirname, 'lib/process_system_module.js') } + ] + }; + if (projectConfig.compileMode !== 'esmodule') { + jsRule.type = 'javascript/auto'; + jsRule.use[1].options.plugins.unshift([ + '@babel/plugin-transform-modules-commonjs', + { + 'allowTopLevelThis': true + } + ]); + } else { + jsRule.resolve = { fullySpecified: false }; + } + if (projectConfig.compileHar) { + jsRule.use.unshift({ loader: path.resolve(__dirname, 'lib/process_har_writejs.js')}); + } + return jsRule; +} + +function setModuleJsonConfigRule(config) { + if (projectConfig.compileMode !== 'esmodule') { + return; + } + const jsonRule = { + test: /\.json$/, + use: [ + { loader: path.resolve(__dirname, 'lib/process_source_file.js') } + ] + } + config.module.rules.push(jsonRule); +} + function existsPackageJson(config, rootPackageJsonPath, modulePackageJsonPath) { if (config.cache) { config.cache.buildDependencies = { @@ -199,15 +227,16 @@ function setProjectConfig(envArgs) { if (envArgs.cachePath) { projectConfig.cachePath = envArgs.cachePath; } - if (envArgs.watchMode) { - projectConfig.hotReloadWatch = envArgs.watchMode; + if (envArgs.isPreview === "true") { + projectConfig.isPreview = true; } } function setReleaseConfig(config) { const TerserPlugin = require('terser-webpack-plugin'); config.mode = 'production'; - if (process.env.compileMode !== 'moduleJson' && abilityConfig.abilityType === 'page') { + if ((process.env.compileMode !== 'moduleJson' || projectConfig.splitCommon) && + abilityConfig.abilityType === 'page') { config.optimization = config.optimization; } else { config.optimization = {}; @@ -219,24 +248,35 @@ function setReleaseConfig(config) { minimizer: [new TerserPlugin({ terserOptions: { compress: { + defaults: false, + dead_code: true, + collapse_vars: true, + unused: true, + drop_debugger: true, + if_return: true, + reduce_vars: true, join_vars: false, sequences: 0 }, format: { semicolons: false, beautify: true, + braces: true, indent_level: 2 } } })] }); + config.output.devtoolModuleFilenameTemplate = (info) => { + return `webpack:///${info.absoluteResourcePath.replace(projectConfig.projectRootPath, '')}`; + }; config.output.sourceMapFilename = '_releaseMap/[name].js.map'; config.performance = { hints: false }; } -function setCopyPluginConfig(config) { +function setCopyPluginConfig(config, appResource, isPreview) { const copyPluginPattrens = []; copyPluginPattrens.push({ from: '**/*', @@ -281,6 +321,13 @@ function setCopyPluginConfig(config) { }); } } + if (appResource && fs.existsSync(appResource) && !projectConfig.xtsMode && + isPreview === 'true') { + copyPluginPattrens.push({ + from: path.resolve(__dirname, appResource), + to: path.resolve(__dirname, projectConfig.cachePath) + }); + } config.plugins.push(new CopyPlugin({ patterns: copyPluginPattrens })); } @@ -292,7 +339,8 @@ function excludeWorker(workerFile, name) { } function setOptimizationConfig(config, workerFile) { - if (process.env.compileMode !== 'moduleJson' && abilityConfig.abilityType === 'page') { + if ((process.env.compileMode !== 'moduleJson' || projectConfig.splitCommon) && + abilityConfig.abilityType === 'page') { config.optimization = { splitChunks: { chunks(chunk) { @@ -317,21 +365,6 @@ function setOptimizationConfig(config, workerFile) { } } -function setTsConfigFile() { - let tsconfigTemplate = - path.resolve(__dirname, projectConfig.compileMode === 'esmodule' ? 'tsconfig.esm.json' : 'tsconfig.cjs.json'); - if (fs.existsSync(tsconfigTemplate) && fs.statSync(tsconfigTemplate).isFile()) { - let currentTsconfigFile = path.resolve(__dirname, 'tsconfig.json'); - let tsconfigTemplateNew = - currentTsconfigFile.replace(/.json$/, projectConfig.compileMode === 'esmodule' ? '.cjs.json' : '.esm.json'); - fs.renameSync(currentTsconfigFile, tsconfigTemplateNew); - - let tsconfigFileNew = - tsconfigTemplate.replace(projectConfig.compileMode === 'esmodule' ? /.esm.json$/ : /.cjs.json$/, '.json'); - fs.renameSync(tsconfigTemplate, tsconfigFileNew); - } -} - function setGenAbcPlugin(env, config) { process.env.compilerType = 'ark'; process.env.panda = projectConfig.pandaMode; @@ -352,42 +385,56 @@ function setGenAbcPlugin(env, config) { } function setCleanWebpackPlugin(workerFile, config) { - if (projectConfig.compileMode === 'esmodule') { - return; - } - let cleanPath = []; - cleanPath.push(projectConfig.buildPath); - if (workerFile) { - let workerFilesPath = Object.keys(workerFile); - for (let workerFilePath of workerFilesPath) { - cleanPath.push(path.join(projectConfig.buildPath, workerFilePath, '..')); - } - } - config.plugins.push( new CleanWebpackPlugin({ dry: false, dangerouslyAllowCleanPatternsOutsideProject: true, - cleanOnceBeforeBuildPatterns: cleanPath + cleanOnceBeforeBuildPatterns: getCleanConfig(workerFile) }) ); } +function clearWebpackCacheByBuildMode() { + if (projectConfig.compileMode !== 'esmodule') { + return; + } + + if (!projectConfig.cachePath || projectConfig.xtsMode) { + return; + } + + // clear&update cache dir when buildMode is different from last time + const CACHED_BUILDMODE = path.join(projectConfig.cachePath, PREBUILDMODE_JSON); + if (fs.existsSync(CACHED_BUILDMODE)) { + let cachedBuildMode = undefined; + try { + cachedBuildMode = JSON.parse(fs.readFileSync(CACHED_BUILDMODE).toString()).buildMode; + } catch { + removeDir(projectConfig.cachePath); + mkdirsSync(projectConfig.cachePath); + } + if (cachedBuildMode && cachedBuildMode !== projectConfig.buildArkMode) { + removeDir(projectConfig.cachePath); + mkdirsSync(projectConfig.cachePath); + } + } +} + module.exports = (env, argv) => { const config = {}; setProjectConfig(env); loadEntryObj(projectConfig); loadModuleInfo(projectConfig, env); - setTsConfigFile(); + clearWebpackCacheByBuildMode(); initConfig(config); + readPatchConfig(); const workerFile = readWorkerFile(); setOptimizationConfig(config, workerFile); - setCopyPluginConfig(config); setCleanWebpackPlugin(workerFile, config); if (env.isPreview !== "true") { loadWorker(projectConfig, workerFile); - if (env.compilerType && env.compilerType === 'ark') { + if (env.compilerType && env.compilerType === 'ark' && !projectConfig.compileHar) { setGenAbcPlugin(env, config); } } else { @@ -396,7 +443,7 @@ module.exports = (env, argv) => { setGenAbcPlugin(env, config); let port; process.argv.forEach((val, index) => { - if(val.startsWith('port=')){ + if (val.startsWith('port=')) { port = val.split('=')[1]; } }); @@ -405,16 +452,28 @@ module.exports = (env, argv) => { } } + if (projectConfig.compileHar && env.obfuscate === 'uglify') { + projectConfig.obfuscateHarType = 'uglify'; + } + if (env.sourceMap === 'none') { config.devtool = false; } - if (env.buildMode === 'release') { + if (env.buildMode === 'release' && projectConfig.compileMode !== 'esmodule') { setReleaseConfig(config); } + if (projectConfig.compileMode === 'esmodule' && projectConfig.harNameOhmMap) { + config.externals = []; + for (const harName in projectConfig.harNameOhmMap) { + config.externals.push(RegExp('^(' + harName + ')($|\\/\\S+)')); + } + } + const appResourcePath = env.appResource || process.env.appResource; checkAppResourcePath(appResourcePath, config); + setCopyPluginConfig(config, appResourcePath, env.isPreview); addSDKBuildDependencies(config); config.output.library = projectConfig.hashProjectPath; return config;