diff --git a/.eslintignore b/.eslintignore index a4a23f6ed035..8c511519b182 100644 --- a/.eslintignore +++ b/.eslintignore @@ -3,6 +3,7 @@ dist-h5 lib node_modules *.d.ts +*.ets coverage examples diff --git a/.eslintrc.js b/.eslintrc.js index 2adc439e07cf..7d30eb0d1601 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -1,27 +1,23 @@ module.exports = { parser: '@typescript-eslint/parser', - plugins: [ - '@typescript-eslint', - 'import', - 'jest', - 'react', - 'simple-import-sort', - 'prettier' - ], + plugins: ['@typescript-eslint', 'import', 'jest', 'react', 'simple-import-sort', 'prettier'], extends: [ 'eslint:recommended', 'standard', 'plugin:@typescript-eslint/recommended', 'plugin:react/jsx-runtime', 'plugin:react/recommended', - 'prettier' + 'prettier', ], rules: { '@typescript-eslint/ban-ts-comment': 0, '@typescript-eslint/explicit-function-return-type': 0, '@typescript-eslint/explicit-module-boundary-types': 0, '@typescript-eslint/indent': [2, 2], - '@typescript-eslint/member-delimiter-style': [1, { multiline: { delimiter: 'none' }, singleline: { delimiter: 'comma' } }], + '@typescript-eslint/member-delimiter-style': [ + 1, + { multiline: { delimiter: 'none' }, singleline: { delimiter: 'comma' } }, + ], '@typescript-eslint/no-empty-function': 0, '@typescript-eslint/no-explicit-any': 0, '@typescript-eslint/no-namespace': 0, @@ -31,17 +27,22 @@ module.exports = { '@typescript-eslint/no-use-before-define': [1, { functions: false, classes: false }], '@typescript-eslint/no-var-requires': 0, camelcase: 0, + 'comma-spacing': 2, + 'eol-last': 2, 'import/first': 2, 'import/newline-after-import': 2, 'import/no-duplicates': 2, - indent: 'off', + indent: 0, + 'keyword-spacing': 2, 'no-console': [2, { allow: ['warn', 'error'] }], + 'no-empty': 1, + 'no-multiple-empty-lines': 2, + 'no-multi-spaces': 2, 'no-prototype-builtins': 0, 'no-unused-expressions': 0, 'no-unused-vars': 'off', 'no-use-before-define': 0, 'object-curly-spacing': 2, - 'no-empty': 1, 'prefer-spread': 0, 'prefer-rest-params': 0, 'react/jsx-uses-vars': 1, @@ -51,34 +52,37 @@ module.exports = { 'import/no-named-default': 'off', quotes: [2, 'single', { avoidEscape: true, allowTemplateLiterals: true }], semi: [2, 'never'], - 'simple-import-sort/imports': [2, { - groups: [ - // Side effect imports. - ['^\\u0000'], - // Node.js builtins prefixed with `node:`. - ['^node:'], - // Packages. - // Things that start with a letter (or digit or underscore), or `@` followed by a letter. - ['^@?\\w'], - // Absolute imports and other imports such as Vue-style `@/foo`. - // Anything not matched in another group. - ['^'], - // Relative imports. - // Anything that starts with a dot. - ['^\\.'], - // Types Group - ['^node:.*\\u0000$', '^@?\\w.*\\u0000$', '(?<=\\u0000)$', '^\\..*\\u0000$'], - ] - }], + 'simple-import-sort/imports': [ + 2, + { + groups: [ + // Side effect imports. + ['^\\u0000'], + // Node.js builtins prefixed with `node:`. + ['^node:'], + // Packages. + // Things that start with a letter (or digit or underscore), or `@` followed by a letter. + ['^@?\\w'], + // Absolute imports and other imports such as Vue-style `@/foo`. + // Anything not matched in another group. + ['^'], + // Relative imports. + // Anything that starts with a dot. + ['^\\.'], + // Types Group + ['^node:.*\\u0000$', '^@?\\w.*\\u0000$', '(?<=\\u0000)$', '^\\..*\\u0000$'], + ], + }, + ], 'simple-import-sort/exports': 2, - 'space-before-function-paren': [2, 'always'], - 'standard/no-callback-literal': 0 + 'space-before-function-paren': 0, + 'standard/no-callback-literal': 0, }, env: { 'jest/globals': true, browser: true, node: true, - es6: true + es6: true, }, globals: { testRule: 'readonly', @@ -92,16 +96,16 @@ module.exports = { requirePlugin: 'readonly', jd: 'readonly', ks: 'readonly', - LOCATION_APIKEY: 'readonly' + LOCATION_APIKEY: 'readonly', }, parserOptions: { ecmaFeatures: { - jsx: true - } + jsx: true, + }, }, settings: { react: { - version: 'detect' - } - } + version: 'detect', + }, + }, } diff --git a/.github/workflows/build-rust-binding.yml b/.github/workflows/build-rust-binding.yml index 2e5b1e0f4374..c0b9b3269972 100644 --- a/.github/workflows/build-rust-binding.yml +++ b/.github/workflows/build-rust-binding.yml @@ -44,7 +44,7 @@ jobs: - name: Setup pnpm uses: pnpm/action-setup@v2.4.0 with: - version: 7 + version: 8 - name: Setup Node.js ${{ matrix.node-version }} uses: actions/setup-node@v4 if: ${{ !matrix.settings.docker }} diff --git a/.github/workflows/nodejs.yml b/.github/workflows/nodejs.yml index 30c44bb0ec92..4d4285c0ed7d 100644 --- a/.github/workflows/nodejs.yml +++ b/.github/workflows/nodejs.yml @@ -5,6 +5,13 @@ env: on: push: branches: + - 'chore/**' + - 'feat/**' + - 'fix/**' + - '1.x' + - '2.x' + - '3.x' + - '4.x' - main pull_request: branches: @@ -22,29 +29,40 @@ jobs: uses: ./.github/workflows/build-rust-wasm.yml nodejs-tesing: - name: Testing on Node.js ${{ matrix.node-version }} (${{ matrix.settings.host }}) + name: Testing on Node.js ${{ matrix.node-version }} (${{ matrix.host }}) needs: - build-rust-binding - build-rust-wasm strategy: fail-fast: false matrix: - node-version: [16.x] - settings: + node-version: [16.x, 18.x, 20.x] + host: [macos-11, windows-latest, ubuntu-latest] + include: - host: macos-11 target: x86_64-apple-darwin - host: windows-latest target: x86_64-pc-windows-msvc - host: ubuntu-latest target: x86_64-unknown-linux-gnu - runs-on: ${{ matrix.settings.host }} + exclude: + - node-version: 16.x + host: macos-11 + - node-version: 16.x + host: windows-latest + - node-version: 18.x + host: macos-11 + - node-version: 18.x + host: windows-latest + + runs-on: ${{ matrix.host }} steps: - name: Checkout uses: actions/checkout@v4 - name: Setup pnpm uses: pnpm/action-setup@v2.4.0 with: - version: 7 + version: 8 - name: Setup Node.js ${{ matrix.node-version }} uses: actions/setup-node@v4 with: @@ -65,22 +83,21 @@ jobs: run: pnpm -r install --frozen-lockfile - name: Lint run: pnpm lint - - name: Download artifact bindings-${{ matrix.settings.target }} + - name: Download artifact bindings-${{ matrix.target }} uses: actions/download-artifact@v4 with: - name: bindings-${{ matrix.settings.target }} + name: bindings-${{ matrix.target }} path: crates/native_binding - name: Test bindings run: pnpm test:binding - if: ${{ matrix.settings.target != 'x86_64-unknown-linux-gnu' }} + if: ${{ matrix.target != 'x86_64-unknown-linux-gnu' }} - name: Test bindings with docker - if: ${{ matrix.settings.target == 'x86_64-unknown-linux-gnu' }} + if: ${{ matrix.target == 'x86_64-unknown-linux-gnu' }} # 暂时使用了一个第三方的 docker 镜像 run: docker run --rm -v $(pwd):/build -w /build chf007/pnpm pnpm test:binding # 以下的测试流程应该在所有平台都执行,但 windows 好像还有些问题,因此目前只在 ubuntu-latest 执行 - name: Download all artifacts uses: actions/download-artifact@v4 - if: ${{ matrix.settings.host == 'ubuntu-latest' }} with: path: crates/native_binding/artifacts - name: List Package crates/native_binding @@ -88,20 +105,21 @@ jobs: shell: bash - name: Move artifacts run: pnpm artifacts - if: ${{ matrix.settings.host == 'ubuntu-latest' }} - name: build run: pnpm build - if: ${{ matrix.settings.host == 'ubuntu-latest' }} - name: test run: pnpm test - if: ${{ matrix.settings.host == 'ubuntu-latest' }} env: CI: true + - name: Upload coverage reports to Codecov + uses: codecov/codecov-action@v3 + env: + CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} # 以下 coverage 流程通过 artifact 拆分文件作为单独 job 上传时间损耗过长,因此在在 node test 后直接继续执行 - name: Upload [taro-cli] coverage to Codecov uses: codecov/codecov-action@v3 - if: ${{ matrix.settings.host == 'ubuntu-latest' }} + if: ${{ matrix.host == 'ubuntu-latest' }} with: move_coverage_to_trash: true flags: taro-cli @@ -109,7 +127,7 @@ jobs: token: ${{ secrets.CODECOV_TOKEN }} - name: Upload runner coverage to Codecov uses: codecov/codecov-action@v3 - if: ${{ matrix.settings.host == 'ubuntu-latest' }} + if: ${{ matrix.host == 'ubuntu-latest' }} with: move_coverage_to_trash: true flags: taro-runner @@ -117,7 +135,7 @@ jobs: token: ${{ secrets.CODECOV_TOKEN }} - name: Upload [taro-runtime] coverage to Codecov uses: codecov/codecov-action@v3 - if: ${{ matrix.settings.host == 'ubuntu-latest' }} + if: ${{ matrix.host == 'ubuntu-latest' }} with: move_coverage_to_trash: true flags: taro-runtime @@ -125,7 +143,7 @@ jobs: token: ${{ secrets.CODECOV_TOKEN }} - name: Upload [taro-web] coverage to Codecov uses: codecov/codecov-action@v3 - if: ${{ matrix.settings.host == 'ubuntu-latest' }} + if: ${{ matrix.host == 'ubuntu-latest' }} with: move_coverage_to_trash: true flags: taro-web @@ -133,7 +151,7 @@ jobs: token: ${{ secrets.CODECOV_TOKEN }} - name: Upload rest coverage to Codecov uses: codecov/codecov-action@v3 - if: ${{ matrix.settings.host == 'ubuntu-latest' }} + if: ${{ matrix.host == 'ubuntu-latest' }} with: token: ${{ secrets.CODECOV_TOKEN }} diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 14525ba1a4d0..a52272e9f4df 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -4,7 +4,11 @@ on: branches: - 'chore/**' - 'feat/**' - # When Release Pull Request is merged + - 'fix/**' + - '1.x' + - '2.x' + - '3.x' + - '4.x' pull_request: branches: - main @@ -83,7 +87,7 @@ jobs: - name: Setup pnpm uses: pnpm/action-setup@v2.4.0 with: - version: 7 + version: 8 - name: Setup Node 16 uses: actions/setup-node@v4 with: diff --git a/.github/workflows/sync-components-types.yml b/.github/workflows/sync-components-types.yml index b437f3c9ab0c..e480cd9a2859 100644 --- a/.github/workflows/sync-components-types.yml +++ b/.github/workflows/sync-components-types.yml @@ -36,7 +36,7 @@ jobs: - name: install uses: pnpm/action-setup@v2.4.0 with: - version: 7 + version: 8 run_install: | - recursive: true args: [--frozen-lockfile, --strict-peer-dependencies] diff --git a/.husky/commit-msg b/.husky/commit-msg old mode 100755 new mode 100644 diff --git a/.husky/pre-commit b/.husky/pre-commit old mode 100755 new mode 100644 diff --git a/.vscode/launch.json b/.vscode/launch.json index 7abf2978c8d0..467ea8397f89 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -5,7 +5,7 @@ "version": "0.2.0", "configurations": [ { - "type": "lldb", + "type": "node", "request": "launch", "name": "debug-init", "sourceLanguages": ["rust"], diff --git a/.vscode/settings.json b/.vscode/settings.json index 40629da47a9c..ebd73d16e806 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,16 +1,5 @@ { - "eslint.validate": [ - "javascript", - "javascriptreact", - { - "language": "typescript", - "autoFix": true - }, - { - "language": "typescriptreact", - "autoFix": true - } - ], + "eslint.validate": ["javascript", "javascriptreact", "typescript", "typescriptreact"], "search.exclude": { "**/.git": true, "**/node_modules": true, @@ -22,7 +11,8 @@ "javascript.format.insertSpaceBeforeFunctionParenthesis": true, "typescript.format.insertSpaceBeforeFunctionParenthesis": true, "files.associations": { - "*.json": "jsonc" + "*.json": "jsonc", + "*.ets": "typescript" }, "rust-analyzer.linkedProjects": [ "./crates/taro_init/Cargo.toml", diff --git a/Cargo.lock b/Cargo.lock index 20bebf63fe9b..95cf63074b50 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -71,7 +71,7 @@ dependencies = [ "proc-macro2", "quote", "swc_macros_common", - "syn 2.0.39", + "syn 2.0.43", ] [[package]] @@ -302,12 +302,12 @@ dependencies = [ [[package]] name = "ctor" -version = "0.2.5" +version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37e366bff8cd32dd8754b0991fb66b279dc48f598c3a18914852a6673deef583" +checksum = "30d2b3721e861707777e3195b0158f950ae6dc4a27e4d02ff9f67e3eb3de199e" dependencies = [ "quote", - "syn 2.0.39", + "syn 2.0.43", ] [[package]] @@ -328,9 +328,9 @@ dependencies = [ [[package]] name = "deunicode" -version = "1.4.1" +version = "1.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a1abaf4d861455be59f64fd2b55606cb151fce304ede7165f410243ce96bde6" +checksum = "3ae2a35373c5c74340b79ae6780b498b2b183915ec5dacf263aac5a099bf485a" [[package]] name = "diff" @@ -430,7 +430,7 @@ checksum = "3a0b11eeb173ce52f84ebd943d42e58813a2ebb78a6a3ff0a243b71c5199cd7b" dependencies = [ "proc-macro2", "swc_macros_common", - "syn 2.0.39", + "syn 2.0.43", ] [[package]] @@ -441,9 +441,9 @@ checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" [[package]] name = "futures" -version = "0.3.29" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da0290714b38af9b4a7b094b8a37086d1b4e61f2df9122c3cad2577669145335" +checksum = "645c6916888f6cb6350d2550b80fb63e734897a8498abe35cfb732b6487804b0" dependencies = [ "futures-channel", "futures-core", @@ -456,9 +456,9 @@ dependencies = [ [[package]] name = "futures-channel" -version = "0.3.29" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff4dd66668b557604244583e3e1e1eada8c5c2e96a6d0d6653ede395b78bbacb" +checksum = "eac8f7d7865dcb88bd4373ab671c8cf4508703796caa2b1985a9ca867b3fcb78" dependencies = [ "futures-core", "futures-sink", @@ -466,15 +466,15 @@ dependencies = [ [[package]] name = "futures-core" -version = "0.3.29" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb1d22c66e66d9d72e1758f0bd7d4fd0bee04cad842ee34587d68c07e45d088c" +checksum = "dfc6580bb841c5a68e9ef15c77ccc837b40a7504914d52e47b8b0e9bbda25a1d" [[package]] name = "futures-executor" -version = "0.3.29" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f4fb8693db0cf099eadcca0efe2a5a22e4550f98ed16aba6c48700da29597bc" +checksum = "a576fc72ae164fca6b9db127eaa9a9dda0d61316034f33a0a0d4eda41f02b01d" dependencies = [ "futures-core", "futures-task", @@ -483,38 +483,38 @@ dependencies = [ [[package]] name = "futures-io" -version = "0.3.29" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8bf34a163b5c4c52d0478a4d757da8fb65cabef42ba90515efee0f6f9fa45aaa" +checksum = "a44623e20b9681a318efdd71c299b6b222ed6f231972bfe2f224ebad6311f0c1" [[package]] name = "futures-macro" -version = "0.3.29" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53b153fd91e4b0147f4aced87be237c98248656bb01050b96bf3ee89220a8ddb" +checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.43", ] [[package]] name = "futures-sink" -version = "0.3.29" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e36d3378ee38c2a36ad710c5d30c2911d752cb941c00c72dbabfb786a7970817" +checksum = "9fb8e00e87438d937621c1c6269e53f536c14d3fbd6a042bb24879e57d474fb5" [[package]] name = "futures-task" -version = "0.3.29" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "efd193069b0ddadc69c46389b740bbccdd97203899b48d09c5f7969591d6bae2" +checksum = "38d84fa142264698cdce1a9f9172cf383a0c82de1bddcf3092901442c4097004" [[package]] name = "futures-util" -version = "0.3.29" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a19526d624e703a3179b3d322efec918b6246ea0fa51d41124525f00f1cc8104" +checksum = "3d6401deb83407ab3da39eba7e33987a73c3df0c82b4bb5813ee871c19c41d48" dependencies = [ "futures-channel", "futures-core", @@ -697,7 +697,7 @@ dependencies = [ "Inflector", "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.43", ] [[package]] @@ -708,9 +708,9 @@ checksum = "616cde7c720bb2bb5824a224687d8f77bfd38922027f01d825cd7453be5099fb" [[package]] name = "itoa" -version = "1.0.9" +version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af150ab688ff2122fcef229be89cb50dd66af9e01a4ff320cc137eecc9bacc38" +checksum = "b1a46d1a171d865aa5f83f92695765caa047a9b4cbae2cbf37dbd613a793fd4c" [[package]] name = "jmespath" @@ -761,9 +761,9 @@ checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" [[package]] name = "libc" -version = "0.2.150" +version = "0.2.151" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89d92a4743f9a61002fae18374ed11e7973f530cb3a3255fb354818118b2203c" +checksum = "302d7ab3130588088d277783b1e2d2e10c9e9e4a16dd9050e6ec93fb3e7048f4" [[package]] name = "libloading" @@ -891,23 +891,23 @@ checksum = "d4b4532cf86bfef556348ac65e561e3123879f0e7566cca6d43a6ff5326f13df" [[package]] name = "napi-derive" -version = "2.14.2" +version = "2.14.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0cca5738c6e81eb5ffd2c8ff2b4f05ece9c4c60c7e2b36cec6524492cf7f330" +checksum = "9b5af262f1d8e660742eb722abc7113a5b3c3de4144d0ef23ede2518672ceff1" dependencies = [ "cfg-if", "convert_case", "napi-derive-backend", "proc-macro2", "quote", - "syn 1.0.109", + "syn 2.0.43", ] [[package]] name = "napi-derive-backend" -version = "1.0.55" +version = "1.0.58" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35960e5f33228192a9b661447d0dfe8f5a3790ff5b4058c4d67680ded4f65b91" +checksum = "2314f777bc9cde51705d991c44466cee4de4a3f41c6d3d019fcbbebb5cdd47c4" dependencies = [ "convert_case", "once_cell", @@ -915,7 +915,7 @@ dependencies = [ "quote", "regex", "semver 1.0.20", - "syn 1.0.109", + "syn 2.0.43", ] [[package]] @@ -986,9 +986,9 @@ dependencies = [ [[package]] name = "object" -version = "0.32.1" +version = "0.32.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cf5f9dd3933bd50a9e1f149ec995f39ae2c496d31fd772c1fd45ebc27e902b0" +checksum = "a6a622008b6e321afc04970976f62ee297fdbaa6f95318ca343e3eebb9648441" dependencies = [ "memchr", ] @@ -1071,7 +1071,7 @@ dependencies = [ "pest_meta", "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.43", ] [[package]] @@ -1115,7 +1115,7 @@ dependencies = [ "phf_shared", "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.43", ] [[package]] @@ -1147,7 +1147,7 @@ checksum = "52a40bc70c2c58040d2d8b167ba9a5ff59fc9dab7ad44771cfde3dcfde7a09c6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.43", ] [[package]] @@ -1162,9 +1162,9 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.70" +version = "1.0.71" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39278fbbf5fb4f646ce651690877f89d1c5811a3d4acb27700c1cb3cdb78fd3b" +checksum = "75cb1540fadbd5b8fbccc4dddad2734eba435053f725621c070711a14bb5f4b8" dependencies = [ "unicode-ident", ] @@ -1283,9 +1283,9 @@ checksum = "c08c74e62047bb2de4ff487b251e4a92e24f48745648451635cec7d591162d9f" [[package]] name = "relative-path" -version = "1.9.0" +version = "1.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c707298afce11da2efef2f600116fa93ffa7a032b5d7b628aa17711ec81383ca" +checksum = "e898588f33fdd5b9420719948f9f2a32c922a246964576f71ba7f24f80610fbc" [[package]] name = "rend" @@ -1407,9 +1407,9 @@ checksum = "7ffc183a10b4478d04cbbbfc96d0873219d962dd5accaff2ffbd4ceb7df837f4" [[package]] name = "ryu" -version = "1.0.15" +version = "1.0.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ad4cc8da4ef723ed60bced201181d83791ad433213d8c24efffda1eec85d741" +checksum = "f98d2aa92eebf49b69786be48e4477826b256916e84a57ff2a4f21923b48eb4c" [[package]] name = "scoped-tls" @@ -1480,7 +1480,7 @@ checksum = "43576ca501357b9b071ac53cdc7da8ef0cbd9493d8df094cd821777ea6e894d3" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.43", ] [[package]] @@ -1496,18 +1496,18 @@ dependencies = [ [[package]] name = "serde_spanned" -version = "0.6.4" +version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12022b835073e5b11e90a14f86838ceb1c8fb0325b72416845c487ac0fa95e80" +checksum = "eb3622f419d1296904700073ea6cc23ad690adbd66f13ea683df73298736f0c1" dependencies = [ "serde", ] [[package]] name = "serde_yaml" -version = "0.9.27" +version = "0.9.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3cc7a1570e38322cfe4154732e5110f887ea57e22b76f4bfd32b5bdd3368666c" +checksum = "a15e0ef66bf939a7c890a0bf6d5a733c70202225f9888a89ed5c62298b019129" dependencies = [ "indexmap", "itoa", @@ -1666,7 +1666,7 @@ dependencies = [ "proc-macro2", "quote", "swc_macros_common", - "syn 2.0.39", + "syn 2.0.43", ] [[package]] @@ -1767,9 +1767,9 @@ dependencies = [ [[package]] name = "swc_core" -version = "0.87.2" +version = "0.87.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d258de92df3ac19f6d49a9a6a18750e3cc4fcd483bb08b254db955a75baff71" +checksum = "1b815a0f6e8a5f77aa6c3863e3d4e73864f8c62f6e07adcbac72ce26fec59798" dependencies = [ "once_cell", "swc_atoms", @@ -1808,9 +1808,9 @@ dependencies = [ [[package]] name = "swc_ecma_codegen" -version = "0.146.45" +version = "0.146.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be75490c5a5cad616587cb8600ce387bb5925c8a9a3e44de674b67bf962fb439" +checksum = "a7d39a90607035cd7d3dca3bcdf1c086a9453ec32e1c9c91c59ea4a9b702cd2b" dependencies = [ "memchr", "num-bigint", @@ -1834,7 +1834,7 @@ dependencies = [ "proc-macro2", "quote", "swc_macros_common", - "syn 2.0.39", + "syn 2.0.43", ] [[package]] @@ -1874,9 +1874,9 @@ dependencies = [ [[package]] name = "swc_ecma_transforms_base" -version = "0.135.1" +version = "0.135.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e0b068341f5a479875415e0eed6aeb0eb63e09e300cb9b0caef117e98c65200" +checksum = "81d3f06d8da75e01249631d788211aad2a028640c3a4e222cfda7930235f3ea4" dependencies = [ "better_scoped_tls", "bitflags 2.4.1", @@ -1897,9 +1897,9 @@ dependencies = [ [[package]] name = "swc_ecma_transforms_testing" -version = "0.138.1" +version = "0.138.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f96a473c64e7f777b594d180114500caa917ee3585c3b28b87884876f72a2098" +checksum = "6ebc487d155be02aff745fa8ca356c4df993482a12b58a024565b705d8a4a5c5" dependencies = [ "ansi_term", "anyhow", @@ -1961,7 +1961,7 @@ checksum = "695a1d8b461033d32429b5befbf0ad4d7a2c4d6ba9cd5ba4e0645c615839e8e4" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.43", ] [[package]] @@ -1985,7 +1985,7 @@ checksum = "50176cfc1cbc8bb22f41c6fe9d1ec53fbe057001219b5954961b8ad0f336fce9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.43", ] [[package]] @@ -2001,6 +2001,7 @@ dependencies = [ name = "swc_plugin_compile_mode" version = "0.1.0" dependencies = [ + "regex", "serde", "serde_json", "swc_core", @@ -2022,7 +2023,7 @@ checksum = "785309d342a69df4c929ee59e14e36889ca832f1d2a3c1d03c47c93126c72dbc" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.43", ] [[package]] @@ -2047,7 +2048,7 @@ checksum = "ff9719b6085dd2824fd61938a881937be14b08f95e2d27c64c825a9f65e052ba" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.43", ] [[package]] @@ -2071,7 +2072,7 @@ dependencies = [ "proc-macro2", "quote", "swc_macros_common", - "syn 2.0.39", + "syn 2.0.43", ] [[package]] @@ -2087,9 +2088,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.39" +version = "2.0.43" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23e78b90f2fcf45d3e842032ce32e3f2d1545ba6636271dcbf24fa306d87be7a" +checksum = "ee659fb5f3d355364e1f3e5bc10fb82068efbf824a1e9d1c9504244a6469ad53" dependencies = [ "proc-macro2", "quote", @@ -2202,7 +2203,7 @@ dependencies = [ "quote", "regex", "relative-path", - "syn 2.0.39", + "syn 2.0.43", ] [[package]] @@ -2218,22 +2219,22 @@ dependencies = [ [[package]] name = "thiserror" -version = "1.0.50" +version = "1.0.52" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9a7210f5c9a7156bb50aa36aed4c95afb51df0df00713949448cf9e97d382d2" +checksum = "83a48fd946b02c0a526b2e9481c8e2a17755e47039164a86c4070446e3a4614d" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.50" +version = "1.0.52" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "266b2e40bc00e5a6c09c3584011e08b06f123c00362c92b975ba9843aaaa14b8" +checksum = "e7fbe9b594d6568a6a1443250a7e67d80b74e1e96f6d1715e1e21cc1888291d3" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.43", ] [[package]] @@ -2286,7 +2287,7 @@ checksum = "5b8a1e28f2deaa14e508979454cb3a223b10b938b45af148bc0986de36f1923b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.43", ] [[package]] @@ -2356,7 +2357,7 @@ checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.43", ] [[package]] @@ -2463,9 +2464,9 @@ checksum = "e51733f11c9c4f72aa0c160008246859e340b00807569a0da0e7a1079b27ba85" [[package]] name = "unsafe-libyaml" -version = "0.2.9" +version = "0.2.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f28467d3e1d3c6586d8f25fa243f544f5800fec42d97032474e17222c2b75cfa" +checksum = "ab4c90930b95a82d00dc9e9ac071b4991924390d46cbd0dfe566148667605e4b" [[package]] name = "untrusted" @@ -2545,7 +2546,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.43", "wasm-bindgen-shared", ] @@ -2567,7 +2568,7 @@ checksum = "f0eb82fcb7930ae6219a7ecfd55b217f5f0893484b7a13022ebb2b2bf20b5283" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.43", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -2838,9 +2839,9 @@ checksum = "dff9641d1cd4be8d1a070daf9e3773c5f67e78b4d9d42263020c057706765c04" [[package]] name = "winnow" -version = "0.5.25" +version = "0.5.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7e87b8dfbe3baffbe687eef2e164e32286eff31a5ee16463ce03d991643ec94" +checksum = "9b5c3db89721d50d0e2a673f5043fc4722f76dcc352d7b1ab8b8288bed4ed2c5" dependencies = [ "memchr", ] diff --git a/Cargo.toml b/Cargo.toml index 753b04f6a8e4..db523b70a55d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,12 +5,12 @@ resolver = "2" [workspace.dependencies] napi = { version = "=2.14.1", features = ["napi4", "tokio_rt"] } napi-build = { version = "=2.1.0" } -napi-derive = { version = "=2.14.2" } +napi-derive = { version = "=2.14.4" } napi-sys = { version = "=2.3.0" } once_cell = { version = "=1.19.0" } tokio = { version = "=1.34.0" } tokio-util = { version = "=0.7.10" } -futures = { version = "=0.3.29" } +futures = { version = "=0.3.30" } handlebars = { version = "=4.5.0" } handlebars_misc_helpers = { version = "=0.13.0" } serde_json = { version = "=1.0.108" } diff --git a/crates/native_binding/binding.d.ts b/crates/native_binding/binding.d.ts index 6b8363e85114..a46e568eebf6 100644 --- a/crates/native_binding/binding.d.ts +++ b/crates/native_binding/binding.d.ts @@ -27,6 +27,9 @@ export interface CreateOptions { pageName?: string compiler?: CompilerType setPageName?: string + subPkg?: string + pageDir?: string + setSubPkgPageName?: string changeExt?: boolean isCustomTemplate?: boolean pluginType?: string @@ -76,6 +79,8 @@ export interface Page { customTemplatePath?: string basePageFiles: Array period: PeriodType + subPkg?: string + pageDir?: string } export const enum PeriodType { diff --git a/crates/native_binding/package.json b/crates/native_binding/package.json index 6d0598cb0140..c8bee69d78f0 100644 --- a/crates/native_binding/package.json +++ b/crates/native_binding/package.json @@ -1,6 +1,6 @@ { "name": "@tarojs/binding", - "version": "3.6.23", + "version": "4.0.0-beta.58", "description": "Node binding for taro", "main": "binding.js", "typings": "binding.d.ts", diff --git a/crates/native_binding/src/lib.rs b/crates/native_binding/src/lib.rs index fd1f56a287b0..5100146bb1da 100644 --- a/crates/native_binding/src/lib.rs +++ b/crates/native_binding/src/lib.rs @@ -62,6 +62,8 @@ pub async fn create_page( conf.custom_template_path, conf.base_page_files, conf.period, + conf.sub_pkg, + conf.page_dir, ); let mut thread_safe_functions = HashMap::new(); for (key, callback) in handlers { diff --git a/crates/swc_plugin_compile_mode/Cargo.toml b/crates/swc_plugin_compile_mode/Cargo.toml index d5c336bb7a22..732ddbdccdba 100644 --- a/crates/swc_plugin_compile_mode/Cargo.toml +++ b/crates/swc_plugin_compile_mode/Cargo.toml @@ -10,6 +10,7 @@ crate-type = ["cdylib"] serde = { workspace = true } serde_json = { workspace = true } swc_core = { workspace = true } +regex = "1.10.2" [dev-dependencies] swc_core = { workspace = true, features = ["ecma_parser", "ecma_codegen"] } diff --git a/crates/swc_plugin_compile_mode/src/tests/harmony/children.rs b/crates/swc_plugin_compile_mode/src/tests/harmony/children.rs new file mode 100644 index 000000000000..341731a2aace --- /dev/null +++ b/crates/swc_plugin_compile_mode/src/tests/harmony/children.rs @@ -0,0 +1,96 @@ +use swc_core::ecma::transforms::testing::test; +use super::{tr, get_syntax_config}; + +test!( + get_syntax_config(), + |_| tr(), + should_support_render_fn, + r#" + function Index () { + return ( + + {renderHeader()} + + {renderHeader()} + {normalFunc()} + + {this.methods.renderFooter()} + {normalFunc()} + + ) + } + "# +); + +test!( + get_syntax_config(), + |_| tr(), + should_support_fragment, + r#" + function Index () { + return ( + + {content0} + <> + {content1} + hello + + <> + {content2} + hello! + + + {content3} + + {content4} + <> + {content5} + + <> + hello!! + + hello!!! + {content6} + + ) + } + "# +); + +test!( + get_syntax_config(), + |_| tr(), + should_render_react_component, + r#" + function Index () { + return ( + + + {}} /> + + ) + } + "# +); + +test!( + get_syntax_config(), + |_| tr(), + should_render_complex_children, + r#" + function Index () { + return ( + + {showModal && + + + + {haveIcon && } + + + } + + ) + } + "# +); diff --git a/crates/swc_plugin_compile_mode/src/tests/harmony/condition.rs b/crates/swc_plugin_compile_mode/src/tests/harmony/condition.rs index 3fe623fc4324..97c264e49478 100644 --- a/crates/swc_plugin_compile_mode/src/tests/harmony/condition.rs +++ b/crates/swc_plugin_compile_mode/src/tests/harmony/condition.rs @@ -41,4 +41,39 @@ test!( ) } "# -); \ No newline at end of file +); + +test!( + get_syntax_config(), + |_| tr(), + should_support_conditional_and_unkonw_component, + r#" + function Index () { + return ( + + {condition ? hello : hello} + + ) + } + "# +); + +test!( + get_syntax_config(), + |_| tr(), + should_support_complex_condition, + r#" + function Index () { + return ( + + {condition1 && condition2 && doSth()} />} + {condition1 && ident} + {condition1 && obj.property} + {condition1 && fn()} + {condition1 ? : } + {condition1 ? {condition2 ? : } : } + + ) + } + "# +); diff --git a/crates/swc_plugin_compile_mode/src/tests/harmony/mod.rs b/crates/swc_plugin_compile_mode/src/tests/harmony/mod.rs index 48fb71ad865a..858212721f97 100644 --- a/crates/swc_plugin_compile_mode/src/tests/harmony/mod.rs +++ b/crates/swc_plugin_compile_mode/src/tests/harmony/mod.rs @@ -9,6 +9,7 @@ mod entry; mod attributes; mod condition; mod looping; +mod children; pub fn tr () -> impl Fold + VisitMut { let config = serde_json::from_str::( diff --git a/crates/swc_plugin_compile_mode/src/transform_harmony.rs b/crates/swc_plugin_compile_mode/src/transform_harmony.rs index 7725bd381dbc..9d4795795c88 100644 --- a/crates/swc_plugin_compile_mode/src/transform_harmony.rs +++ b/crates/swc_plugin_compile_mode/src/transform_harmony.rs @@ -1,117 +1,115 @@ - -use swc_core::{ - common::{ - util::take::Take, - DUMMY_SP as span - }, - ecma::{ - self, - ast::*, - atoms::Atom, - visit::{VisitMut, VisitMutWith}, - }, -}; +use crate::utils::{ self, constants::*, harmony::components::* }; +use crate::PluginConfig; use std::collections::HashMap; -use std::rc::Rc; use std::collections::HashSet; -use crate::PluginConfig; -use crate::utils::{self, constants::*, harmony::components::*}; +use swc_core::{ + common::{ util::take::Take, DUMMY_SP as span }, + ecma::{ self, ast::*, atoms::Atom, visit::{ swc_ecma_ast, VisitMut, VisitMutWith } }, +}; +pub struct PreVisitor {} -pub struct PreVisitor { - is_in_jsx_expr_container: Rc, - is_in_and_expr: bool, +pub enum EtsDirection { + Row, + Column, + Flex, } + impl PreVisitor { - fn new () -> Self { - Self { - is_in_jsx_expr_container: Rc::new(true), - is_in_and_expr: false, - } + fn new() -> Self { + Self {} + } + fn process_cond_expr(&self, expr: &mut CondExpr) { + let test = &expr.test; + let cons = &mut expr.cons; + let compile_if = utils::create_jsx_expr_attr(COMPILE_IF, test.clone()); + let process_cond_arm = |arm: &mut Box, attr: JSXAttrOrSpread| { + match &mut **arm { + Expr::JSXElement(el) => { + el.opening.attrs.push(attr); + } + Expr::Cond(cond_expr) => { + self.process_cond_expr(cond_expr); + } + _ => (), + } + }; + process_cond_arm(cons, compile_if); } } impl VisitMut for PreVisitor { - fn visit_mut_jsx_expr_container (&mut self, container: &mut JSXExprContainer) { - let _counter = Rc::clone(&self.is_in_jsx_expr_container); - // TODO 目前的判断可能误伤函数内的三元表达式、条件表达式 - container.visit_mut_children_with(self); - } - fn visit_mut_expr (&mut self, expr: &mut Expr) { - if Rc::strong_count(&self.is_in_jsx_expr_container) == 1 { return }; - let mut is_first_and_expr = false; - - // is_in_and_expr 为 false 时,表示为当前 expr 的第一个 && 表达式,即当出现 aa && bb && 这种表达式时,只会处理最右侧的 && 表达式 - match expr { - // 将 aa && 转换为 aa ? : - Expr::Bin(BinExpr { op, left, right, ..}) => { - // C&&A 替换为 C?A:A',原因是为了无论显示还是隐藏都保留一个元素,从而不影响兄弟节点的变量路径 - if *op == op!("&&") && !self.is_in_and_expr { - is_first_and_expr = true; - fn inject_compile_if (el: &mut Box, condition: &mut Box) -> () { - el.opening.attrs.push(utils::create_jsx_expr_attr(COMPILE_IF, condition.clone())); - } - fn get_element_double (element_name: JSXElementName, condition: &mut Box, right: &mut Box) -> Expr { - Expr::Cond(CondExpr { - span, - test: condition.take(), - cons: right.take(), - alt: Box::new(utils::create_self_closing_jsx_element_expr( - element_name, // element 替换为同类型的元素。在显示/隐藏切换时,让运行时 diff 只更新必要属性而不是整个节点刷新 - Some(vec![utils::create_jsx_bool_attr(COMPILE_IGNORE)] - ))) - }) - } - match &mut **right { - Expr::JSXElement(el) => { - let element_name = el.opening.name.clone(); - inject_compile_if(el, left); - *expr = get_element_double(element_name, left, right); - }, - Expr::Paren(ParenExpr { expr: paren_expr, .. }) => { - if paren_expr.is_jsx_element() { - let el: &mut Box = paren_expr.as_mut_jsx_element().unwrap(); - let element_name = el.opening.name.clone(); - inject_compile_if(el, left); - *expr = get_element_double(element_name, left, paren_expr); - } - }, - Expr::Lit(_) => { - *expr = Expr::Cond(CondExpr { + fn visit_mut_jsx_element_child(&mut self, child: &mut JSXElementChild) { + if let JSXElementChild::JSXExprContainer(JSXExprContainer { expr: JSXExpr::Expr(expr), .. }) = child { + if let Expr::Paren(ParenExpr { expr: e, .. }) = &mut **expr { + *expr = e.take(); + } + + match &mut **expr { + // 将 aa && 转换为 aa ? : + Expr::Bin(BinExpr { op, left, right, .. }) => { + // C&&A 替换为 C?A:A',原因是为了无论显示还是隐藏都保留一个元素,从而不影响兄弟节点的变量路径 + if *op == op!("&&") { + fn inject_compile_if(el: &mut Box, condition: &mut Box) -> () { + el.opening.attrs.push(utils::create_jsx_expr_attr(COMPILE_IF, condition.clone())); + } + fn get_element_double(condition: &mut Box, right: &mut Box) -> Expr { + Expr::Cond(CondExpr { span, - test: left.take(), + test: condition.take(), cons: right.take(), - alt: Box::new(Expr::Lit(Lit::Str(Str { span, value: String::new().into(), raw: None }))) + alt: Box::new( + utils::create_self_closing_jsx_element_expr( + JSXElementName::Ident( + swc_ecma_ast::Ident::new( + "View".into(), + span // 使用适当的 Span + ) + ), // element 替换为同类型的元素。在显示/隐藏切换时,让运行时 diff 只更新必要属性而不是整个节点刷新 + Some(vec![utils::create_jsx_bool_attr(COMPILE_IGNORE)]) + ) + ), }) - }, - _ => { - // TODO Unknown fallback to template - println!("unknown expr: {right:?}"); + } + match &mut **right { + Expr::JSXElement(el) => { + inject_compile_if(el, left); + **expr = get_element_double(left, right); + } + Expr::Paren(ParenExpr { expr: paren_expr, .. }) => { + if paren_expr.is_jsx_element() { + let el: &mut Box = paren_expr.as_mut_jsx_element().unwrap(); + inject_compile_if(el, left); + **expr = get_element_double(left, paren_expr); + } + } + Expr::Lit(_) => { + **expr = Expr::Cond(CondExpr { + span, + test: left.take(), + cons: right.take(), + alt: Box::new( + Expr::Lit( + Lit::Str(Str { + span, + value: String::new().into(), + raw: None, + }) + ) + ), + }); + } + _ => (), } } } - }, - Expr::Cond(CondExpr { test, cons, ..}) => { - let compile_if = utils::create_jsx_expr_attr(COMPILE_IF, test.clone()); - let process_cond_arm = |arm: &mut Box, attr: JSXAttrOrSpread| { - match &mut **arm { - Expr::JSXElement(el) => { - el.opening.attrs.push(attr); - }, - _ => () - } - }; - process_cond_arm(cons, compile_if); - }, - _ => (), - } - - if is_first_and_expr { - self.is_in_and_expr = true; - } - - expr.visit_mut_children_with(self); + Expr::Cond(cond_expr) => { + self.process_cond_expr(cond_expr); + } + _ => (), + } - if is_first_and_expr { - self.is_in_and_expr = false; + expr.visit_mut_children_with(self); + } else { + child.visit_mut_children_with(self); } } } @@ -125,11 +123,12 @@ pub struct TransformVisitor { pub templates: HashMap, pub get_tmpl_name: Box String>, pub node_name_vec: Vec, - pub get_node_name: Box String> + pub get_node_name: Box String>, + pub deal_loop_now: bool, } impl TransformVisitor { - pub fn new (config: PluginConfig) -> Self { + pub fn new(config: PluginConfig) -> Self { let get_node_name = Box::new(utils::named_iter(String::from("node"))); let get_tmpl_name = Box::new(utils::named_iter(format!("{}t", config.tmpl_prefix))); @@ -142,17 +141,23 @@ impl TransformVisitor { get_tmpl_name, component_set: HashSet::new(), node_name_vec: vec![], - get_node_name + get_node_name, + deal_loop_now: false, } } - fn build_ets_element (&mut self, el: &mut JSXElement) -> String { + pub fn get_dynmaic_node_name(&mut self, name: String) -> String { + let node_name = if self.deal_loop_now { name } else { format!("this.{}", name) }; + node_name.to_string() + } + + fn build_ets_element(&mut self, el: &mut JSXElement) -> String { // jsx 节点添加动态 id,需要判断是否存在静态节点 let dynmaic_node_name: String; let mut is_node_name_created = false; // 如果是半编译状态下碰到的第一个 jsx,或者 jsx 含有动态属性,则创建新的 node_name - if !self.check_jsx_is_static(el) || self.node_stack.is_empty() { + if !self.deal_loop_now && (!self.check_jsx_is_static(el) || self.node_stack.is_empty()) { dynmaic_node_name = utils::create_jsx_dynamic_id(el, self); self.node_name.push(dynmaic_node_name.clone()); is_node_name_created = true; @@ -170,72 +175,81 @@ impl TransformVisitor { // 内置组件 Some(_) => { // 事件的处理,根据事件添加对应的 ets 事件处理函数 - let event_string: String = self.build_ets_event(opening_element); + let mut event_string: String = self.build_ets_event(opening_element); + let element_direction: EtsDirection = self.build_ets_direction(opening_element); + let mut children = utils::create_original_node_renderer_foreach(self); - // 判断 el 的子元素是否只有一个循环,如果是的话,直接使用 createNode 来生成后续子节点 + // 只处理元素的子元素只有一个循环的情况和子元素没有循环的情况,其他情况先用 createLazyChildren 生成子结点 let is_loop_exist = utils::check_jsx_element_children_exist_loop(el); - let mut children = utils::create_original_node_renderer(self); - - if !is_loop_exist { - children = self.build_ets_children(el); + let el_children_len = utils::get_valid_nodes(&el.children); + if !is_loop_exist || (is_loop_exist && el_children_len == 1) { + let (temp_children, ..) = self.build_ets_children(&mut el.children, None); + children = temp_children; } // 当前 node_name 节点树已全部递归完毕 if is_node_name_created { self.node_name.pop(); } - let mut code = match name.as_str() { VIEW_TAG => { self.component_set.insert(name.clone()); - get_view_component_str(&dynmaic_node_name, &children) - }, + + get_view_component_str( + &self.get_dynmaic_node_name(dynmaic_node_name), + &children, + element_direction + ) + } TEXT_TAG => { self.component_set.insert(name.clone()); - get_text_component_str(&dynmaic_node_name) - }, + event_string = "".to_owned(); + get_text_component_str(&self.get_dynmaic_node_name(dynmaic_node_name)) + } IMAGE_TAG => { self.component_set.insert(name.clone()); - get_image_component_str(&dynmaic_node_name) - }, - _ => String::new() + get_image_component_str(&self.get_dynmaic_node_name(dynmaic_node_name)) + } + _ => String::new(), }; code.push_str(event_string.as_str()); utils::add_spaces_to_lines(code.as_str()) - }, + } None => { // React 组件 - // 原生自定义组件 + // 原生自定义组件, 不支持自定义组件的跟节点是一个 fragment!! // 半编译暂未支持的组件 utils::create_original_node_renderer(self) } } } - _ => String::new() + _ => String::new(), }; child_string } - fn build_ets_children (&mut self, el: &mut JSXElement) -> String { + fn build_ets_children( + &mut self, + children: &mut Vec, + retain_start_from: Option + ) -> (String, i32) { let mut children_string = String::new(); - let mut retain_child_counter = 0; + let start = if retain_start_from.is_some() { retain_start_from.unwrap() } else { 0 }; + let mut retain_child_counter = start; // 迭代 el.children - el.children.iter_mut().for_each(|child| { - self.node_stack.entry(self.node_name.last().unwrap().clone()).or_insert(vec![]).push(retain_child_counter); + children.iter_mut().for_each(|child| { + self.push_node_stack(retain_child_counter); match child { JSXElementChild::JSXElement(child_el) => { let child_string = self.build_ets_element(&mut **child_el); children_string.push_str(&child_string); - retain_child_counter = retain_child_counter + 1; - }, - JSXElementChild::JSXExprContainer(JSXExprContainer { - expr: JSXExpr::Expr(jsx_expr), - .. - }) => { + retain_child_counter += 1; + } + JSXElementChild::JSXExprContainer(JSXExprContainer { expr: JSXExpr::Expr(jsx_expr), .. }) => { // 如果套着 (),则获取括号里面的内容 if let Expr::Paren(ParenExpr { expr, .. }) = &mut **jsx_expr { *jsx_expr = expr.take(); @@ -243,39 +257,83 @@ impl TransformVisitor { match &mut **jsx_expr { Expr::Cond(cond_expr) => { children_string.push_str(self.build_ets_cond_expr(cond_expr).as_str()); - }, + } + Expr::Call(CallExpr { callee: Callee::Expr(callee_expr), args, .. }) => { + let mut handle_loop = false; + // 如果这个child是一个loop, {xxx.map(item => )} + if let Some(return_jsx) = utils::extract_jsx_loop(callee_expr, args) { + if !self.deal_loop_now { + handle_loop = true; + let loop_start = format!( + "ForEach(this.{}.childNodes, (item: TaroElement) => {{\n", + self.node_name.last().unwrap() + ); + let loop_foot = "}, (item: TaroElement) => item._nid);"; + + // let loop_body = self.build_ets_children(&mut vec![JSXElementChild::JSXElement(return_jsx) ], None); + + println!("start"); + self.deal_loop_now = true; + self.node_name.push("item".to_string()); + let loop_body = self.build_ets_element(return_jsx); + self.node_name.pop(); + self.deal_loop_now = false; + + children_string.push_str(&utils::add_spaces_to_lines(&loop_start)); + children_string.push_str(&utils::add_spaces_to_lines(&loop_body)); + children_string.push_str(&utils::add_spaces_to_lines(&loop_foot)); + } + } + if !handle_loop { + let mut tmpl = utils::create_normal_text_template(self, false); + if utils::is_render_fn(callee_expr) { + tmpl = utils::create_original_node_renderer(self); + } + children_string.push_str(&tmpl); + } + } _ => { - // TODO: 全部当普通文本处理,后续根据前缀是否为 render 来判断是 jsx 还是普通文本,后续会支持 render 开头的函数调用返回 JSX - // Expr::Call(_) - let node_path = self.get_current_node_path(); - let code = utils::add_spaces_to_lines(get_text_component_str(&node_path).as_str()); - self.component_set.insert(TEXT_TAG.to_string()); + let code = utils::create_normal_text_template(self, false); children_string.push_str(&code); } - }; - retain_child_counter = retain_child_counter + 1; - }, + } + retain_child_counter += 1; + } JSXElementChild::JSXText(jsx_text) => { let content = utils::jsx_text_to_string(&jsx_text.value); if !content.is_empty() { let current_path = self.get_current_node_path(); - let code = utils::add_spaces_to_lines(get_text_component_str(¤t_path).as_str()); + let code = utils::add_spaces_to_lines( + get_text_component_str(&self.get_dynmaic_node_name(current_path)).as_str() + ); children_string.push_str(code.as_str()); self.component_set.insert(TEXT_TAG.to_string()); - retain_child_counter = retain_child_counter + 1; + retain_child_counter += 1; } - }, + } + JSXElementChild::JSXFragment(child_el) => { + self.pop_node_stack(); + let (child_string, inner_retain) = self.build_ets_children( + &mut child_el.children, + Some(retain_child_counter) + ); + children_string.push_str(&child_string); + if inner_retain != 0 { + retain_child_counter += inner_retain; + } + self.push_node_stack(retain_child_counter); + } _ => (), } - self.node_stack.entry(self.node_name.last().unwrap().clone()).or_insert(vec![]).pop(); + self.pop_node_stack(); }); - children_string + (children_string, retain_child_counter - start) } - fn build_ets_cond_expr (&mut self, cond_expr: &mut CondExpr) -> String { + fn build_ets_cond_expr(&mut self, cond_expr: &mut CondExpr) -> String { let mut children_string = String::new(); let mut process_condition_expr = |arm: &mut Box| { match &mut **arm { @@ -286,7 +344,7 @@ impl TransformVisitor { } else { self.build_ets_element(el) } - }, + } Expr::Lit(_) => { // {condition1 && 'Hello'} 在预处理时会变成 {condition1 ? 'Hello' : "compileIgnore"} // 而普通文本三元则会被 block 标签包裹,因此处理后只有上述情况会存在 lit 类型的表达式 @@ -294,16 +352,24 @@ impl TransformVisitor { let current_path = self.get_current_node_path(); self.component_set.insert(TEXT_TAG.to_string()); - utils::add_spaces_to_lines(get_text_component_str(¤t_path).as_str()) - }, + utils::add_spaces_to_lines( + get_text_component_str(&self.get_dynmaic_node_name(current_path)).as_str() + ) + } Expr::Cond(cond_expr) => self.build_ets_cond_expr(cond_expr), - _ => String::new() + _ => String::new(), } }; let alt_children_string = process_condition_expr(&mut cond_expr.alt); let cons_children_string = process_condition_expr(&mut cond_expr.cons as &mut Box); - children_string.push_str(format!("if (this.{}._attrs.compileIf) {{\n{}}}", self.get_current_node_path(), cons_children_string).as_str()); + children_string.push_str( + format!( + "if (({} as TaroElement)._attrs.compileIf) {{\n{}}}", + self.get_dynmaic_node_name(self.get_current_node_path()), + cons_children_string + ).as_str() + ); if !alt_children_string.is_empty() { children_string.push_str(format!(" else {{\n{}}}", alt_children_string).as_str()); } @@ -311,7 +377,7 @@ impl TransformVisitor { utils::add_spaces_to_lines(&children_string) } - fn check_jsx_is_static (&self, el: &mut JSXElement) -> bool { + fn check_jsx_is_static(&self, el: &mut JSXElement) -> bool { let opening_element = &mut el.opening; for attr in opening_element.attrs.iter_mut() { @@ -326,20 +392,21 @@ impl TransformVisitor { if let Some(value) = &jsx_attr.value { match value { JSXAttrValue::Lit(..) => (), - JSXAttrValue::JSXExprContainer(JSXExprContainer{ expr, .. }) => { + JSXAttrValue::JSXExprContainer(JSXExprContainer { expr, .. }) => { // jsx_attr 是事件,而且事件的 value 不是一个变量,那么当作静态属性,否则 JSXExprContainer 情况下都当作非静态属性 if is_event { if let JSXExpr::Expr(expr) = &expr { if let Expr::Ident(..) = &**expr { - return false + return false; } } } else if !is_condition { - return false + return false; } - - }, - _ => return false + } + _ => { + return false; + } } } } @@ -349,14 +416,91 @@ impl TransformVisitor { // 判断当前 el 的 children 是否是表达式,表达式的话父节点需要标注为非静态 for child in el.children.iter_mut() { if let JSXElementChild::JSXExprContainer(JSXExprContainer { .. }) = child { - return false + return false; } } return true; } - fn build_ets_event (&self, opening_element: &mut JSXOpeningElement) -> String { + fn build_ets_direction(&self, opening_element: &mut JSXOpeningElement) -> EtsDirection { + // 判断 opening_element 中的 attrs.style._flexDirection 属性,如果值是 FlexDirection.Row,则返回 EtsDirection.Row,否则返回 EtsDirection.Column + let mut direction = EtsDirection::Column; + let mut is_flex = false; + for attr in opening_element.attrs.iter_mut() { + if let JSXAttrOrSpread::JSXAttr(jsx_attr) = attr { + if let JSXAttrName::Ident(Ident { sym: name, .. }) = &jsx_attr.name { + let jsx_attr_name = name.to_string(); + if jsx_attr_name == DIRECTION_ATTR { + if let Some(JSXAttrValue::Lit(Lit::Str(Str { value, .. }))) = &jsx_attr.value { + direction = match value.as_str() { + "row" => EtsDirection::Row, + "flex" => EtsDirection::Flex, + _ => EtsDirection::Column, + }; + } + } else if jsx_attr_name == STYLE_ATTR { + if + let Some(JSXAttrValue::JSXExprContainer(JSXExprContainer { expr, .. })) = + &mut jsx_attr.value + { + if let JSXExpr::Expr(expr) = expr { + if let Expr::Object(ObjectLit { props, .. }) = &mut **expr { + for prop in props.iter_mut() { + if let PropOrSpread::Prop(prop) = prop { + if let Prop::KeyValue(KeyValueProp { key, value, .. }) = &mut **prop { + if let PropName::Ident(Ident { sym: name, .. }) = key { + // 判断 display 是否为 flex 且 _flexDirection 为 FlexDirection.Column,如果是则返回 EtsDirection.Column,否则返回 EtsDirection.Row + if name == "display" { + if let Expr::Lit(Lit::Str(Str { value, .. })) = &mut **value { + if value == "flex" && is_flex == false { + direction = EtsDirection::Row; + } + } + } + + if name == "_flexDirection" { + is_flex = true; + // 判断 value 是否为 attrs.style._flexDirection: FlexDirection.Row 变量 + if + let Expr::Member(MemberExpr { obj, prop, .. }) = + &mut **value + { + if + let Expr::Ident(Ident { sym: obj_name, .. }) = + &mut **obj + { + if + let MemberProp::Ident( + Ident { sym: prop_name, .. }, + ) = &mut *prop + { + if + obj_name == "FlexDirection" && + prop_name == "Column" + { + direction = EtsDirection::Column; + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + + direction + } + + fn build_ets_event(&mut self, opening_element: &mut JSXOpeningElement) -> String { let mut event_string = String::new(); // 在 transform 中使用的是 retain_mut 方法,在 retain_mut 中,如果 return false,就代表该属性不需要保留,在小程序中主要用于剪枝静态属性,鸿蒙这里不需要处理 @@ -378,7 +522,12 @@ impl TransformVisitor { jsx_attr_name = harmony_event_name.unwrap().to_string(); } - event_string.push_str(&create_component_event(jsx_attr_name.as_str(), &self.get_current_node_path())) + event_string.push_str( + &create_component_event( + jsx_attr_name.as_str(), + self.get_dynmaic_node_name(self.get_current_node_path()).as_str() + ) + ); } } } @@ -386,11 +535,13 @@ impl TransformVisitor { event_string } - fn get_current_node_path (&self) -> String { + pub fn get_current_node_path(&self) -> String { let current_node_name = self.node_name.last().unwrap().clone(); let current_node_stack = match self.node_stack.get(¤t_node_name) { Some(stack) => stack, - None => return current_node_name + None => { + return current_node_name; + } }; // return: node0.childNodes[0].childNodes[0].... @@ -399,101 +550,135 @@ impl TransformVisitor { return acc; }) } + + pub fn pop_node_stack(&mut self) { + self.node_stack + .entry(self.node_name.last().unwrap().clone()) + .or_insert(vec![]) + .pop(); + } + + pub fn push_node_stack(&mut self, index: i32) { + self.node_stack + .entry(self.node_name.last().unwrap().clone()) + .or_insert(vec![]) + .push(index); + } } impl VisitMut for TransformVisitor { - // Implement necessary visit_mut_* methods for actual custom transform. - // A comprehensive list of possible visitor methods can be found here: - // https://rustdoc.swc.rs/swc_ecma_visit/trait.VisitMut.html - // 半编译模式入口,遍历 jsx 语法树,寻找拥有 COMPILE_MODE 属性节点,预处理节点所在的子树,并根据子树信息生成 tmpl_contents - fn visit_mut_jsx_element (&mut self, el: &mut JSXElement) { - let mut tmpl_name = String::new(); - for attr in &mut el.opening.attrs { - if let JSXAttrOrSpread::JSXAttr(jsx_attr) = attr { - if let JSXAttrName::Ident(jsx_attr_name) = &jsx_attr.name { - if &*jsx_attr_name.sym == COMPILE_MODE { - self.is_compile_mode = true; - tmpl_name = (self.get_tmpl_name)(); - jsx_attr.value = Some(JSXAttrValue::Lit(Lit::Str(Str { - span, - value: tmpl_name.clone().into(), - raw: None, - }))); - break; - } - } - } - } - if self.is_compile_mode { - el.visit_mut_children_with(&mut PreVisitor::new()); - - let tmpl_build_contents = format!("build() {{\n{content}}}", content = self.build_ets_element(el)); - let tmpl_node_declare_contents = self.node_name_vec.iter().fold(String::new(), |mut acc, item| { - acc.push_str(&format!("@State {}: TaroElement = new TaroIgnoreElement()\n", item)); - return acc; - }); - let tmpl_main_contents = utils::add_spaces_to_lines(&format!("{}\n{}", tmpl_node_declare_contents, tmpl_build_contents)); - let tmpl_contents = - HARMONY_IMPORTER.to_owned() + - utils::get_harmony_component_style(self).as_str() + - format!( -r#"@Component -struct TARO_TEMPLATES_{name} {{ - nodeInfoMap: any = {{}} - dynamicCenter: DynamicCenter - @ObjectLink node: TaroElement + // Implement necessary visit_mut_* methods for actual custom transform. + // A comprehensive list of possible visitor methods can be found here: + // https://rustdoc.swc.rs/swc_ecma_visit/trait.VisitMut.html + // 半编译模式入口,遍历 jsx 语法树,寻找拥有 COMPILE_MODE 属性节点,预处理节点所在的子树,并根据子树信息生成 tmpl_contents + fn visit_mut_jsx_element(&mut self, el: &mut JSXElement) { + let mut tmpl_name = String::new(); + // 遍历 JSX 元素的属性,寻找特定的 COMPILE_MODE 属性比如 xxx + for attr in &mut el.opening.attrs { + if let JSXAttrOrSpread::JSXAttr(jsx_attr) = attr { + if let JSXAttrName::Ident(jsx_attr_name) = &jsx_attr.name { + if &*jsx_attr_name.sym == COMPILE_MODE { + self.is_compile_mode = true; + tmpl_name = (self.get_tmpl_name)(); + jsx_attr.value = Some( + JSXAttrValue::Lit( + Lit::Str(Str { + span, + value: tmpl_name.clone().into(), + raw: None, + }) + ) + ); + break; + } + } + } + } + if self.is_compile_mode { + el.visit_mut_children_with(&mut PreVisitor::new()); + + let tmpl_build_contents = format!("build() {{\n{content}}}", content = self.build_ets_element(el)); + let tmpl_node_declare_contents = self.node_name_vec.iter().fold(String::new(), |mut acc, item| { + acc.push_str(&format!("@State {}: TaroElement = new TaroElement('Ignore')\n", item)); + return acc; + }); + let tmpl_main_contents = utils::add_spaces_to_lines( + &format!("{}\n{}", tmpl_node_declare_contents, tmpl_build_contents) + ); + let tmpl_contents = + HARMONY_IMPORTER.to_owned() + + format!( + r#"@Component +export default struct TARO_TEMPLATES_{name} {{ + node: TaroViewElement = new TaroElement('Ignore') + + dynamicCenter: DynamicCenter = new DynamicCenter() aboutToAppear () {{ - this.dynamicCenter = new DynamicCenter() this.dynamicCenter.bindComponentToNodeWithDFS(this.node, this) }} {content}}} -export default TARO_TEMPLATES_{name} "#, - name = tmpl_name, - content = tmpl_main_contents - ).as_str(); - - self.templates.insert(tmpl_name, format!("`{}`", tmpl_contents)); - - // 数据清理 - self.node_stack.clear(); - self.node_name.clear(); - self.node_name_vec.clear(); - self.component_set.clear(); - self.is_compile_mode = false; - self.get_node_name = Box::new(utils::named_iter(String::from("node"))); - } else { - el.visit_mut_children_with(self) - } - } - - // 将生成的模板字符串以变量的形式插入在文件最上面,等待后续编译抽离 - fn visit_mut_module_items (&mut self, body_stmts: &mut Vec) { - body_stmts.visit_mut_children_with(self); - - let mut keys: Vec<&String> = self.templates.keys().collect(); - keys.sort(); - let stmts_being_inserted = keys.into_iter() - .map(|key| { - let value = self.templates.get(key).unwrap(); - ModuleItem::Stmt(Stmt::Decl(Decl::Var(Box::new(VarDecl { - span, - kind: VarDeclKind::Const, - declare: false, - decls: vec![VarDeclarator { - span, - name: Pat::Ident(Ident::new(format!("TARO_TEMPLATES_{}", key).as_str().into(), span).into()), - init: Some(Box::new(Expr::Lit(Lit::Str(Str { - span, - value: value.as_str().into(), - raw: Some(Atom::new(value.as_str())) - })))), - definite: false, - }], - })))) - }); - ecma::utils::prepend_stmts(body_stmts, stmts_being_inserted); - } + name = tmpl_name, + content = tmpl_main_contents + ).as_str() + + utils::get_harmony_component_style(self).as_str(); + + self.templates.insert(tmpl_name, format!("`{}`", tmpl_contents)); + + // println!("templates: {:?}", self.templates); + + // 数据清理 + self.node_stack.clear(); + self.node_name.clear(); + self.node_name_vec.clear(); + self.component_set.clear(); + self.is_compile_mode = false; + self.get_node_name = Box::new(utils::named_iter(String::from("node"))); + } else { + el.visit_mut_children_with(self) + } + } + + // 将生成的模板字符串以变量的形式插入在文件最上面,等待后续编译抽离 + fn visit_mut_module_items(&mut self, body_stmts: &mut Vec) { + body_stmts.visit_mut_children_with(self); + + let mut keys: Vec<&String> = self.templates.keys().collect(); + keys.sort(); + let stmts_being_inserted = keys.into_iter().map(|key| { + let value = self.templates.get(key).unwrap(); + ModuleItem::Stmt( + Stmt::Decl( + Decl::Var( + Box::new(VarDecl { + span, + kind: VarDeclKind::Const, + declare: false, + decls: vec![VarDeclarator { + span, + name: Pat::Ident( + Ident::new(format!("TARO_TEMPLATES_{}", key).as_str().into(), span).into() + ), + init: Some( + Box::new( + Expr::Lit( + Lit::Str(Str { + span, + value: value.as_str().into(), + raw: Some(Atom::new(value.as_str())), + }) + ) + ) + ), + definite: false, + }], + }) + ) + ) + ) + }); + ecma::utils::prepend_stmts(body_stmts, stmts_being_inserted); + } } diff --git a/crates/swc_plugin_compile_mode/src/utils/constants.rs b/crates/swc_plugin_compile_mode/src/utils/constants.rs index 17538c2947b5..5ad0ca6b7526 100644 --- a/crates/swc_plugin_compile_mode/src/utils/constants.rs +++ b/crates/swc_plugin_compile_mode/src/utils/constants.rs @@ -16,191 +16,197 @@ pub const VIEW_TAG: &str = "view"; pub const TEXT_TAG: &str = "text"; pub const IMAGE_TAG: &str = "image"; -pub const HARMONY_IMPORTER: &str = "import { FlexManager } from './utils/FlexManager' -import { getNodeThresholds, getNormalAttributes, getTextAttributes } from './utils/helper' -import { TaroIgnoreElement, eventHandler, DynamicCenter, getComponentEventCallback, AREA_CHANGE_EVENT_NAME, VISIBLE_CHANGE_EVENT_NAME } from '../runtime' -import type { TaroElement } from '../runtime' -import { TOUCH_EVENT_MAP } from './utils/constant/event' +pub const STYLE_ATTR: &str = "style"; +pub const DIRECTION_ATTR: &str = "harmonyDirection"; + +pub const HARMONY_IMPORTER: &str = "import { + rowModify, + FlexManager, + columnModify, + DynamicCenter, + getButtonColor, + TOUCH_EVENT_MAP, + getFontAttributes, + commonStyleModify, + getNodeThresholds, + BUTTON_THEME_COLOR, + getStyleAttr, + getNormalAttributes, + shouldBindEvent, + textModify, + setNormalTextAttributeIntoInstance, + getImageMode +} from '@tarojs/components' +import { + NodeType, + convertNumber2VP, + TaroElement, + eventHandler, + getComponentEventCallback, + AREA_CHANGE_EVENT_NAME, + VISIBLE_CHANGE_EVENT_NAME +} from '@tarojs/runtime' +import { + createLazyChildren, + createChildItem +} from '../render' + +import type { + TaroTextElement, + HarmonyStyle, + TaroButtonElement, + TaroViewElement, + TaroAny, + TaroStyleType, + TaroTextStyleType +} from '@tarojs/runtime' +import { isString } from '@tarojs/shared' + "; -pub const HARMONY_FLEX_STYLE_BIND: &str = r#"@Extend(Flex) -function attrs ({ - flexBasis, - flexGrow, - flexShrink, - alignSelf, - clip, - width, - height, - margin, - padding, - linearGradient, - zIndex, - borderStyle, - borderWidth, - borderColor, - borderRadius, - opacity, - backgroundColor, - backgroundImage, - backgroundRepeat, - backgroundImageSize, - constraintSize, - rotate, - scale, - translate, - transform -}) { - .flexGrow(flexGrow) - .flexShrink(flexShrink) - .flexBasis(flexBasis) - .alignSelf(alignSelf) - .width(width) - .height(height) - .constraintSize(constraintSize) - .margin(margin) - .padding(padding) - .linearGradient(linearGradient) - .zIndex(zIndex) - .borderStyle(borderStyle) - .borderWidth(borderWidth) - .borderColor(borderColor) - .borderRadius(borderRadius) - .opacity(opacity) - .backgroundColor(backgroundColor) - .backgroundImage(backgroundImage, backgroundRepeat) - .backgroundImageSize(backgroundImageSize) - .rotate(rotate) - .scale(scale) - .translate(translate) - .transform(transform) - .clip(clip) -} -"#; -pub const HARMONY_TEXT_STYLE_BIND: &str = r#"@Extend(Text) -function attrsText ({ - id, - width, - height, - zIndex, - opacity, - margin, - padding, - decoration, - lineHeight, - letterSpacing, - maxLines, - fontColor, - fontSize, - fontWeight, - fontFamily, - textOverflow, - constraintSize, - border, - borderRadius, - backgroundColor, - backgroundImage, - backgroundRepeat, - backgroundImageSize, - rotate, - scale, - translate, - transform, - textAlign, - }) { - .id(id) - .key(id) - .constraintSize(constraintSize) - .zIndex(zIndex) - .opacity(opacity) - .margin(margin) - .padding(padding) - .decoration(decoration) - .lineHeight(lineHeight) - .letterSpacing(letterSpacing) - .maxLines(maxLines) - .fontColor(fontColor) - .fontSize(fontSize) - .fontWeight(fontWeight) - .fontFamily(fontFamily) - .textOverflow(textOverflow) - .border(border) - .borderRadius(borderRadius) - .backgroundColor(backgroundColor) - .backgroundImage(backgroundImage, backgroundRepeat) - .backgroundImageSize(backgroundImageSize) - .rotate(rotate) - .scale(scale) - .translate(translate) - .transform(transform) - .textAlign(textAlign) - .width(width) - .height(height) +pub const HARMONY_TEXT_HELPER_FUNCITON: &str = r#" + + +class SpanStyleModify implements AttributeModifier { + node: TaroTextElement | null = null + style: HarmonyStyle | null = null + overwriteStyle: Record = {} + withNormal = false + + setNode (node: TaroTextElement) { + this.node = node + this.style = getNormalAttributes(this.node) + return this + } + + applyNormalAttribute(instance: SpanAttribute): void { + if (this.node && this.style) { + setNormalTextAttributeIntoInstance(instance, this.style, this.node) + } + } } -function getTextAttributes (node: TaroViewElement) { - const attrs = { - ...getNormalAttributes(node), - ...getFontAttributes(node) +function getSpanVerticalAlign (verticalAlign?: Alignment) { + switch (verticalAlign) { + case Alignment.Start: + case Alignment.TopStart: + case Alignment.Top: + case Alignment.TopEnd: { + return ImageSpanAlignment.TOP + } + case Alignment.End: + case Alignment.BottomStart: + case Alignment.Bottom: + case Alignment.BottomEnd: { + return ImageSpanAlignment.BOTTOM + } + case Alignment.Center: { + return ImageSpanAlignment.CENTER + } } + return ImageSpanAlignment.BASELINE +} - transformW3CToHarmonyInStyle(node._st, attrs) +function getButtonFontSize (node: TaroButtonElement): string | number { + const isMini = node._attrs.size === 'mini' - return attrs + return isMini ? convertNumber2VP(26) : convertNumber2VP(36) } + +function getTextInViewWidth (node: TaroElement | null): TaroAny { + if (node) { + const hmStyle = node.hmStyle || {} + const isFlexView = hmStyle.display === 'flex' + const width: TaroAny = getStyleAttr(node, 'width') + const isPercentWidth = isString(width) && width.includes('%') + + return isFlexView || isPercentWidth ? null : getStyleAttr(node, 'width') + } +} + "#; -pub const HARMONY_IMAGE_STYLE_BIND: &str = r#"@Extend(Image) -function attrsImage ({ - flexBasis, - flexGrow, - flexShrink, - alignSelf, - clip, - width, - height, - margin, - padding, - linearGradient, - zIndex, - borderStyle, - borderWidth, - borderColor, - borderRadius, - opacity, - backgroundColor, - backgroundImage, - backgroundRepeat, - backgroundImageSize, - constraintSize, - rotate, - scale, - translate, - transform -}) { - .flexGrow(flexGrow) - .flexShrink(flexShrink) - .flexBasis(flexBasis) - .alignSelf(alignSelf) - .width(width) - .height(height) - .constraintSize(constraintSize) - .margin(margin) - .padding(padding) - .linearGradient(linearGradient) - .zIndex(zIndex) - .borderStyle(borderStyle) - .borderWidth(borderWidth) - .borderColor(borderColor) - .borderRadius(borderRadius) - .opacity(opacity) - .backgroundColor(backgroundColor) - .backgroundImage(backgroundImage, backgroundRepeat) - .backgroundImageSize(backgroundImageSize) - .rotate(rotate) - .scale(scale) - .translate(translate) - .transform(transform) - .clip(clip) - .objectFit(ImageFit.Contain) + +pub const HARMONY_TEXT_BUILDER: &str = r#"@Builder +function createText (node: TaroTextElement) { + if (node.nodeType === NodeType.TEXT_NODE) { + if (node.parentNode) { + if ((node.parentNode as TaroElement).tagName === 'BUTTON') { + Text(node.textContent) + .attributeModifier(textModify.setNode(node?.parentElement as TaroElement, { + fontSize: getButtonFontSize(node.parentNode as TaroButtonElement), + color: getButtonColor(node.parentNode as TaroButtonElement, BUTTON_THEME_COLOR.get((node.parentNode as TaroButtonElement)._attrs.type || '').text) + })) + } else { + Text(node.textContent) + .attributeModifier(textModify.setNode(node?.parentElement as TaroElement)) + .width(getTextInViewWidth(node.parentElement)) + } + } + } else { + Text(node.textContent) { + // text 下还有标签 + if (node.childNodes.length > 1 || ((node.childNodes[0] && node.childNodes[0] as TaroElement)?.nodeType === NodeType.ELEMENT_NODE)) { + ForEach(node.childNodes, (item: TaroElement) => { + createTextChildNode(item, getSpanVerticalAlign(node.hmStyle?.verticalAlign)) + }, (item: TaroElement) => item._nid) + } + } + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', node), node, ['click'])) + .attributeModifier(textModify.setNode(node).withNormalStyle()) + .onVisibleAreaChange(getNodeThresholds(node) || [0.0, 1.0], getComponentEventCallback(node, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(node, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + node._nodeInfo.areaInfo = res[1] + })) + } +} + +@Builder +function createTextChildNode (item: TaroElement, align: ImageSpanAlignment) { + if (item.tagName === 'IMAGE') { + ImageSpan(item.getAttribute('src')) + .objectFit(getImageMode(item.getAttribute('mode'))) + .verticalAlign(align) + .width(item._st.hmStyle.width) + .height(item._st.hmStyle.height) + .margin({ + top: item._st.hmStyle.marginTop, + left: item._st.hmStyle.marginLeft, + right: item._st.hmStyle.marginRight, + bottom: item._st.hmStyle.marginBottom, + }) + .padding({ + top: item._st.hmStyle.paddingTop, + left: item._st.hmStyle.paddingLeft, + right: item._st.hmStyle.paddingRight, + bottom: item._st.hmStyle.paddingBottom, + }) + .textBackgroundStyle({ + color: item._st.hmStyle.backgroundColor, + radius: { + topLeft: item._st.hmStyle.borderTopLeftRadius, + topRight: item._st.hmStyle.borderTopRightRadius, + bottomLeft: item._st.hmStyle.borderBottomLeftRadius, + bottomRight: item._st.hmStyle.borderBottomRightRadius, + } + }) + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', item), item, ['click'])) + } else if (item.nodeType === NodeType.TEXT_NODE) { + Span(item.textContent) + } else if (item.tagName === 'TEXT') { + Span(item.textContent) + .attributeModifier((new SpanStyleModify()).setNode(item as TaroTextElement)) + .letterSpacing(item._st.hmStyle.letterSpacing) + .textBackgroundStyle({ + color: item._st.hmStyle.backgroundColor, + radius: { + topLeft: item._st.hmStyle.borderTopLeftRadius, + topRight: item._st.hmStyle.borderTopRightRadius, + bottomLeft: item._st.hmStyle.borderBottomLeftRadius, + bottomRight: item._st.hmStyle.borderBottomRightRadius, + } + }) + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', item), item, ['click'])) + } } "#; + diff --git a/crates/swc_plugin_compile_mode/src/utils/harmony/components.rs b/crates/swc_plugin_compile_mode/src/utils/harmony/components.rs index bfedd4282f76..626937409902 100644 --- a/crates/swc_plugin_compile_mode/src/utils/harmony/components.rs +++ b/crates/swc_plugin_compile_mode/src/utils/harmony/components.rs @@ -1,61 +1,90 @@ -pub fn get_component_attr_str (node_name: &str, tag_name: &str) -> String { - if tag_name == "text" { - format!(".attrsText(getTextAttributes(this.{}))", node_name) - } else if tag_name == "image" { - format!(".attrsImage(getNormalAttributes(this.{}))", node_name) - } else { - format!(".attrs(getNormalAttributes(this.{}))", node_name) - } +use crate::{ transform_harmony::EtsDirection, utils::{ self, harmony::components } }; + +pub fn get_component_attr_str(node_name: &str, tag_name: &str) -> String { + if tag_name == "text" { + format!( + ".attributeModifier(commonStyleModify.setNode({} as TaroElement))\n.textSpecialFontStyle(getFontAttributes({} as TaroElement))", + node_name, + node_name + ) + } else if tag_name == "row" { + format!(".attributeModifier(rowModify.setNode({} as TaroElement))", node_name) + } else if tag_name == "column" { + format!(".attributeModifier(columnModify.setNode({} as TaroElement))", node_name) + } else { + format!(".attributeModifier(commonStyleModify.setNode({} as TaroElement))", node_name) + } } -pub fn get_component_style_str (node_name: &str, tag_name: &str) -> String { - format!( -r#"{} -.onVisibleAreaChange(getNodeThresholds(this.{node_id}) || [0.0, 1.0], getComponentEventCallback(this.{node_id}, VISIBLE_CHANGE_EVENT_NAME)) -.onAreaChange(getComponentEventCallback(this.{node_id}, AREA_CHANGE_EVENT_NAME, ({{ eventResult }}) => {{ - const [_, areaResult] = eventResult - this.nodeInfoMap[this.{node_id}._nid].areaInfo = areaResult +pub fn get_component_style_str(node_name: &str, tag_name: &str) -> String { + format!( + r#"{} +.onVisibleAreaChange(getNodeThresholds({node_id} as TaroElement) || [0.0, 1.0], getComponentEventCallback({node_id} as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) +.onAreaChange(getComponentEventCallback({node_id} as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => {{ + ({node_id} as TaroElement)._nodeInfo.areaInfo = res[1] }}))"#, - get_component_attr_str(node_name, tag_name), - node_id = node_name, - ) + get_component_attr_str(node_name, tag_name), + node_id = node_name + ) } +pub fn get_view_component_str(node_name: &str, child_content: &str, direction: EtsDirection) -> String { + let component_name; + let mut component_param = "".to_string(); + let component_children = match child_content { + "" => "".to_string(), + _ => format!("\n{}", child_content), + }; -pub fn get_view_component_str (node_name: &str, child_content: &str) -> String { - format!("Flex(FlexManager.flexOptions(this.{node_id})) {{{children}}}\n{style}", - node_id = node_name, - children = match child_content { - "" => "".to_string(), - _ => format!("\n{}", child_content) - }, - style = get_component_style_str(node_name, "view") - ) + match direction { + EtsDirection::Row => { + component_name = "Row"; + } + EtsDirection::Column => { + component_name = "Column"; + } + EtsDirection::Flex => { + component_name = "Flex"; + component_param = format!("FlexManager.flexOptions({} as TaroElement)", node_name); + } + } + let style = get_component_style_str(node_name, component_name.to_lowercase().as_str()); + + format!( + "{name}({param}) {{{children}}}\n{style}", + name = component_name, + param = component_param, + children = component_children, + style = style + ) } -pub fn get_image_component_str (node_name: &str) -> String { - format!("Image(this.{node_id}.getAttribute('src'))\n{style}", - node_id = node_name, - style = get_component_style_str(node_name, "image") - ) +pub fn get_image_component_str(node_name: &str) -> String { + format!( + "Image(({node_id} as TaroElement).getAttribute('src'))\n.objectFit(getImageMode(({node_id} as TaroElement).getAttribute('mode')))\n{style}", + node_id = node_name, + style = get_component_style_str(node_name, "image") + ) } -pub fn get_text_component_str (node_name: &str) -> String { - format!("Text(this.{node_id}.textContent)\n{style}", - node_id = node_name, - style = get_component_style_str(node_name, "text") - ) +pub fn get_text_component_str(node_name: &str) -> String { + format!("createText({node_id} as TaroTextElement)", node_id = node_name) } +pub fn create_component_event(event_name: &str, node_name: &str) -> String { + let process_event_trigger_name = |name: &str| -> String { + if name == "touch" { String::from("TOUCH_EVENT_MAP.get(e.type)") } else { format!("'{}'", name) } + }; -pub fn create_component_event (event_name: &str, node_name: &str) -> String { - let process_event_trigger_name = |name: &str| -> String { - if name == "touch" { - String::from("TOUCH_EVENT_MAP[e.type]") - } else { - format!("'{}'", name) - } - }; - - format!("\n.{}(e => eventHandler(e, {}, this.{}))", event_name, process_event_trigger_name(&event_name.get(2..).unwrap().to_lowercase()), node_name) + format!( + "\n.{}(e => eventHandler(e, {}, {} as TaroElement))", + event_name, + process_event_trigger_name( + &event_name + .get(2..) + .unwrap() + .to_lowercase() + ), + node_name + ) } diff --git a/crates/swc_plugin_compile_mode/src/utils/mod.rs b/crates/swc_plugin_compile_mode/src/utils/mod.rs index cc41829302a2..18910f6046cf 100644 --- a/crates/swc_plugin_compile_mode/src/utils/mod.rs +++ b/crates/swc_plugin_compile_mode/src/utils/mod.rs @@ -1,25 +1,18 @@ +use std::collections::HashMap; use swc_core::{ - ecma::{ - atoms::Atom, - ast::*, - utils::quote_str, - }, - common::{ - iter::IdentifyLast, - util::take::Take, - DUMMY_SP as span - }, + common::{ iter::IdentifyLast, util::take::Take, DUMMY_SP as span }, + ecma::{ ast::*, atoms::Atom, utils::quote_str }, }; -use std::collections::HashMap; +use regex::Regex; -use self::constants::*; -use crate::PluginConfig; +use self::{ constants::*, harmony::components::get_text_component_str }; use crate::transform_harmony::TransformVisitor; +use crate::PluginConfig; -pub mod harmony; pub mod constants; +pub mod harmony; -pub fn named_iter (str: String) -> impl FnMut() -> String { +pub fn named_iter(str: String) -> impl FnMut() -> String { let mut count = -1; return move || { count += 1; @@ -27,7 +20,7 @@ pub fn named_iter (str: String) -> impl FnMut() -> String { }; } -pub fn jsx_text_to_string (atom: &Atom) -> String { +pub fn jsx_text_to_string(atom: &Atom) -> String { let content = atom.replace("\t", " "); let res = content @@ -36,18 +29,10 @@ pub fn jsx_text_to_string (atom: &Atom) -> String { .identify_last() .fold(String::new(), |mut acc, (is_last, (index, line))| { // 首行不 trim 头 - let line = if index == 0 { - line - } else { - line.trim_start() - }; + let line = if index == 0 { line } else { line.trim_start() }; // 尾行不 trim 尾 - let line = if is_last { - line - } else { - line.trim_end() - }; + let line = if is_last { line } else { line.trim_end() }; if !acc.is_empty() && !line.is_empty() { acc.push(' '); @@ -60,10 +45,9 @@ pub fn jsx_text_to_string (atom: &Atom) -> String { } // 将驼峰写法转换为 kebab-case,即 aBcD -> a-bc-d -pub fn to_kebab_case (val: &str) -> String { +pub fn to_kebab_case(val: &str) -> String { let mut res = String::new(); - val - .chars() + val.chars() .enumerate() .for_each(|(idx, c)| { if idx != 0 && c.is_uppercase() { @@ -74,51 +58,43 @@ pub fn to_kebab_case (val: &str) -> String { res } -pub fn convert_jsx_attr_key (jsx_key: &str, adapter: &HashMap) -> String { +pub fn convert_jsx_attr_key(jsx_key: &str, adapter: &HashMap) -> String { if jsx_key == "className" { return String::from("class"); - } else if - jsx_key == COMPILE_IF || - jsx_key == COMPILE_ELSE || - jsx_key == COMPILE_FOR || - jsx_key == COMPILE_FOR_KEY - { + } else if jsx_key == COMPILE_IF || jsx_key == COMPILE_ELSE || jsx_key == COMPILE_FOR || jsx_key == COMPILE_FOR_KEY { let expr = match jsx_key { COMPILE_IF => "if", COMPILE_ELSE => "else", COMPILE_FOR => "for", COMPILE_FOR_KEY => "key", - _ => "" + _ => "", }; let adapter = adapter.get(expr).expect(&format!("[compile mode] 模板 {} 语法未配置", expr)); - return adapter.clone() + return adapter.clone(); } to_kebab_case(jsx_key) } -pub fn check_is_event_attr (val: &str) -> bool { - val.starts_with("on") && val.chars().nth(2).is_some_and(|x| x.is_uppercase()) +pub fn check_is_event_attr(val: &str) -> bool { + val.starts_with("on") && + val + .chars() + .nth(2) + .is_some_and(|x| x.is_uppercase()) } -pub fn identify_jsx_event_key (val: &str, platform: &str) -> Option { +pub fn identify_jsx_event_key(val: &str, platform: &str) -> Option { if check_is_event_attr(val) { - let event_name = val.get(2..).unwrap().to_lowercase(); - let event_name = if event_name == "click" { - "tap" - } else { - &event_name - }; + let event_name = val + .get(2..) + .unwrap() + .to_lowercase(); + let event_name = if event_name == "click" { "tap" } else { &event_name }; let event_binding_name = match platform { "ALIPAY" => { - if event_name == "tap" { - String::from("onTap") - } else { - String::from(val) - } - }, - _ => { - format!("bind{}", event_name) + if event_name == "tap" { String::from("onTap") } else { String::from(val) } } + _ => { format!("bind{}", event_name) } }; Some(event_binding_name) } else { @@ -126,7 +102,7 @@ pub fn identify_jsx_event_key (val: &str, platform: &str) -> Option { } } -pub fn is_inner_component (el: &mut Box, config: &PluginConfig) -> bool { +pub fn is_inner_component(el: &mut Box, config: &PluginConfig) -> bool { let opening = &el.opening; if let JSXElementName::Ident(Ident { sym, .. }) = &opening.name { let name = to_kebab_case(&sym); @@ -136,64 +112,68 @@ pub fn is_inner_component (el: &mut Box, config: &PluginConfig) -> b false } -pub fn is_static_jsx (el: &Box) -> bool { +pub fn is_static_jsx(el: &Box) -> bool { if el.opening.attrs.len() > 0 { - return false + return false; } for child in &el.children { if let JSXElementChild::JSXText(_) = child { } else { - return false + return false; } } true } -pub fn create_self_closing_jsx_element_expr (name: JSXElementName, attrs: Option>) -> Expr { - Expr::JSXElement(Box::new(JSXElement { - span, - opening: JSXOpeningElement { - name, +pub fn create_self_closing_jsx_element_expr(name: JSXElementName, attrs: Option>) -> Expr { + Expr::JSXElement( + Box::new(JSXElement { span, - attrs: attrs.unwrap_or(vec![]), - self_closing: true, - type_args: None - }, - children: vec![], - closing: None - })) + opening: JSXOpeningElement { + name, + span, + attrs: attrs.unwrap_or(vec![]), + self_closing: true, + type_args: None, + }, + children: vec![], + closing: None, + }) + ) } -pub fn create_jsx_expr_attr (name: &str, expr: Box) -> JSXAttrOrSpread { +pub fn create_jsx_expr_attr(name: &str, expr: Box) -> JSXAttrOrSpread { JSXAttrOrSpread::JSXAttr(JSXAttr { span, name: JSXAttrName::Ident(Ident::new(name.into(), span)), - value: Some(JSXAttrValue::JSXExprContainer(JSXExprContainer { - span, - expr: JSXExpr::Expr(expr) - })) + value: Some( + JSXAttrValue::JSXExprContainer(JSXExprContainer { + span, + expr: JSXExpr::Expr(expr), + }) + ), }) } -pub fn create_jsx_bool_attr (name: &str) -> JSXAttrOrSpread { +pub fn create_jsx_bool_attr(name: &str) -> JSXAttrOrSpread { JSXAttrOrSpread::JSXAttr(JSXAttr { span, name: JSXAttrName::Ident(Ident::new(name.into(), span)), - value: None + value: None, }) } -pub fn create_jsx_lit_attr (name: &str, lit: Lit) -> JSXAttrOrSpread { +pub fn create_jsx_lit_attr(name: &str, lit: Lit) -> JSXAttrOrSpread { JSXAttrOrSpread::JSXAttr(JSXAttr { span, name: JSXAttrName::Ident(Ident::new(name.into(), span)), - value: Some(JSXAttrValue::Lit(lit)) + value: Some(JSXAttrValue::Lit(lit)), }) } -pub fn create_jsx_dynamic_id (el: &mut JSXElement, visitor: &mut TransformVisitor) -> String { +pub fn create_jsx_dynamic_id(el: &mut JSXElement, visitor: &mut TransformVisitor) -> String { let node_name = (visitor.get_node_name)(); visitor.node_name_vec.push(node_name.clone()); @@ -201,8 +181,7 @@ pub fn create_jsx_dynamic_id (el: &mut JSXElement, visitor: &mut TransformVisito node_name } -pub fn add_spaces_to_lines(input: &str) -> String { - let count = 2; +pub fn add_spaces_to_lines_with_count(input: &str, count: usize) -> String { let mut result = String::new(); for line in input.lines() { @@ -213,7 +192,13 @@ pub fn add_spaces_to_lines(input: &str) -> String { result } -pub fn get_harmony_component_style (visitor: &mut TransformVisitor) -> String { +pub fn add_spaces_to_lines(input: &str) -> String { + let count = 2; + + add_spaces_to_lines_with_count(input, count) +} + +pub fn get_harmony_component_style(visitor: &mut TransformVisitor) -> String { let component_set = &visitor.component_set; let mut harmony_component_style = String::new(); @@ -223,19 +208,20 @@ pub fn get_harmony_component_style (visitor: &mut TransformVisitor) -> String { } }; - build_component(VIEW_TAG, HARMONY_FLEX_STYLE_BIND); - build_component(IMAGE_TAG, HARMONY_IMAGE_STYLE_BIND); - build_component(TEXT_TAG, HARMONY_TEXT_STYLE_BIND); + // build_component(IMAGE_TAG, HARMONY_IMAGE_STYLE_BIND); + // build_component(TEXT_TAG, HARMONY_TEXT_STYLE_BIND); + build_component(TEXT_TAG, HARMONY_TEXT_BUILDER); + build_component(TEXT_TAG, HARMONY_TEXT_HELPER_FUNCITON); harmony_component_style } -pub fn check_jsx_element_has_compile_ignore (el: &JSXElement) -> bool { +pub fn check_jsx_element_has_compile_ignore(el: &JSXElement) -> bool { for attr in &el.opening.attrs { if let JSXAttrOrSpread::JSXAttr(JSXAttr { name, .. }) = attr { if let JSXAttrName::Ident(Ident { sym, .. }) = name { if sym == COMPILE_IGNORE { - return true + return true; } } } @@ -243,47 +229,49 @@ pub fn check_jsx_element_has_compile_ignore (el: &JSXElement) -> bool { false } + + /** * identify: `xx.map(function () {})` or `xx.map(() => {})` */ -pub fn is_call_expr_of_loop (callee_expr: &mut Box, args: &mut Vec) -> bool { - if let Expr::Member(MemberExpr { prop: MemberProp::Ident(Ident { sym, ..}), .. }) = &mut **callee_expr { +pub fn is_call_expr_of_loop(callee_expr: &mut Box, args: &mut Vec) -> bool { + if let Expr::Member(MemberExpr { prop: MemberProp::Ident(Ident { sym, .. }), .. }) = &mut **callee_expr { if sym == "map" { if let Some(ExprOrSpread { expr, .. }) = args.get_mut(0) { - return expr.is_arrow() || expr.is_fn_expr() + return expr.is_arrow() || expr.is_fn_expr(); } } } - return false + return false; } -pub fn is_render_fn (callee_expr: &mut Box) -> bool { - fn is_starts_with_render (name: &str) -> bool { +pub fn is_render_fn(callee_expr: &mut Box) -> bool { + fn is_starts_with_render(name: &str) -> bool { name.starts_with("render") } match &**callee_expr { - Expr::Member(MemberExpr { prop: MemberProp::Ident(Ident { sym: name, .. }), .. }) => { - is_starts_with_render(name) - }, - Expr::Ident(Ident { sym: name, .. }) => { - is_starts_with_render(name) - }, - _ => false + Expr::Member(MemberExpr { prop: MemberProp::Ident(Ident { sym: name, .. }), .. }) => + is_starts_with_render(name), + Expr::Ident(Ident { sym: name, .. }) => is_starts_with_render(name), + _ => false, } } -pub fn extract_jsx_loop <'a> (callee_expr: &mut Box, args: &'a mut Vec) -> Option<&'a mut Box> { +pub fn extract_jsx_loop<'a>( + callee_expr: &mut Box, + args: &'a mut Vec +) -> Option<&'a mut Box> { if is_call_expr_of_loop(callee_expr, args) { if let Some(ExprOrSpread { expr, .. }) = args.get_mut(0) { - fn update_return_el (return_value: &mut Box) -> Option<&mut Box> { + fn update_return_el(return_value: &mut Box) -> Option<&mut Box> { if let Expr::Paren(ParenExpr { expr, .. }) = &mut **return_value { - *return_value = expr.take() + *return_value = expr.take(); } if return_value.is_jsx_element() { let el = return_value.as_mut_jsx_element().unwrap(); el.opening.attrs.push(create_jsx_bool_attr(COMPILE_FOR)); el.opening.attrs.push(create_jsx_lit_attr(COMPILE_FOR_KEY, Lit::Str(quote_str!("sid")))); - return Some(el) + return Some(el); } None } @@ -294,50 +282,95 @@ pub fn extract_jsx_loop <'a> (callee_expr: &mut Box, args: &'a mut Vec { + } + Expr::Arrow(ArrowExpr { body, .. }) => match &mut **body { BlockStmtOrExpr::BlockStmt(BlockStmt { stmts, .. }) => { if let Some(Stmt::Return(ReturnStmt { arg: Some(return_value), .. })) = stmts.last_mut() { return update_return_el(return_value); } - }, + } BlockStmtOrExpr::Expr(return_value) => { return update_return_el(return_value); } } - }, - _ => () + _ => (), } } } None } -pub fn check_jsx_element_children_exist_loop (el: &mut JSXElement) -> bool { - for child in el.children.iter_mut() { - if let JSXElementChild::JSXExprContainer(JSXExprContainer { expr: JSXExpr::Expr(expr), .. }) = child { - if let Expr::Call(CallExpr { callee: Callee::Expr(callee_expr), args, .. }) = &mut **expr { - if is_call_expr_of_loop(callee_expr, args) { - return true +pub fn get_valid_nodes(children: &Vec) -> usize { + let re = Regex::new(r"^\s*$").unwrap(); + let filtered_children: Vec<&JSXElementChild> = children + .iter() + .filter(|&item| { + match item { + JSXElementChild::JSXText(JSXText { value, .. }) => { + // 用正则判断value是否只含在\n和空格,如果时,返回false + !re.is_match(value) } + _ => true, } + }) + .collect(); + filtered_children.len() +} + +pub fn check_jsx_element_children_exist_loop(el: &mut JSXElement) -> bool { + for child in el.children.iter_mut() { + if check_jsx_element_child_is_loop(child) { + return true; } } false } -pub fn create_original_node_renderer (visitor: &mut TransformVisitor) -> String { - add_spaces_to_lines(format!("ForEach(this.{}.childNodes, item => {{\n createNode(item)\n}}, item => item._nid)", visitor.node_name.last().unwrap().clone()).as_str()) +pub fn check_jsx_element_child_is_loop(child: &mut JSXElementChild) -> bool { + if let JSXElementChild::JSXExprContainer(JSXExprContainer { expr: JSXExpr::Expr(expr), .. }) = child { + if let Expr::Call(CallExpr { callee: Callee::Expr(callee_expr), args, .. }) = &mut **expr { + if is_call_expr_of_loop(callee_expr, args) { + return true; + } + } + } + false +} + +pub fn create_original_node_renderer_foreach(visitor: &mut TransformVisitor) -> String { + add_spaces_to_lines( + format!("createLazyChildren({})", visitor.get_dynmaic_node_name(visitor.get_current_node_path())).as_str() + ) +} + +pub fn create_original_node_renderer(visitor: &mut TransformVisitor) -> String { + add_spaces_to_lines( + format!( + "createChildItem({} as TaroElement, createLazyChildren)", + visitor.get_dynmaic_node_name(visitor.get_current_node_path()) + ).as_str() + ) +} + +pub fn create_normal_text_template(visitor: &mut TransformVisitor, disable_this: bool) -> String { + let node_path = visitor.get_current_node_path(); + + let node_name = if disable_this { String::from("item") } else { visitor.get_dynmaic_node_name(node_path) }; + + let code = add_spaces_to_lines(get_text_component_str(&node_name).as_str()); + + visitor.component_set.insert(TEXT_TAG.to_string()); + code } -pub fn gen_template_v (node_path: &str) -> String { +pub fn gen_template_v(node_path: &str) -> String { format!("{{{{{}.v}}}}", node_path) } #[test] -fn test_jsx_text () { +fn test_jsx_text() { assert_eq!(" span ", jsx_text_to_string(&" span ".into())); assert_eq!(" s xxx ", jsx_text_to_string(&" s\n \n \n xxx ".into())); assert_eq!("a b", jsx_text_to_string(&" \n \n a b \n ".into())); diff --git a/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/attributes.rs/should_handle_events.js b/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/attributes.rs/should_handle_events.js index f12900f30938..c04353621de9 100644 --- a/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/attributes.rs/should_handle_events.js +++ b/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/attributes.rs/should_handle_events.js @@ -1,190 +1,112 @@ -const TARO_TEMPLATES_f0t0 = `import { FlexManager } from './utils/FlexManager' -import { getNodeThresholds, getNormalAttributes, getTextAttributes } from './utils/helper' -import { TaroIgnoreElement, eventHandler, DynamicCenter, getComponentEventCallback, AREA_CHANGE_EVENT_NAME, VISIBLE_CHANGE_EVENT_NAME } from '../runtime' -import type { TaroElement } from '../runtime' -import { TOUCH_EVENT_MAP } from './utils/constant/event' -@Extend(Flex) -function attrs ({ - flexBasis, - flexGrow, - flexShrink, - alignSelf, - clip, - width, - height, - margin, - padding, - linearGradient, - zIndex, - borderStyle, - borderWidth, - borderColor, - borderRadius, - opacity, - backgroundColor, - backgroundImage, - backgroundRepeat, - backgroundImageSize, - constraintSize, - rotate, - scale, - translate, - transform -}) { - .flexGrow(flexGrow) - .flexShrink(flexShrink) - .flexBasis(flexBasis) - .alignSelf(alignSelf) - .width(width) - .height(height) - .constraintSize(constraintSize) - .margin(margin) - .padding(padding) - .linearGradient(linearGradient) - .zIndex(zIndex) - .borderStyle(borderStyle) - .borderWidth(borderWidth) - .borderColor(borderColor) - .borderRadius(borderRadius) - .opacity(opacity) - .backgroundColor(backgroundColor) - .backgroundImage(backgroundImage, backgroundRepeat) - .backgroundImageSize(backgroundImageSize) - .rotate(rotate) - .scale(scale) - .translate(translate) - .transform(transform) - .clip(clip) -} -@Extend(Image) -function attrsImage ({ - flexBasis, - flexGrow, - flexShrink, - alignSelf, - clip, - width, - height, - margin, - padding, - linearGradient, - zIndex, - borderStyle, - borderWidth, - borderColor, - borderRadius, - opacity, - backgroundColor, - backgroundImage, - backgroundRepeat, - backgroundImageSize, - constraintSize, - rotate, - scale, - translate, - transform -}) { - .flexGrow(flexGrow) - .flexShrink(flexShrink) - .flexBasis(flexBasis) - .alignSelf(alignSelf) - .width(width) - .height(height) - .constraintSize(constraintSize) - .margin(margin) - .padding(padding) - .linearGradient(linearGradient) - .zIndex(zIndex) - .borderStyle(borderStyle) - .borderWidth(borderWidth) - .borderColor(borderColor) - .borderRadius(borderRadius) - .opacity(opacity) - .backgroundColor(backgroundColor) - .backgroundImage(backgroundImage, backgroundRepeat) - .backgroundImageSize(backgroundImageSize) - .rotate(rotate) - .scale(scale) - .translate(translate) - .transform(transform) - .clip(clip) - .objectFit(ImageFit.Contain) -} +const TARO_TEMPLATES_f0t0 = `import { + rowModify, + FlexManager, + columnModify, + DynamicCenter, + getButtonColor, + TOUCH_EVENT_MAP, + getFontAttributes, + commonStyleModify, + getNodeThresholds, + BUTTON_THEME_COLOR, + getStyleAttr, + getNormalAttributes, + shouldBindEvent, + textModify, + setNormalTextAttributeIntoInstance, + getImageMode +} from '@tarojs/components' +import { + NodeType, + convertNumber2VP, + TaroElement, + eventHandler, + getComponentEventCallback, + AREA_CHANGE_EVENT_NAME, + VISIBLE_CHANGE_EVENT_NAME +} from '@tarojs/runtime' +import { + createLazyChildren, + createChildItem +} from '../render' + +import type { + TaroTextElement, + HarmonyStyle, + TaroButtonElement, + TaroViewElement, + TaroAny, + TaroStyleType, + TaroTextStyleType +} from '@tarojs/runtime' +import { isString } from '@tarojs/shared' @Component -struct TARO_TEMPLATES_f0t0 { - nodeInfoMap: any = {} - dynamicCenter: DynamicCenter - @ObjectLink node: TaroElement +export default struct TARO_TEMPLATES_f0t0 { + node: TaroViewElement = new TaroElement('Ignore') + + dynamicCenter: DynamicCenter = new DynamicCenter() aboutToAppear () { - this.dynamicCenter = new DynamicCenter() this.dynamicCenter.bindComponentToNodeWithDFS(this.node, this) } - @State node0: TaroElement = new TaroIgnoreElement() - @State node1: TaroElement = new TaroIgnoreElement() - @State node2: TaroElement = new TaroIgnoreElement() + @State node0: TaroElement = new TaroElement('Ignore') + @State node1: TaroElement = new TaroElement('Ignore') + @State node2: TaroElement = new TaroElement('Ignore') build() { - Flex(FlexManager.flexOptions(this.node0)) { - Flex(FlexManager.flexOptions(this.node0.childNodes[0])) {} - .attrs(getNormalAttributes(this.node0.childNodes[0])) - .onVisibleAreaChange(getNodeThresholds(this.node0.childNodes[0]) || [0.0, 1.0], getComponentEventCallback(this.node0.childNodes[0], VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node0.childNodes[0], AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node0.childNodes[0]._nid].areaInfo = areaResult + Column() { + Column() {} + .attributeModifier(columnModify.setNode(this.node0.childNodes[0] as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node0.childNodes[0] as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node0.childNodes[0] as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node0.childNodes[0] as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0.childNodes[0] as TaroElement)._nodeInfo.areaInfo = res[1] })) - .onClick(e => eventHandler(e, 'click', this.node0.childNodes[0])) - Flex(FlexManager.flexOptions(this.node0.childNodes[1])) {} - .attrs(getNormalAttributes(this.node0.childNodes[1])) - .onVisibleAreaChange(getNodeThresholds(this.node0.childNodes[1]) || [0.0, 1.0], getComponentEventCallback(this.node0.childNodes[1], VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node0.childNodes[1], AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node0.childNodes[1]._nid].areaInfo = areaResult + .onClick(e => eventHandler(e, 'click', this.node0.childNodes[0] as TaroElement)) + Column() {} + .attributeModifier(columnModify.setNode(this.node0.childNodes[1] as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node0.childNodes[1] as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node0.childNodes[1] as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node0.childNodes[1] as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0.childNodes[1] as TaroElement)._nodeInfo.areaInfo = res[1] })) - .onClick(e => eventHandler(e, 'click', this.node0.childNodes[1])) - Flex(FlexManager.flexOptions(this.node1)) {} - .attrs(getNormalAttributes(this.node1)) - .onVisibleAreaChange(getNodeThresholds(this.node1) || [0.0, 1.0], getComponentEventCallback(this.node1, VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node1, AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node1._nid].areaInfo = areaResult + .onClick(e => eventHandler(e, 'click', this.node0.childNodes[1] as TaroElement)) + Column() {} + .attributeModifier(columnModify.setNode(this.node1 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node1 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node1 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node1 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node1 as TaroElement)._nodeInfo.areaInfo = res[1] })) - .onClick(e => eventHandler(e, 'click', this.node1)) - Flex(FlexManager.flexOptions(this.node2)) {} - .attrs(getNormalAttributes(this.node2)) - .onVisibleAreaChange(getNodeThresholds(this.node2) || [0.0, 1.0], getComponentEventCallback(this.node2, VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node2, AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node2._nid].areaInfo = areaResult + .onClick(e => eventHandler(e, 'click', this.node1 as TaroElement)) + Column() {} + .attributeModifier(columnModify.setNode(this.node2 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node2 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node2 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node2 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node2 as TaroElement)._nodeInfo.areaInfo = res[1] })) - Image(this.node0.childNodes[4].getAttribute('src')) - .attrsImage(getNormalAttributes(this.node0.childNodes[4])) - .onVisibleAreaChange(getNodeThresholds(this.node0.childNodes[4]) || [0.0, 1.0], getComponentEventCallback(this.node0.childNodes[4], VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node0.childNodes[4], AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node0.childNodes[4]._nid].areaInfo = areaResult + Image((this.node0.childNodes[4] as TaroElement).getAttribute('src')) + .objectFit(getImageMode((this.node0.childNodes[4] as TaroElement).getAttribute('mode'))) + .attributeModifier(commonStyleModify.setNode(this.node0.childNodes[4] as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node0.childNodes[4] as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node0.childNodes[4] as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node0.childNodes[4] as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0.childNodes[4] as TaroElement)._nodeInfo.areaInfo = res[1] })) - .onComplete(e => eventHandler(e, 'complete', this.node0.childNodes[4])) - Flex(FlexManager.flexOptions(this.node0.childNodes[5])) {} - .attrs(getNormalAttributes(this.node0.childNodes[5])) - .onVisibleAreaChange(getNodeThresholds(this.node0.childNodes[5]) || [0.0, 1.0], getComponentEventCallback(this.node0.childNodes[5], VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node0.childNodes[5], AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node0.childNodes[5]._nid].areaInfo = areaResult + .onComplete(e => eventHandler(e, 'complete', this.node0.childNodes[4] as TaroElement)) + Column() {} + .attributeModifier(columnModify.setNode(this.node0.childNodes[5] as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node0.childNodes[5] as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node0.childNodes[5] as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node0.childNodes[5] as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0.childNodes[5] as TaroElement)._nodeInfo.areaInfo = res[1] })) - .onClick(e => eventHandler(e, 'click', this.node0.childNodes[5])) - .onTouch(e => eventHandler(e, TOUCH_EVENT_MAP[e.type], this.node0.childNodes[5])) + .onClick(e => eventHandler(e, 'click', this.node0.childNodes[5] as TaroElement)) + .onTouch(e => eventHandler(e, TOUCH_EVENT_MAP.get(e.type), this.node0.childNodes[5] as TaroElement)) } - .attrs(getNormalAttributes(this.node0)) - .onVisibleAreaChange(getNodeThresholds(this.node0) || [0.0, 1.0], getComponentEventCallback(this.node0, VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node0, AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node0._nid].areaInfo = areaResult + .attributeModifier(columnModify.setNode(this.node0 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node0 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node0 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node0 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0 as TaroElement)._nodeInfo.areaInfo = res[1] })) } } -export default TARO_TEMPLATES_f0t0 `; function Index() { return diff --git a/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/attributes.rs/should_turn_dynamic_attrs.js b/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/attributes.rs/should_turn_dynamic_attrs.js index 70710c618853..c3e63f0c55f8 100644 --- a/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/attributes.rs/should_turn_dynamic_attrs.js +++ b/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/attributes.rs/should_turn_dynamic_attrs.js @@ -1,196 +1,118 @@ -const TARO_TEMPLATES_f0t0 = `import { FlexManager } from './utils/FlexManager' -import { getNodeThresholds, getNormalAttributes, getTextAttributes } from './utils/helper' -import { TaroIgnoreElement, eventHandler, DynamicCenter, getComponentEventCallback, AREA_CHANGE_EVENT_NAME, VISIBLE_CHANGE_EVENT_NAME } from '../runtime' -import type { TaroElement } from '../runtime' -import { TOUCH_EVENT_MAP } from './utils/constant/event' -@Extend(Flex) -function attrs ({ - flexBasis, - flexGrow, - flexShrink, - alignSelf, - clip, - width, - height, - margin, - padding, - linearGradient, - zIndex, - borderStyle, - borderWidth, - borderColor, - borderRadius, - opacity, - backgroundColor, - backgroundImage, - backgroundRepeat, - backgroundImageSize, - constraintSize, - rotate, - scale, - translate, - transform -}) { - .flexGrow(flexGrow) - .flexShrink(flexShrink) - .flexBasis(flexBasis) - .alignSelf(alignSelf) - .width(width) - .height(height) - .constraintSize(constraintSize) - .margin(margin) - .padding(padding) - .linearGradient(linearGradient) - .zIndex(zIndex) - .borderStyle(borderStyle) - .borderWidth(borderWidth) - .borderColor(borderColor) - .borderRadius(borderRadius) - .opacity(opacity) - .backgroundColor(backgroundColor) - .backgroundImage(backgroundImage, backgroundRepeat) - .backgroundImageSize(backgroundImageSize) - .rotate(rotate) - .scale(scale) - .translate(translate) - .transform(transform) - .clip(clip) -} -@Extend(Image) -function attrsImage ({ - flexBasis, - flexGrow, - flexShrink, - alignSelf, - clip, - width, - height, - margin, - padding, - linearGradient, - zIndex, - borderStyle, - borderWidth, - borderColor, - borderRadius, - opacity, - backgroundColor, - backgroundImage, - backgroundRepeat, - backgroundImageSize, - constraintSize, - rotate, - scale, - translate, - transform -}) { - .flexGrow(flexGrow) - .flexShrink(flexShrink) - .flexBasis(flexBasis) - .alignSelf(alignSelf) - .width(width) - .height(height) - .constraintSize(constraintSize) - .margin(margin) - .padding(padding) - .linearGradient(linearGradient) - .zIndex(zIndex) - .borderStyle(borderStyle) - .borderWidth(borderWidth) - .borderColor(borderColor) - .borderRadius(borderRadius) - .opacity(opacity) - .backgroundColor(backgroundColor) - .backgroundImage(backgroundImage, backgroundRepeat) - .backgroundImageSize(backgroundImageSize) - .rotate(rotate) - .scale(scale) - .translate(translate) - .transform(transform) - .clip(clip) - .objectFit(ImageFit.Contain) -} +const TARO_TEMPLATES_f0t0 = `import { + rowModify, + FlexManager, + columnModify, + DynamicCenter, + getButtonColor, + TOUCH_EVENT_MAP, + getFontAttributes, + commonStyleModify, + getNodeThresholds, + BUTTON_THEME_COLOR, + getStyleAttr, + getNormalAttributes, + shouldBindEvent, + textModify, + setNormalTextAttributeIntoInstance, + getImageMode +} from '@tarojs/components' +import { + NodeType, + convertNumber2VP, + TaroElement, + eventHandler, + getComponentEventCallback, + AREA_CHANGE_EVENT_NAME, + VISIBLE_CHANGE_EVENT_NAME +} from '@tarojs/runtime' +import { + createLazyChildren, + createChildItem +} from '../render' + +import type { + TaroTextElement, + HarmonyStyle, + TaroButtonElement, + TaroViewElement, + TaroAny, + TaroStyleType, + TaroTextStyleType +} from '@tarojs/runtime' +import { isString } from '@tarojs/shared' @Component -struct TARO_TEMPLATES_f0t0 { - nodeInfoMap: any = {} - dynamicCenter: DynamicCenter - @ObjectLink node: TaroElement +export default struct TARO_TEMPLATES_f0t0 { + node: TaroViewElement = new TaroElement('Ignore') + + dynamicCenter: DynamicCenter = new DynamicCenter() aboutToAppear () { - this.dynamicCenter = new DynamicCenter() this.dynamicCenter.bindComponentToNodeWithDFS(this.node, this) } - @State node0: TaroElement = new TaroIgnoreElement() - @State node1: TaroElement = new TaroIgnoreElement() - @State node2: TaroElement = new TaroIgnoreElement() - @State node3: TaroElement = new TaroIgnoreElement() - @State node4: TaroElement = new TaroIgnoreElement() - @State node5: TaroElement = new TaroIgnoreElement() + @State node0: TaroElement = new TaroElement('Ignore') + @State node1: TaroElement = new TaroElement('Ignore') + @State node2: TaroElement = new TaroElement('Ignore') + @State node3: TaroElement = new TaroElement('Ignore') + @State node4: TaroElement = new TaroElement('Ignore') + @State node5: TaroElement = new TaroElement('Ignore') build() { - Flex(FlexManager.flexOptions(this.node0)) { - Flex(FlexManager.flexOptions(this.node1)) { - Flex(FlexManager.flexOptions(this.node2)) {} - .attrs(getNormalAttributes(this.node2)) - .onVisibleAreaChange(getNodeThresholds(this.node2) || [0.0, 1.0], getComponentEventCallback(this.node2, VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node2, AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node2._nid].areaInfo = areaResult + Column() { + Column() { + Column() {} + .attributeModifier(columnModify.setNode(this.node2 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node2 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node2 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node2 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node2 as TaroElement)._nodeInfo.areaInfo = res[1] })) - Flex(FlexManager.flexOptions(this.node1.childNodes[1])) {} - .attrs(getNormalAttributes(this.node1.childNodes[1])) - .onVisibleAreaChange(getNodeThresholds(this.node1.childNodes[1]) || [0.0, 1.0], getComponentEventCallback(this.node1.childNodes[1], VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node1.childNodes[1], AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node1.childNodes[1]._nid].areaInfo = areaResult + Column() {} + .attributeModifier(columnModify.setNode(this.node1.childNodes[1] as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node1.childNodes[1] as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node1.childNodes[1] as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node1.childNodes[1] as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node1.childNodes[1] as TaroElement)._nodeInfo.areaInfo = res[1] })) - Flex(FlexManager.flexOptions(this.node3)) { - Flex(FlexManager.flexOptions(this.node4)) {} - .attrs(getNormalAttributes(this.node4)) - .onVisibleAreaChange(getNodeThresholds(this.node4) || [0.0, 1.0], getComponentEventCallback(this.node4, VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node4, AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node4._nid].areaInfo = areaResult + Column() { + Column() {} + .attributeModifier(columnModify.setNode(this.node4 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node4 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node4 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node4 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node4 as TaroElement)._nodeInfo.areaInfo = res[1] })) } - .attrs(getNormalAttributes(this.node3)) - .onVisibleAreaChange(getNodeThresholds(this.node3) || [0.0, 1.0], getComponentEventCallback(this.node3, VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node3, AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node3._nid].areaInfo = areaResult + .attributeModifier(columnModify.setNode(this.node3 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node3 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node3 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node3 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node3 as TaroElement)._nodeInfo.areaInfo = res[1] })) } - .attrs(getNormalAttributes(this.node1)) - .onVisibleAreaChange(getNodeThresholds(this.node1) || [0.0, 1.0], getComponentEventCallback(this.node1, VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node1, AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node1._nid].areaInfo = areaResult + .attributeModifier(columnModify.setNode(this.node1 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node1 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node1 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node1 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node1 as TaroElement)._nodeInfo.areaInfo = res[1] })) - Image(this.node0.childNodes[1].getAttribute('src')) - .attrsImage(getNormalAttributes(this.node0.childNodes[1])) - .onVisibleAreaChange(getNodeThresholds(this.node0.childNodes[1]) || [0.0, 1.0], getComponentEventCallback(this.node0.childNodes[1], VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node0.childNodes[1], AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node0.childNodes[1]._nid].areaInfo = areaResult + Image((this.node0.childNodes[1] as TaroElement).getAttribute('src')) + .objectFit(getImageMode((this.node0.childNodes[1] as TaroElement).getAttribute('mode'))) + .attributeModifier(commonStyleModify.setNode(this.node0.childNodes[1] as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node0.childNodes[1] as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node0.childNodes[1] as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node0.childNodes[1] as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0.childNodes[1] as TaroElement)._nodeInfo.areaInfo = res[1] })) - Image(this.node5.getAttribute('src')) - .attrsImage(getNormalAttributes(this.node5)) - .onVisibleAreaChange(getNodeThresholds(this.node5) || [0.0, 1.0], getComponentEventCallback(this.node5, VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node5, AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node5._nid].areaInfo = areaResult + Image((this.node5 as TaroElement).getAttribute('src')) + .objectFit(getImageMode((this.node5 as TaroElement).getAttribute('mode'))) + .attributeModifier(commonStyleModify.setNode(this.node5 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node5 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node5 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node5 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node5 as TaroElement)._nodeInfo.areaInfo = res[1] })) } - .attrs(getNormalAttributes(this.node0)) - .onVisibleAreaChange(getNodeThresholds(this.node0) || [0.0, 1.0], getComponentEventCallback(this.node0, VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node0, AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node0._nid].areaInfo = areaResult + .attributeModifier(columnModify.setNode(this.node0 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node0 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node0 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node0 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0 as TaroElement)._nodeInfo.areaInfo = res[1] })) } } -export default TARO_TEMPLATES_f0t0 `; function Index() { return diff --git a/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/children.rs/should_render_complex_children.js b/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/children.rs/should_render_complex_children.js new file mode 100644 index 000000000000..ff31fa3089f1 --- /dev/null +++ b/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/children.rs/should_render_complex_children.js @@ -0,0 +1,126 @@ +const TARO_TEMPLATES_f0t0 = `import { + rowModify, + FlexManager, + columnModify, + DynamicCenter, + getButtonColor, + TOUCH_EVENT_MAP, + getFontAttributes, + commonStyleModify, + getNodeThresholds, + BUTTON_THEME_COLOR, + getStyleAttr, + getNormalAttributes, + shouldBindEvent, + textModify, + setNormalTextAttributeIntoInstance, + getImageMode +} from '@tarojs/components' +import { + NodeType, + convertNumber2VP, + TaroElement, + eventHandler, + getComponentEventCallback, + AREA_CHANGE_EVENT_NAME, + VISIBLE_CHANGE_EVENT_NAME +} from '@tarojs/runtime' +import { + createLazyChildren, + createChildItem +} from '../render' + +import type { + TaroTextElement, + HarmonyStyle, + TaroButtonElement, + TaroViewElement, + TaroAny, + TaroStyleType, + TaroTextStyleType +} from '@tarojs/runtime' +import { isString } from '@tarojs/shared' +@Component +export default struct TARO_TEMPLATES_f0t0 { + node: TaroViewElement = new TaroElement('Ignore') + + dynamicCenter: DynamicCenter = new DynamicCenter() + + aboutToAppear () { + this.dynamicCenter.bindComponentToNodeWithDFS(this.node, this) + } + + @State node0: TaroElement = new TaroElement('Ignore') + @State node1: TaroElement = new TaroElement('Ignore') + @State node2: TaroElement = new TaroElement('Ignore') + @State node3: TaroElement = new TaroElement('Ignore') + @State node4: TaroElement = new TaroElement('Ignore') + + build() { + Column() { + if ((this.node0.childNodes[0] as TaroElement)._attrs.compileIf) { + Column() { + Column() { + Image((this.node3 as TaroElement).getAttribute('src')) + .objectFit(getImageMode((this.node3 as TaroElement).getAttribute('mode'))) + .attributeModifier(commonStyleModify.setNode(this.node3 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node3 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node3 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node3 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node3 as TaroElement)._nodeInfo.areaInfo = res[1] + })) + if ((this.node2.childNodes[1] as TaroElement)._attrs.compileIf) { + Image((this.node4 as TaroElement).getAttribute('src')) + .objectFit(getImageMode((this.node4 as TaroElement).getAttribute('mode'))) + .attributeModifier(commonStyleModify.setNode(this.node4 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node4 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node4 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node4 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node4 as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } + } + .attributeModifier(columnModify.setNode(this.node2 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node2 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node2 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node2 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node2 as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } + .attributeModifier(columnModify.setNode(this.node1 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node1 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node1 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node1 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node1 as TaroElement)._nodeInfo.areaInfo = res[1] + })) + .onClick(e => eventHandler(e, 'click', this.node1 as TaroElement)) + } + } + .attributeModifier(columnModify.setNode(this.node0 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node0 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node0 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node0 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0 as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } +} +`; +function Index() { + return + + {showModal ? + + + + + + {haveIcon ? : } + + + + : } + + ; +} diff --git a/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/children.rs/should_render_react_component.js b/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/children.rs/should_render_react_component.js new file mode 100644 index 000000000000..ec676c09424e --- /dev/null +++ b/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/children.rs/should_render_react_component.js @@ -0,0 +1,77 @@ +const TARO_TEMPLATES_f0t0 = `import { + rowModify, + FlexManager, + columnModify, + DynamicCenter, + getButtonColor, + TOUCH_EVENT_MAP, + getFontAttributes, + commonStyleModify, + getNodeThresholds, + BUTTON_THEME_COLOR, + getStyleAttr, + getNormalAttributes, + shouldBindEvent, + textModify, + setNormalTextAttributeIntoInstance, + getImageMode +} from '@tarojs/components' +import { + NodeType, + convertNumber2VP, + TaroElement, + eventHandler, + getComponentEventCallback, + AREA_CHANGE_EVENT_NAME, + VISIBLE_CHANGE_EVENT_NAME +} from '@tarojs/runtime' +import { + createLazyChildren, + createChildItem +} from '../render' + +import type { + TaroTextElement, + HarmonyStyle, + TaroButtonElement, + TaroViewElement, + TaroAny, + TaroStyleType, + TaroTextStyleType +} from '@tarojs/runtime' +import { isString } from '@tarojs/shared' +@Component +export default struct TARO_TEMPLATES_f0t0 { + node: TaroViewElement = new TaroElement('Ignore') + + dynamicCenter: DynamicCenter = new DynamicCenter() + + aboutToAppear () { + this.dynamicCenter.bindComponentToNodeWithDFS(this.node, this) + } + + @State node0: TaroElement = new TaroElement('Ignore') + @State node1: TaroElement = new TaroElement('Ignore') + + build() { + Column() { + createChildItem(this.node0.childNodes[0] as TaroElement, createLazyChildren) + createChildItem(this.node1 as TaroElement, createLazyChildren) + } + .attributeModifier(columnModify.setNode(this.node0 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node0 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node0 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node0 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0 as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } +} +`; +function Index() { + return + + + + {}} _dynamicID="node1"/> + + ; +} diff --git a/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/children.rs/should_support_fragment.js b/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/children.rs/should_support_fragment.js new file mode 100644 index 000000000000..06c9b159d32d --- /dev/null +++ b/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/children.rs/should_support_fragment.js @@ -0,0 +1,656 @@ +const TARO_TEMPLATES_f0t0 = `import { + rowModify, + FlexManager, + columnModify, + DynamicCenter, + getButtonColor, + TOUCH_EVENT_MAP, + getFontAttributes, + commonStyleModify, + getNodeThresholds, + BUTTON_THEME_COLOR, + getStyleAttr, + getNormalAttributes, + shouldBindEvent, + textModify, + setNormalTextAttributeIntoInstance, + getImageMode +} from '@tarojs/components' +import { + NodeType, + convertNumber2VP, + TaroElement, + eventHandler, + getComponentEventCallback, + AREA_CHANGE_EVENT_NAME, + VISIBLE_CHANGE_EVENT_NAME +} from '@tarojs/runtime' +import { + createLazyChildren, + createChildItem +} from '../render' + +import type { + TaroTextElement, + HarmonyStyle, + TaroButtonElement, + TaroViewElement, + TaroAny, + TaroStyleType, + TaroTextStyleType +} from '@tarojs/runtime' +import { isString } from '@tarojs/shared' +@Extend(Text) +function textNormalFontStyle (style: HarmonyStyle) { + .id(style.id) + .key(style.id) + .opacity(style.opacity) + .fontColor(style.color) + .fontSize(style.fontSize) + .fontWeight(style.fontWeight) + .fontStyle(style.fontStyle) + .fontFamily(style.fontFamily) + .lineHeight(style.lineHeight) + .decoration({ + type: style.textDecoration?.type, + color: style.color + }) +} + +@Extend(Text) +function textSpecialFontStyle(attr: TaroTextStyleType) { + .textAlign(attr.textAlign) + .textOverflow(attr.textOverflow) + .maxLines(attr.WebkitLineClamp) + .letterSpacing(attr.letterSpacing) +} + +function getButtonFontSize (node: TaroButtonElement) { + const isMini = node._attrs.size === 'mini' + + return isMini ? convertNumber2VP(26) : convertNumber2VP(36) +} + +@Builder +function createTextChildNode (item: TaroElement, align: ImageSpanAlignment) { + if (item.tagName === 'IMAGE') { + ImageSpan(item.getAttribute('src')) + .objectFit(getImageMode(item.getAttribute('mode'))) + .verticalAlign(align) + .width(item._st.hmStyle.width) + .height(item._st.hmStyle.height) + .margin({ + top: item._st.hmStyle.marginTop, + left: item._st.hmStyle.marginLeft, + right: item._st.hmStyle.marginRight, + bottom: item._st.hmStyle.marginBottom, + }) + .padding({ + top: item._st.hmStyle.paddingTop, + left: item._st.hmStyle.paddingLeft, + right: item._st.hmStyle.paddingRight, + bottom: item._st.hmStyle.paddingBottom, + }) + .textBackgroundStyle({ + color: item._st.hmStyle.backgroundColor, + radius: { + topLeft: item._st.hmStyle.borderTopLeftRadius, + topRight: item._st.hmStyle.borderTopRightRadius, + bottomLeft: item._st.hmStyle.borderBottomLeftRadius, + bottomRight: item._st.hmStyle.borderBottomRightRadius, + } + }) + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', item), item, ['click'])) + } else if (item.nodeType === NodeType.TEXT_NODE) { + Span(item.textContent) + } else if (item.tagName === 'TEXT') { + Span(item.textContent) + .attributeModifier((new SpanStyleModify()).setNode(item as TaroTextElement)) + .letterSpacing(item._st.hmStyle.letterSpacing) + .textBackgroundStyle({ + color: item._st.hmStyle.backgroundColor, + radius: { + topLeft: item._st.hmStyle.borderTopLeftRadius, + topRight: item._st.hmStyle.borderTopRightRadius, + bottomLeft: item._st.hmStyle.borderBottomLeftRadius, + bottomRight: item._st.hmStyle.borderBottomRightRadius, + } + }) + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', item), item, ['click'])) + } +} + +class SpanStyleModify implements AttributeModifier { + node: TaroTextElement | null = null + style: HarmonyStyle | null = null + overwriteStyle: Record = {} + withNormal = false + + setNode (node: TaroTextElement) { + this.node = node + this.style = getNormalAttributes(this.node) + return this + } + + applyNormalAttribute(instance: SpanAttribute): void { + if (this.node && this.style) { + setNormalTextAttributeIntoInstance(instance, this.style, this.node) + } + } +} + +function getSpanVerticalAlign (verticalAlign?: Alignment) { + switch (verticalAlign) { + case Alignment.Start: + case Alignment.TopStart: + case Alignment.Top: + case Alignment.TopEnd: { + return ImageSpanAlignment.TOP + } + case Alignment.End: + case Alignment.BottomStart: + case Alignment.Bottom: + case Alignment.BottomEnd: { + return ImageSpanAlignment.BOTTOM + } + case Alignment.Center: { + return ImageSpanAlignment.CENTER + } + } + return ImageSpanAlignment.BASELINE +} + +function getTextInViewWidth (node: TaroElement | null): TaroAny { + if (node) { + const hmStyle = node.hmStyle || {} + const isFlexView = hmStyle.display === 'flex' + const width: TaroAny = getStyleAttr(node, 'width') + const isPercentWidth = isString(width) && width.includes('%') + + return isFlexView || isPercentWidth ? null : getStyleAttr(node, 'width') + } +} + +@Component +export default struct TARO_TEMPLATES_f0t0 { + node: TaroViewElement = new TaroElement('Ignore') + + dynamicCenter: DynamicCenter = new DynamicCenter() + + aboutToAppear () { + this.dynamicCenter.bindComponentToNodeWithDFS(this.node, this) + } + + @State node0: TaroElement = new TaroElement('Ignore') + @State node1: TaroElement = new TaroElement('Ignore') + @State node2: TaroElement = new TaroElement('Ignore') + @State node3: TaroElement = new TaroElement('Ignore') + @State node4: TaroElement = new TaroElement('Ignore') + @State node5: TaroElement = new TaroElement('Ignore') + @State node6: TaroElement = new TaroElement('Ignore') + + build() { + Column() { + if (this.node0.childNodes[0].nodeType === NodeType.TEXT_NODE) { + if (this.node0.childNodes[0].parentNode) { + if ((this.node0.childNodes[0].parentNode as TaroElement).tagName === 'BUTTON') { + Text(this.node0.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node0.childNodes[0]?.parentElement as TaroElement, { + fontSize: getButtonFontSize(this.node0.childNodes[0].parentNode as TaroButtonElement), + color: getButtonColor(this.node0.childNodes[0].parentNode as TaroButtonElement, BUTTON_THEME_COLOR.get((this.node0.childNodes[0].parentNode as TaroButtonElement)._attrs.type || '').text) + })) + } else { + Text(this.node0.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node0.childNodes[0]?.parentElement as TaroElement)) + .width(getTextInViewWidth(this.node0.childNodes[0].parentElement)) + } + } + } else { + Text(this.node0.childNodes[0].textContent) { + // text 下还有标签 + if (this.node0.childNodes[0].childNodes.length > 1 || ((this.node0.childNodes[0].childNodes[0] && this.node0.childNodes[0].childNodes[0] as TaroElement)?.nodeType === NodeType.ELEMENT_NODE)) { + ForEach(this.node0.childNodes[0].childNodes, (item: TaroElement) => { + createTextChildNode(item, getSpanVerticalAlign((this.node0.childNodes[0] as TaroElement).hmStyle?.verticalAlign)) + }, (item: TaroElement) => item._nid) + } + } + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', this.node0.childNodes[0] as TaroElement), this.node0.childNodes[0] as TaroElement, ['click'])) + .attributeModifier(textModify.setNode(this.node0.childNodes[0] as TaroElement).withNormalStyle()) + .onVisibleAreaChange(getNodeThresholds((this.node0.childNodes[0] as TaroElement)) || [0.0, 1.0], getComponentEventCallback((this.node0.childNodes[0] as TaroElement), VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback((this.node0.childNodes[0] as TaroElement), AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0.childNodes[0] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } + Column() { + if (this.node1.childNodes[0].nodeType === NodeType.TEXT_NODE) { + if (this.node1.childNodes[0].parentNode) { + if ((this.node1.childNodes[0].parentNode as TaroElement).tagName === 'BUTTON') { + Text(this.node1.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node1.childNodes[0]?.parentElement as TaroElement, { + fontSize: getButtonFontSize(this.node1.childNodes[0].parentNode as TaroButtonElement), + color: getButtonColor(this.node1.childNodes[0].parentNode as TaroButtonElement, BUTTON_THEME_COLOR.get((this.node1.childNodes[0].parentNode as TaroButtonElement)._attrs.type || '').text) + })) + } else { + Text(this.node1.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node1.childNodes[0]?.parentElement as TaroElement)) + .width(getTextInViewWidth(this.node1.childNodes[0].parentElement)) + } + } + } else { + Text(this.node1.childNodes[0].textContent) { + // text 下还有标签 + if (this.node1.childNodes[0].childNodes.length > 1 || ((this.node1.childNodes[0].childNodes[0] && this.node1.childNodes[0].childNodes[0] as TaroElement)?.nodeType === NodeType.ELEMENT_NODE)) { + ForEach(this.node1.childNodes[0].childNodes, (item: TaroElement) => { + createTextChildNode(item, getSpanVerticalAlign((this.node1.childNodes[0] as TaroElement).hmStyle?.verticalAlign)) + }, (item: TaroElement) => item._nid) + } + } + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', this.node1.childNodes[0] as TaroElement), this.node1.childNodes[0] as TaroElement, ['click'])) + .attributeModifier(textModify.setNode(this.node1.childNodes[0] as TaroElement).withNormalStyle()) + .onVisibleAreaChange(getNodeThresholds((this.node1.childNodes[0] as TaroElement)) || [0.0, 1.0], getComponentEventCallback((this.node1.childNodes[0] as TaroElement), VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback((this.node1.childNodes[0] as TaroElement), AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node1.childNodes[0] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } + } + .attributeModifier(columnModify.setNode(this.node1 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node1 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node1 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node1 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node1 as TaroElement)._nodeInfo.areaInfo = res[1] + })) + Column() { + if (this.node0.childNodes[2].childNodes[0].nodeType === NodeType.TEXT_NODE) { + if (this.node0.childNodes[2].childNodes[0].parentNode) { + if ((this.node0.childNodes[2].childNodes[0].parentNode as TaroElement).tagName === 'BUTTON') { + Text(this.node0.childNodes[2].childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node0.childNodes[2].childNodes[0]?.parentElement as TaroElement, { + fontSize: getButtonFontSize(this.node0.childNodes[2].childNodes[0].parentNode as TaroButtonElement), + color: getButtonColor(this.node0.childNodes[2].childNodes[0].parentNode as TaroButtonElement, BUTTON_THEME_COLOR.get((this.node0.childNodes[2].childNodes[0].parentNode as TaroButtonElement)._attrs.type || '').text) + })) + } else { + Text(this.node0.childNodes[2].childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node0.childNodes[2].childNodes[0]?.parentElement as TaroElement)) + .width(getTextInViewWidth(this.node0.childNodes[2].childNodes[0].parentElement)) + } + } + } else { + Text(this.node0.childNodes[2].childNodes[0].textContent) { + // text 下还有标签 + if (this.node0.childNodes[2].childNodes[0].childNodes.length > 1 || ((this.node0.childNodes[2].childNodes[0].childNodes[0] && this.node0.childNodes[2].childNodes[0].childNodes[0] as TaroElement)?.nodeType === NodeType.ELEMENT_NODE)) { + ForEach(this.node0.childNodes[2].childNodes[0].childNodes, (item: TaroElement) => { + createTextChildNode(item, getSpanVerticalAlign((this.node0.childNodes[2].childNodes[0] as TaroElement).hmStyle?.verticalAlign)) + }, (item: TaroElement) => item._nid) + } + } + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', this.node0.childNodes[2].childNodes[0] as TaroElement), this.node0.childNodes[2].childNodes[0] as TaroElement, ['click'])) + .attributeModifier(textModify.setNode(this.node0.childNodes[2].childNodes[0] as TaroElement).withNormalStyle()) + .onVisibleAreaChange(getNodeThresholds((this.node0.childNodes[2].childNodes[0] as TaroElement)) || [0.0, 1.0], getComponentEventCallback((this.node0.childNodes[2].childNodes[0] as TaroElement), VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback((this.node0.childNodes[2].childNodes[0] as TaroElement), AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0.childNodes[2].childNodes[0] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } + } + .attributeModifier(columnModify.setNode(this.node0.childNodes[2] as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node0.childNodes[2] as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node0.childNodes[2] as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node0.childNodes[2] as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0.childNodes[2] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + Column() { + Column() { + if (this.node2.childNodes[0].nodeType === NodeType.TEXT_NODE) { + if (this.node2.childNodes[0].parentNode) { + if ((this.node2.childNodes[0].parentNode as TaroElement).tagName === 'BUTTON') { + Text(this.node2.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node2.childNodes[0]?.parentElement as TaroElement, { + fontSize: getButtonFontSize(this.node2.childNodes[0].parentNode as TaroButtonElement), + color: getButtonColor(this.node2.childNodes[0].parentNode as TaroButtonElement, BUTTON_THEME_COLOR.get((this.node2.childNodes[0].parentNode as TaroButtonElement)._attrs.type || '').text) + })) + } else { + Text(this.node2.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node2.childNodes[0]?.parentElement as TaroElement)) + .width(getTextInViewWidth(this.node2.childNodes[0].parentElement)) + } + } + } else { + Text(this.node2.childNodes[0].textContent) { + // text 下还有标签 + if (this.node2.childNodes[0].childNodes.length > 1 || ((this.node2.childNodes[0].childNodes[0] && this.node2.childNodes[0].childNodes[0] as TaroElement)?.nodeType === NodeType.ELEMENT_NODE)) { + ForEach(this.node2.childNodes[0].childNodes, (item: TaroElement) => { + createTextChildNode(item, getSpanVerticalAlign((this.node2.childNodes[0] as TaroElement).hmStyle?.verticalAlign)) + }, (item: TaroElement) => item._nid) + } + } + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', this.node2.childNodes[0] as TaroElement), this.node2.childNodes[0] as TaroElement, ['click'])) + .attributeModifier(textModify.setNode(this.node2.childNodes[0] as TaroElement).withNormalStyle()) + .onVisibleAreaChange(getNodeThresholds((this.node2.childNodes[0] as TaroElement)) || [0.0, 1.0], getComponentEventCallback((this.node2.childNodes[0] as TaroElement), VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback((this.node2.childNodes[0] as TaroElement), AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node2.childNodes[0] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } + } + .attributeModifier(columnModify.setNode(this.node2 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node2 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node2 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node2 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node2 as TaroElement)._nodeInfo.areaInfo = res[1] + })) + Column() { + if (this.node0.childNodes[3].childNodes[1].childNodes[0].nodeType === NodeType.TEXT_NODE) { + if (this.node0.childNodes[3].childNodes[1].childNodes[0].parentNode) { + if ((this.node0.childNodes[3].childNodes[1].childNodes[0].parentNode as TaroElement).tagName === 'BUTTON') { + Text(this.node0.childNodes[3].childNodes[1].childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node0.childNodes[3].childNodes[1].childNodes[0]?.parentElement as TaroElement, { + fontSize: getButtonFontSize(this.node0.childNodes[3].childNodes[1].childNodes[0].parentNode as TaroButtonElement), + color: getButtonColor(this.node0.childNodes[3].childNodes[1].childNodes[0].parentNode as TaroButtonElement, BUTTON_THEME_COLOR.get((this.node0.childNodes[3].childNodes[1].childNodes[0].parentNode as TaroButtonElement)._attrs.type || '').text) + })) + } else { + Text(this.node0.childNodes[3].childNodes[1].childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node0.childNodes[3].childNodes[1].childNodes[0]?.parentElement as TaroElement)) + .width(getTextInViewWidth(this.node0.childNodes[3].childNodes[1].childNodes[0].parentElement)) + } + } + } else { + Text(this.node0.childNodes[3].childNodes[1].childNodes[0].textContent) { + // text 下还有标签 + if (this.node0.childNodes[3].childNodes[1].childNodes[0].childNodes.length > 1 || ((this.node0.childNodes[3].childNodes[1].childNodes[0].childNodes[0] && this.node0.childNodes[3].childNodes[1].childNodes[0].childNodes[0] as TaroElement)?.nodeType === NodeType.ELEMENT_NODE)) { + ForEach(this.node0.childNodes[3].childNodes[1].childNodes[0].childNodes, (item: TaroElement) => { + createTextChildNode(item, getSpanVerticalAlign((this.node0.childNodes[3].childNodes[1].childNodes[0] as TaroElement).hmStyle?.verticalAlign)) + }, (item: TaroElement) => item._nid) + } + } + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', this.node0.childNodes[3].childNodes[1].childNodes[0] as TaroElement), this.node0.childNodes[3].childNodes[1].childNodes[0] as TaroElement, ['click'])) + .attributeModifier(textModify.setNode(this.node0.childNodes[3].childNodes[1].childNodes[0] as TaroElement).withNormalStyle()) + .onVisibleAreaChange(getNodeThresholds((this.node0.childNodes[3].childNodes[1].childNodes[0] as TaroElement)) || [0.0, 1.0], getComponentEventCallback((this.node0.childNodes[3].childNodes[1].childNodes[0] as TaroElement), VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback((this.node0.childNodes[3].childNodes[1].childNodes[0] as TaroElement), AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0.childNodes[3].childNodes[1].childNodes[0] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } + } + .attributeModifier(columnModify.setNode(this.node0.childNodes[3].childNodes[1] as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node0.childNodes[3].childNodes[1] as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node0.childNodes[3].childNodes[1] as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node0.childNodes[3].childNodes[1] as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0.childNodes[3].childNodes[1] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } + .attributeModifier(columnModify.setNode(this.node0.childNodes[3] as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node0.childNodes[3] as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node0.childNodes[3] as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node0.childNodes[3] as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0.childNodes[3] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + Column() { + if (this.node3.childNodes[0].nodeType === NodeType.TEXT_NODE) { + if (this.node3.childNodes[0].parentNode) { + if ((this.node3.childNodes[0].parentNode as TaroElement).tagName === 'BUTTON') { + Text(this.node3.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node3.childNodes[0]?.parentElement as TaroElement, { + fontSize: getButtonFontSize(this.node3.childNodes[0].parentNode as TaroButtonElement), + color: getButtonColor(this.node3.childNodes[0].parentNode as TaroButtonElement, BUTTON_THEME_COLOR.get((this.node3.childNodes[0].parentNode as TaroButtonElement)._attrs.type || '').text) + })) + } else { + Text(this.node3.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node3.childNodes[0]?.parentElement as TaroElement)) + .width(getTextInViewWidth(this.node3.childNodes[0].parentElement)) + } + } + } else { + Text(this.node3.childNodes[0].textContent) { + // text 下还有标签 + if (this.node3.childNodes[0].childNodes.length > 1 || ((this.node3.childNodes[0].childNodes[0] && this.node3.childNodes[0].childNodes[0] as TaroElement)?.nodeType === NodeType.ELEMENT_NODE)) { + ForEach(this.node3.childNodes[0].childNodes, (item: TaroElement) => { + createTextChildNode(item, getSpanVerticalAlign((this.node3.childNodes[0] as TaroElement).hmStyle?.verticalAlign)) + }, (item: TaroElement) => item._nid) + } + } + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', this.node3.childNodes[0] as TaroElement), this.node3.childNodes[0] as TaroElement, ['click'])) + .attributeModifier(textModify.setNode(this.node3.childNodes[0] as TaroElement).withNormalStyle()) + .onVisibleAreaChange(getNodeThresholds((this.node3.childNodes[0] as TaroElement)) || [0.0, 1.0], getComponentEventCallback((this.node3.childNodes[0] as TaroElement), VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback((this.node3.childNodes[0] as TaroElement), AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node3.childNodes[0] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } + } + .attributeModifier(columnModify.setNode(this.node3 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node3 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node3 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node3 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node3 as TaroElement)._nodeInfo.areaInfo = res[1] + })) + Column() { + if (this.node4.childNodes[0].nodeType === NodeType.TEXT_NODE) { + if (this.node4.childNodes[0].parentNode) { + if ((this.node4.childNodes[0].parentNode as TaroElement).tagName === 'BUTTON') { + Text(this.node4.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node4.childNodes[0]?.parentElement as TaroElement, { + fontSize: getButtonFontSize(this.node4.childNodes[0].parentNode as TaroButtonElement), + color: getButtonColor(this.node4.childNodes[0].parentNode as TaroButtonElement, BUTTON_THEME_COLOR.get((this.node4.childNodes[0].parentNode as TaroButtonElement)._attrs.type || '').text) + })) + } else { + Text(this.node4.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node4.childNodes[0]?.parentElement as TaroElement)) + .width(getTextInViewWidth(this.node4.childNodes[0].parentElement)) + } + } + } else { + Text(this.node4.childNodes[0].textContent) { + // text 下还有标签 + if (this.node4.childNodes[0].childNodes.length > 1 || ((this.node4.childNodes[0].childNodes[0] && this.node4.childNodes[0].childNodes[0] as TaroElement)?.nodeType === NodeType.ELEMENT_NODE)) { + ForEach(this.node4.childNodes[0].childNodes, (item: TaroElement) => { + createTextChildNode(item, getSpanVerticalAlign((this.node4.childNodes[0] as TaroElement).hmStyle?.verticalAlign)) + }, (item: TaroElement) => item._nid) + } + } + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', this.node4.childNodes[0] as TaroElement), this.node4.childNodes[0] as TaroElement, ['click'])) + .attributeModifier(textModify.setNode(this.node4.childNodes[0] as TaroElement).withNormalStyle()) + .onVisibleAreaChange(getNodeThresholds((this.node4.childNodes[0] as TaroElement)) || [0.0, 1.0], getComponentEventCallback((this.node4.childNodes[0] as TaroElement), VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback((this.node4.childNodes[0] as TaroElement), AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node4.childNodes[0] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } + } + .attributeModifier(columnModify.setNode(this.node4 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node4 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node4 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node4 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node4 as TaroElement)._nodeInfo.areaInfo = res[1] + })) + Column() { + if (this.node5.childNodes[0].nodeType === NodeType.TEXT_NODE) { + if (this.node5.childNodes[0].parentNode) { + if ((this.node5.childNodes[0].parentNode as TaroElement).tagName === 'BUTTON') { + Text(this.node5.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node5.childNodes[0]?.parentElement as TaroElement, { + fontSize: getButtonFontSize(this.node5.childNodes[0].parentNode as TaroButtonElement), + color: getButtonColor(this.node5.childNodes[0].parentNode as TaroButtonElement, BUTTON_THEME_COLOR.get((this.node5.childNodes[0].parentNode as TaroButtonElement)._attrs.type || '').text) + })) + } else { + Text(this.node5.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node5.childNodes[0]?.parentElement as TaroElement)) + .width(getTextInViewWidth(this.node5.childNodes[0].parentElement)) + } + } + } else { + Text(this.node5.childNodes[0].textContent) { + // text 下还有标签 + if (this.node5.childNodes[0].childNodes.length > 1 || ((this.node5.childNodes[0].childNodes[0] && this.node5.childNodes[0].childNodes[0] as TaroElement)?.nodeType === NodeType.ELEMENT_NODE)) { + ForEach(this.node5.childNodes[0].childNodes, (item: TaroElement) => { + createTextChildNode(item, getSpanVerticalAlign((this.node5.childNodes[0] as TaroElement).hmStyle?.verticalAlign)) + }, (item: TaroElement) => item._nid) + } + } + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', this.node5.childNodes[0] as TaroElement), this.node5.childNodes[0] as TaroElement, ['click'])) + .attributeModifier(textModify.setNode(this.node5.childNodes[0] as TaroElement).withNormalStyle()) + .onVisibleAreaChange(getNodeThresholds((this.node5.childNodes[0] as TaroElement)) || [0.0, 1.0], getComponentEventCallback((this.node5.childNodes[0] as TaroElement), VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback((this.node5.childNodes[0] as TaroElement), AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node5.childNodes[0] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } + } + .attributeModifier(columnModify.setNode(this.node5 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node5 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node5 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node5 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node5 as TaroElement)._nodeInfo.areaInfo = res[1] + })) + Column() { + if (this.node0.childNodes[7].childNodes[0].nodeType === NodeType.TEXT_NODE) { + if (this.node0.childNodes[7].childNodes[0].parentNode) { + if ((this.node0.childNodes[7].childNodes[0].parentNode as TaroElement).tagName === 'BUTTON') { + Text(this.node0.childNodes[7].childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node0.childNodes[7].childNodes[0]?.parentElement as TaroElement, { + fontSize: getButtonFontSize(this.node0.childNodes[7].childNodes[0].parentNode as TaroButtonElement), + color: getButtonColor(this.node0.childNodes[7].childNodes[0].parentNode as TaroButtonElement, BUTTON_THEME_COLOR.get((this.node0.childNodes[7].childNodes[0].parentNode as TaroButtonElement)._attrs.type || '').text) + })) + } else { + Text(this.node0.childNodes[7].childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node0.childNodes[7].childNodes[0]?.parentElement as TaroElement)) + .width(getTextInViewWidth(this.node0.childNodes[7].childNodes[0].parentElement)) + } + } + } else { + Text(this.node0.childNodes[7].childNodes[0].textContent) { + // text 下还有标签 + if (this.node0.childNodes[7].childNodes[0].childNodes.length > 1 || ((this.node0.childNodes[7].childNodes[0].childNodes[0] && this.node0.childNodes[7].childNodes[0].childNodes[0] as TaroElement)?.nodeType === NodeType.ELEMENT_NODE)) { + ForEach(this.node0.childNodes[7].childNodes[0].childNodes, (item: TaroElement) => { + createTextChildNode(item, getSpanVerticalAlign((this.node0.childNodes[7].childNodes[0] as TaroElement).hmStyle?.verticalAlign)) + }, (item: TaroElement) => item._nid) + } + } + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', this.node0.childNodes[7].childNodes[0] as TaroElement), this.node0.childNodes[7].childNodes[0] as TaroElement, ['click'])) + .attributeModifier(textModify.setNode(this.node0.childNodes[7].childNodes[0] as TaroElement).withNormalStyle()) + .onVisibleAreaChange(getNodeThresholds((this.node0.childNodes[7].childNodes[0] as TaroElement)) || [0.0, 1.0], getComponentEventCallback((this.node0.childNodes[7].childNodes[0] as TaroElement), VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback((this.node0.childNodes[7].childNodes[0] as TaroElement), AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0.childNodes[7].childNodes[0] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } + } + .attributeModifier(columnModify.setNode(this.node0.childNodes[7] as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node0.childNodes[7] as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node0.childNodes[7] as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node0.childNodes[7] as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0.childNodes[7] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + Column() { + if (this.node0.childNodes[8].childNodes[0].nodeType === NodeType.TEXT_NODE) { + if (this.node0.childNodes[8].childNodes[0].parentNode) { + if ((this.node0.childNodes[8].childNodes[0].parentNode as TaroElement).tagName === 'BUTTON') { + Text(this.node0.childNodes[8].childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node0.childNodes[8].childNodes[0]?.parentElement as TaroElement, { + fontSize: getButtonFontSize(this.node0.childNodes[8].childNodes[0].parentNode as TaroButtonElement), + color: getButtonColor(this.node0.childNodes[8].childNodes[0].parentNode as TaroButtonElement, BUTTON_THEME_COLOR.get((this.node0.childNodes[8].childNodes[0].parentNode as TaroButtonElement)._attrs.type || '').text) + })) + } else { + Text(this.node0.childNodes[8].childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node0.childNodes[8].childNodes[0]?.parentElement as TaroElement)) + .width(getTextInViewWidth(this.node0.childNodes[8].childNodes[0].parentElement)) + } + } + } else { + Text(this.node0.childNodes[8].childNodes[0].textContent) { + // text 下还有标签 + if (this.node0.childNodes[8].childNodes[0].childNodes.length > 1 || ((this.node0.childNodes[8].childNodes[0].childNodes[0] && this.node0.childNodes[8].childNodes[0].childNodes[0] as TaroElement)?.nodeType === NodeType.ELEMENT_NODE)) { + ForEach(this.node0.childNodes[8].childNodes[0].childNodes, (item: TaroElement) => { + createTextChildNode(item, getSpanVerticalAlign((this.node0.childNodes[8].childNodes[0] as TaroElement).hmStyle?.verticalAlign)) + }, (item: TaroElement) => item._nid) + } + } + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', this.node0.childNodes[8].childNodes[0] as TaroElement), this.node0.childNodes[8].childNodes[0] as TaroElement, ['click'])) + .attributeModifier(textModify.setNode(this.node0.childNodes[8].childNodes[0] as TaroElement).withNormalStyle()) + .onVisibleAreaChange(getNodeThresholds((this.node0.childNodes[8].childNodes[0] as TaroElement)) || [0.0, 1.0], getComponentEventCallback((this.node0.childNodes[8].childNodes[0] as TaroElement), VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback((this.node0.childNodes[8].childNodes[0] as TaroElement), AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0.childNodes[8].childNodes[0] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } + } + .attributeModifier(columnModify.setNode(this.node0.childNodes[8] as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node0.childNodes[8] as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node0.childNodes[8] as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node0.childNodes[8] as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0.childNodes[8] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + Column() { + if (this.node6.childNodes[0].nodeType === NodeType.TEXT_NODE) { + if (this.node6.childNodes[0].parentNode) { + if ((this.node6.childNodes[0].parentNode as TaroElement).tagName === 'BUTTON') { + Text(this.node6.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node6.childNodes[0]?.parentElement as TaroElement, { + fontSize: getButtonFontSize(this.node6.childNodes[0].parentNode as TaroButtonElement), + color: getButtonColor(this.node6.childNodes[0].parentNode as TaroButtonElement, BUTTON_THEME_COLOR.get((this.node6.childNodes[0].parentNode as TaroButtonElement)._attrs.type || '').text) + })) + } else { + Text(this.node6.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node6.childNodes[0]?.parentElement as TaroElement)) + .width(getTextInViewWidth(this.node6.childNodes[0].parentElement)) + } + } + } else { + Text(this.node6.childNodes[0].textContent) { + // text 下还有标签 + if (this.node6.childNodes[0].childNodes.length > 1 || ((this.node6.childNodes[0].childNodes[0] && this.node6.childNodes[0].childNodes[0] as TaroElement)?.nodeType === NodeType.ELEMENT_NODE)) { + ForEach(this.node6.childNodes[0].childNodes, (item: TaroElement) => { + createTextChildNode(item, getSpanVerticalAlign((this.node6.childNodes[0] as TaroElement).hmStyle?.verticalAlign)) + }, (item: TaroElement) => item._nid) + } + } + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', this.node6.childNodes[0] as TaroElement), this.node6.childNodes[0] as TaroElement, ['click'])) + .attributeModifier(textModify.setNode(this.node6.childNodes[0] as TaroElement).withNormalStyle()) + .onVisibleAreaChange(getNodeThresholds((this.node6.childNodes[0] as TaroElement)) || [0.0, 1.0], getComponentEventCallback((this.node6.childNodes[0] as TaroElement), VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback((this.node6.childNodes[0] as TaroElement), AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node6.childNodes[0] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } + } + .attributeModifier(columnModify.setNode(this.node6 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node6 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node6 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node6 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node6 as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } + .attributeModifier(columnModify.setNode(this.node0 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node0 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node0 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node0 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0 as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } +} +`; +function Index() { + return + + {content0} + + <> + + {content1} + + hello + + + + <> + + {content2} + + hello! + + + + + + {content3} + + + + {content4} + + <> + + {content5} + + + + <> + + hello!! + + + + hello!!! + + {content6} + + ; +} diff --git a/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/children.rs/should_support_render_fn.js b/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/children.rs/should_support_render_fn.js new file mode 100644 index 000000000000..d685f7bb7c2e --- /dev/null +++ b/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/children.rs/should_support_render_fn.js @@ -0,0 +1,310 @@ +const TARO_TEMPLATES_f0t0 = `import { + rowModify, + FlexManager, + columnModify, + DynamicCenter, + getButtonColor, + TOUCH_EVENT_MAP, + getFontAttributes, + commonStyleModify, + getNodeThresholds, + BUTTON_THEME_COLOR, + getStyleAttr, + getNormalAttributes, + shouldBindEvent, + textModify, + setNormalTextAttributeIntoInstance, + getImageMode +} from '@tarojs/components' +import { + NodeType, + convertNumber2VP, + TaroElement, + eventHandler, + getComponentEventCallback, + AREA_CHANGE_EVENT_NAME, + VISIBLE_CHANGE_EVENT_NAME +} from '@tarojs/runtime' +import { + createLazyChildren, + createChildItem +} from '../render' + +import type { + TaroTextElement, + HarmonyStyle, + TaroButtonElement, + TaroViewElement, + TaroAny, + TaroStyleType, + TaroTextStyleType +} from '@tarojs/runtime' +import { isString } from '@tarojs/shared' +@Extend(Text) +function textNormalFontStyle (style: HarmonyStyle) { + .id(style.id) + .key(style.id) + .opacity(style.opacity) + .fontColor(style.color) + .fontSize(style.fontSize) + .fontWeight(style.fontWeight) + .fontStyle(style.fontStyle) + .fontFamily(style.fontFamily) + .lineHeight(style.lineHeight) + .decoration({ + type: style.textDecoration?.type, + color: style.color + }) +} + +@Extend(Text) +function textSpecialFontStyle(attr: TaroTextStyleType) { + .textAlign(attr.textAlign) + .textOverflow(attr.textOverflow) + .maxLines(attr.WebkitLineClamp) + .letterSpacing(attr.letterSpacing) +} + +function getButtonFontSize (node: TaroButtonElement) { + const isMini = node._attrs.size === 'mini' + + return isMini ? convertNumber2VP(26) : convertNumber2VP(36) +} + +@Builder +function createTextChildNode (item: TaroElement, align: ImageSpanAlignment) { + if (item.tagName === 'IMAGE') { + ImageSpan(item.getAttribute('src')) + .objectFit(getImageMode(item.getAttribute('mode'))) + .verticalAlign(align) + .width(item._st.hmStyle.width) + .height(item._st.hmStyle.height) + .margin({ + top: item._st.hmStyle.marginTop, + left: item._st.hmStyle.marginLeft, + right: item._st.hmStyle.marginRight, + bottom: item._st.hmStyle.marginBottom, + }) + .padding({ + top: item._st.hmStyle.paddingTop, + left: item._st.hmStyle.paddingLeft, + right: item._st.hmStyle.paddingRight, + bottom: item._st.hmStyle.paddingBottom, + }) + .textBackgroundStyle({ + color: item._st.hmStyle.backgroundColor, + radius: { + topLeft: item._st.hmStyle.borderTopLeftRadius, + topRight: item._st.hmStyle.borderTopRightRadius, + bottomLeft: item._st.hmStyle.borderBottomLeftRadius, + bottomRight: item._st.hmStyle.borderBottomRightRadius, + } + }) + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', item), item, ['click'])) + } else if (item.nodeType === NodeType.TEXT_NODE) { + Span(item.textContent) + } else if (item.tagName === 'TEXT') { + Span(item.textContent) + .attributeModifier((new SpanStyleModify()).setNode(item as TaroTextElement)) + .letterSpacing(item._st.hmStyle.letterSpacing) + .textBackgroundStyle({ + color: item._st.hmStyle.backgroundColor, + radius: { + topLeft: item._st.hmStyle.borderTopLeftRadius, + topRight: item._st.hmStyle.borderTopRightRadius, + bottomLeft: item._st.hmStyle.borderBottomLeftRadius, + bottomRight: item._st.hmStyle.borderBottomRightRadius, + } + }) + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', item), item, ['click'])) + } +} + +class SpanStyleModify implements AttributeModifier { + node: TaroTextElement | null = null + style: HarmonyStyle | null = null + overwriteStyle: Record = {} + withNormal = false + + setNode (node: TaroTextElement) { + this.node = node + this.style = getNormalAttributes(this.node) + return this + } + + applyNormalAttribute(instance: SpanAttribute): void { + if (this.node && this.style) { + setNormalTextAttributeIntoInstance(instance, this.style, this.node) + } + } +} + +function getSpanVerticalAlign (verticalAlign?: Alignment) { + switch (verticalAlign) { + case Alignment.Start: + case Alignment.TopStart: + case Alignment.Top: + case Alignment.TopEnd: { + return ImageSpanAlignment.TOP + } + case Alignment.End: + case Alignment.BottomStart: + case Alignment.Bottom: + case Alignment.BottomEnd: { + return ImageSpanAlignment.BOTTOM + } + case Alignment.Center: { + return ImageSpanAlignment.CENTER + } + } + return ImageSpanAlignment.BASELINE +} + +function getTextInViewWidth (node: TaroElement | null): TaroAny { + if (node) { + const hmStyle = node.hmStyle || {} + const isFlexView = hmStyle.display === 'flex' + const width: TaroAny = getStyleAttr(node, 'width') + const isPercentWidth = isString(width) && width.includes('%') + + return isFlexView || isPercentWidth ? null : getStyleAttr(node, 'width') + } +} + +@Component +export default struct TARO_TEMPLATES_f0t0 { + node: TaroViewElement = new TaroElement('Ignore') + + dynamicCenter: DynamicCenter = new DynamicCenter() + + aboutToAppear () { + this.dynamicCenter.bindComponentToNodeWithDFS(this.node, this) + } + + @State node0: TaroElement = new TaroElement('Ignore') + @State node1: TaroElement = new TaroElement('Ignore') + @State node2: TaroElement = new TaroElement('Ignore') + @State node3: TaroElement = new TaroElement('Ignore') + @State node4: TaroElement = new TaroElement('Ignore') + + build() { + Column() { + Column() { + createChildItem(this.node1.childNodes[0] as TaroElement, createLazyChildren) + } + .attributeModifier(columnModify.setNode(this.node1 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node1 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node1 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node1 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node1 as TaroElement)._nodeInfo.areaInfo = res[1] + })) + Column() { + createChildItem(this.node2.childNodes[0] as TaroElement, createLazyChildren) + if (this.node2.childNodes[1].nodeType === NodeType.TEXT_NODE) { + if (this.node2.childNodes[1].parentNode) { + if ((this.node2.childNodes[1].parentNode as TaroElement).tagName === 'BUTTON') { + Text(this.node2.childNodes[1].textContent) + .attributeModifier(textModify.setNode(this.node2.childNodes[1]?.parentElement as TaroElement, { + fontSize: getButtonFontSize(this.node2.childNodes[1].parentNode as TaroButtonElement), + color: getButtonColor(this.node2.childNodes[1].parentNode as TaroButtonElement, BUTTON_THEME_COLOR.get((this.node2.childNodes[1].parentNode as TaroButtonElement)._attrs.type || '').text) + })) + } else { + Text(this.node2.childNodes[1].textContent) + .attributeModifier(textModify.setNode(this.node2.childNodes[1]?.parentElement as TaroElement)) + .width(getTextInViewWidth(this.node2.childNodes[1].parentElement)) + } + } + } else { + Text(this.node2.childNodes[1].textContent) { + // text 下还有标签 + if (this.node2.childNodes[1].childNodes.length > 1 || ((this.node2.childNodes[1].childNodes[0] && this.node2.childNodes[1].childNodes[0] as TaroElement)?.nodeType === NodeType.ELEMENT_NODE)) { + ForEach(this.node2.childNodes[1].childNodes, (item: TaroElement) => { + createTextChildNode(item, getSpanVerticalAlign((this.node2.childNodes[1] as TaroElement).hmStyle?.verticalAlign)) + }, (item: TaroElement) => item._nid) + } + } + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', this.node2.childNodes[1] as TaroElement), this.node2.childNodes[1] as TaroElement, ['click'])) + .attributeModifier(textModify.setNode(this.node2.childNodes[1] as TaroElement).withNormalStyle()) + .onVisibleAreaChange(getNodeThresholds((this.node2.childNodes[1] as TaroElement)) || [0.0, 1.0], getComponentEventCallback((this.node2.childNodes[1] as TaroElement), VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback((this.node2.childNodes[1] as TaroElement), AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node2.childNodes[1] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } + } + .attributeModifier(columnModify.setNode(this.node2 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node2 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node2 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node2 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node2 as TaroElement)._nodeInfo.areaInfo = res[1] + })) + Column() { + createChildItem(this.node3.childNodes[0] as TaroElement, createLazyChildren) + } + .attributeModifier(columnModify.setNode(this.node3 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node3 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node3 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node3 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node3 as TaroElement)._nodeInfo.areaInfo = res[1] + })) + Column() { + if (this.node4.childNodes[0].nodeType === NodeType.TEXT_NODE) { + if (this.node4.childNodes[0].parentNode) { + if ((this.node4.childNodes[0].parentNode as TaroElement).tagName === 'BUTTON') { + Text(this.node4.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node4.childNodes[0]?.parentElement as TaroElement, { + fontSize: getButtonFontSize(this.node4.childNodes[0].parentNode as TaroButtonElement), + color: getButtonColor(this.node4.childNodes[0].parentNode as TaroButtonElement, BUTTON_THEME_COLOR.get((this.node4.childNodes[0].parentNode as TaroButtonElement)._attrs.type || '').text) + })) + } else { + Text(this.node4.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node4.childNodes[0]?.parentElement as TaroElement)) + .width(getTextInViewWidth(this.node4.childNodes[0].parentElement)) + } + } + } else { + Text(this.node4.childNodes[0].textContent) { + // text 下还有标签 + if (this.node4.childNodes[0].childNodes.length > 1 || ((this.node4.childNodes[0].childNodes[0] && this.node4.childNodes[0].childNodes[0] as TaroElement)?.nodeType === NodeType.ELEMENT_NODE)) { + ForEach(this.node4.childNodes[0].childNodes, (item: TaroElement) => { + createTextChildNode(item, getSpanVerticalAlign((this.node4.childNodes[0] as TaroElement).hmStyle?.verticalAlign)) + }, (item: TaroElement) => item._nid) + } + } + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', this.node4.childNodes[0] as TaroElement), this.node4.childNodes[0] as TaroElement, ['click'])) + .attributeModifier(textModify.setNode(this.node4.childNodes[0] as TaroElement).withNormalStyle()) + .onVisibleAreaChange(getNodeThresholds((this.node4.childNodes[0] as TaroElement)) || [0.0, 1.0], getComponentEventCallback((this.node4.childNodes[0] as TaroElement), VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback((this.node4.childNodes[0] as TaroElement), AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node4.childNodes[0] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } + } + .attributeModifier(columnModify.setNode(this.node4 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node4 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node4 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node4 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node4 as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } + .attributeModifier(columnModify.setNode(this.node0 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node0 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node0 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node0 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0 as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } +} +`; +function Index() { + return + + {renderHeader()} + + + + {renderHeader()} + + {normalFunc()} + + + + {this.methods.renderFooter()} + + {normalFunc()} + + ; +} diff --git a/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/condition.rs/should_support_and_expr.js b/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/condition.rs/should_support_and_expr.js index c697916ebea1..f2947d14d973 100644 --- a/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/condition.rs/should_support_and_expr.js +++ b/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/condition.rs/should_support_and_expr.js @@ -1,236 +1,388 @@ -const TARO_TEMPLATES_f0t0 = `import { FlexManager } from './utils/FlexManager' -import { getNodeThresholds, getNormalAttributes, getTextAttributes } from './utils/helper' -import { TaroIgnoreElement, eventHandler, DynamicCenter, getComponentEventCallback, AREA_CHANGE_EVENT_NAME, VISIBLE_CHANGE_EVENT_NAME } from '../runtime' -import type { TaroElement } from '../runtime' -import { TOUCH_EVENT_MAP } from './utils/constant/event' -@Extend(Flex) -function attrs ({ - flexBasis, - flexGrow, - flexShrink, - alignSelf, - clip, - width, - height, - margin, - padding, - linearGradient, - zIndex, - borderStyle, - borderWidth, - borderColor, - borderRadius, - opacity, - backgroundColor, - backgroundImage, - backgroundRepeat, - backgroundImageSize, - constraintSize, - rotate, - scale, - translate, - transform -}) { - .flexGrow(flexGrow) - .flexShrink(flexShrink) - .flexBasis(flexBasis) - .alignSelf(alignSelf) - .width(width) - .height(height) - .constraintSize(constraintSize) - .margin(margin) - .padding(padding) - .linearGradient(linearGradient) - .zIndex(zIndex) - .borderStyle(borderStyle) - .borderWidth(borderWidth) - .borderColor(borderColor) - .borderRadius(borderRadius) - .opacity(opacity) - .backgroundColor(backgroundColor) - .backgroundImage(backgroundImage, backgroundRepeat) - .backgroundImageSize(backgroundImageSize) - .rotate(rotate) - .scale(scale) - .translate(translate) - .transform(transform) - .clip(clip) +const TARO_TEMPLATES_f0t0 = `import { + rowModify, + FlexManager, + columnModify, + DynamicCenter, + getButtonColor, + TOUCH_EVENT_MAP, + getFontAttributes, + commonStyleModify, + getNodeThresholds, + BUTTON_THEME_COLOR, + getStyleAttr, + getNormalAttributes, + shouldBindEvent, + textModify, + setNormalTextAttributeIntoInstance, + getImageMode +} from '@tarojs/components' +import { + NodeType, + convertNumber2VP, + TaroElement, + eventHandler, + getComponentEventCallback, + AREA_CHANGE_EVENT_NAME, + VISIBLE_CHANGE_EVENT_NAME +} from '@tarojs/runtime' +import { + createLazyChildren, + createChildItem +} from '../render' + +import type { + TaroTextElement, + HarmonyStyle, + TaroButtonElement, + TaroViewElement, + TaroAny, + TaroStyleType, + TaroTextStyleType +} from '@tarojs/runtime' +import { isString } from '@tarojs/shared' +@Extend(Text) +function textNormalFontStyle (style: HarmonyStyle) { + .id(style.id) + .key(style.id) + .opacity(style.opacity) + .fontColor(style.color) + .fontSize(style.fontSize) + .fontWeight(style.fontWeight) + .fontStyle(style.fontStyle) + .fontFamily(style.fontFamily) + .lineHeight(style.lineHeight) + .decoration({ + type: style.textDecoration?.type, + color: style.color + }) } + @Extend(Text) -function attrsText ({ - id, - width, - height, - zIndex, - opacity, - margin, - padding, - decoration, - lineHeight, - letterSpacing, - maxLines, - fontColor, - fontSize, - fontWeight, - fontFamily, - textOverflow, - constraintSize, - border, - borderRadius, - backgroundColor, - backgroundImage, - backgroundRepeat, - backgroundImageSize, - rotate, - scale, - translate, - transform, - textAlign, - }) { - .id(id) - .key(id) - .constraintSize(constraintSize) - .zIndex(zIndex) - .opacity(opacity) - .margin(margin) - .padding(padding) - .decoration(decoration) - .lineHeight(lineHeight) - .letterSpacing(letterSpacing) - .maxLines(maxLines) - .fontColor(fontColor) - .fontSize(fontSize) - .fontWeight(fontWeight) - .fontFamily(fontFamily) - .textOverflow(textOverflow) - .border(border) - .borderRadius(borderRadius) - .backgroundColor(backgroundColor) - .backgroundImage(backgroundImage, backgroundRepeat) - .backgroundImageSize(backgroundImageSize) - .rotate(rotate) - .scale(scale) - .translate(translate) - .transform(transform) - .textAlign(textAlign) - .width(width) - .height(height) +function textSpecialFontStyle(attr: TaroTextStyleType) { + .textAlign(attr.textAlign) + .textOverflow(attr.textOverflow) + .maxLines(attr.WebkitLineClamp) + .letterSpacing(attr.letterSpacing) +} + +function getButtonFontSize (node: TaroButtonElement) { + const isMini = node._attrs.size === 'mini' + + return isMini ? convertNumber2VP(26) : convertNumber2VP(36) +} + +@Builder +function createTextChildNode (item: TaroElement, align: ImageSpanAlignment) { + if (item.tagName === 'IMAGE') { + ImageSpan(item.getAttribute('src')) + .objectFit(getImageMode(item.getAttribute('mode'))) + .verticalAlign(align) + .width(item._st.hmStyle.width) + .height(item._st.hmStyle.height) + .margin({ + top: item._st.hmStyle.marginTop, + left: item._st.hmStyle.marginLeft, + right: item._st.hmStyle.marginRight, + bottom: item._st.hmStyle.marginBottom, + }) + .padding({ + top: item._st.hmStyle.paddingTop, + left: item._st.hmStyle.paddingLeft, + right: item._st.hmStyle.paddingRight, + bottom: item._st.hmStyle.paddingBottom, + }) + .textBackgroundStyle({ + color: item._st.hmStyle.backgroundColor, + radius: { + topLeft: item._st.hmStyle.borderTopLeftRadius, + topRight: item._st.hmStyle.borderTopRightRadius, + bottomLeft: item._st.hmStyle.borderBottomLeftRadius, + bottomRight: item._st.hmStyle.borderBottomRightRadius, + } + }) + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', item), item, ['click'])) + } else if (item.nodeType === NodeType.TEXT_NODE) { + Span(item.textContent) + } else if (item.tagName === 'TEXT') { + Span(item.textContent) + .attributeModifier((new SpanStyleModify()).setNode(item as TaroTextElement)) + .letterSpacing(item._st.hmStyle.letterSpacing) + .textBackgroundStyle({ + color: item._st.hmStyle.backgroundColor, + radius: { + topLeft: item._st.hmStyle.borderTopLeftRadius, + topRight: item._st.hmStyle.borderTopRightRadius, + bottomLeft: item._st.hmStyle.borderBottomLeftRadius, + bottomRight: item._st.hmStyle.borderBottomRightRadius, + } + }) + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', item), item, ['click'])) + } +} + +class SpanStyleModify implements AttributeModifier { + node: TaroTextElement | null = null + style: HarmonyStyle | null = null + overwriteStyle: Record = {} + withNormal = false + + setNode (node: TaroTextElement) { + this.node = node + this.style = getNormalAttributes(this.node) + return this + } + + applyNormalAttribute(instance: SpanAttribute): void { + if (this.node && this.style) { + setNormalTextAttributeIntoInstance(instance, this.style, this.node) + } + } } -function getTextAttributes (node: TaroViewElement) { - const attrs = { - ...getNormalAttributes(node), - ...getFontAttributes(node) +function getSpanVerticalAlign (verticalAlign?: Alignment) { + switch (verticalAlign) { + case Alignment.Start: + case Alignment.TopStart: + case Alignment.Top: + case Alignment.TopEnd: { + return ImageSpanAlignment.TOP + } + case Alignment.End: + case Alignment.BottomStart: + case Alignment.Bottom: + case Alignment.BottomEnd: { + return ImageSpanAlignment.BOTTOM + } + case Alignment.Center: { + return ImageSpanAlignment.CENTER + } } + return ImageSpanAlignment.BASELINE +} - transformW3CToHarmonyInStyle(node._st, attrs) +function getTextInViewWidth (node: TaroElement | null): TaroAny { + if (node) { + const hmStyle = node.hmStyle || {} + const isFlexView = hmStyle.display === 'flex' + const width: TaroAny = getStyleAttr(node, 'width') + const isPercentWidth = isString(width) && width.includes('%') - return attrs + return isFlexView || isPercentWidth ? null : getStyleAttr(node, 'width') + } } + @Component -struct TARO_TEMPLATES_f0t0 { - nodeInfoMap: any = {} - dynamicCenter: DynamicCenter - @ObjectLink node: TaroElement +export default struct TARO_TEMPLATES_f0t0 { + node: TaroViewElement = new TaroElement('Ignore') + + dynamicCenter: DynamicCenter = new DynamicCenter() aboutToAppear () { - this.dynamicCenter = new DynamicCenter() this.dynamicCenter.bindComponentToNodeWithDFS(this.node, this) } - @State node0: TaroElement = new TaroIgnoreElement() - @State node1: TaroElement = new TaroIgnoreElement() - @State node2: TaroElement = new TaroIgnoreElement() - @State node3: TaroElement = new TaroIgnoreElement() - @State node4: TaroElement = new TaroIgnoreElement() + @State node0: TaroElement = new TaroElement('Ignore') + @State node1: TaroElement = new TaroElement('Ignore') + @State node2: TaroElement = new TaroElement('Ignore') + @State node3: TaroElement = new TaroElement('Ignore') + @State node4: TaroElement = new TaroElement('Ignore') build() { - Flex(FlexManager.flexOptions(this.node0)) { - if (this.node0.childNodes[0]._attrs.compileIf) { - Flex(FlexManager.flexOptions(this.node1)) { - Text(this.node1.childNodes[0].textContent) - .attrsText(getTextAttributes(this.node1.childNodes[0])) - .onVisibleAreaChange(getNodeThresholds(this.node1.childNodes[0]) || [0.0, 1.0], getComponentEventCallback(this.node1.childNodes[0], VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node1.childNodes[0], AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node1.childNodes[0]._nid].areaInfo = areaResult - })) + Column() { + if ((this.node0.childNodes[0] as TaroElement)._attrs.compileIf) { + Column() { + if (this.node1.childNodes[0].nodeType === NodeType.TEXT_NODE) { + if (this.node1.childNodes[0].parentNode) { + if ((this.node1.childNodes[0].parentNode as TaroElement).tagName === 'BUTTON') { + Text(this.node1.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node1.childNodes[0]?.parentElement as TaroElement, { + fontSize: getButtonFontSize(this.node1.childNodes[0].parentNode as TaroButtonElement), + color: getButtonColor(this.node1.childNodes[0].parentNode as TaroButtonElement, BUTTON_THEME_COLOR.get((this.node1.childNodes[0].parentNode as TaroButtonElement)._attrs.type || '').text) + })) + } else { + Text(this.node1.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node1.childNodes[0]?.parentElement as TaroElement)) + .width(getTextInViewWidth(this.node1.childNodes[0].parentElement)) + } + } + } else { + Text(this.node1.childNodes[0].textContent) { + // text 下还有标签 + if (this.node1.childNodes[0].childNodes.length > 1 || ((this.node1.childNodes[0].childNodes[0] && this.node1.childNodes[0].childNodes[0] as TaroElement)?.nodeType === NodeType.ELEMENT_NODE)) { + ForEach(this.node1.childNodes[0].childNodes, (item: TaroElement) => { + createTextChildNode(item, getSpanVerticalAlign((this.node1.childNodes[0] as TaroElement).hmStyle?.verticalAlign)) + }, (item: TaroElement) => item._nid) + } + } + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', this.node1.childNodes[0] as TaroElement), this.node1.childNodes[0] as TaroElement, ['click'])) + .attributeModifier(textModify.setNode(this.node1.childNodes[0] as TaroElement).withNormalStyle()) + .onVisibleAreaChange(getNodeThresholds((this.node1.childNodes[0] as TaroElement)) || [0.0, 1.0], getComponentEventCallback((this.node1.childNodes[0] as TaroElement), VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback((this.node1.childNodes[0] as TaroElement), AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node1.childNodes[0] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } } - .attrs(getNormalAttributes(this.node1)) - .onVisibleAreaChange(getNodeThresholds(this.node1) || [0.0, 1.0], getComponentEventCallback(this.node1, VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node1, AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node1._nid].areaInfo = areaResult + .attributeModifier(columnModify.setNode(this.node1 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node1 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node1 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node1 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node1 as TaroElement)._nodeInfo.areaInfo = res[1] })) } - if (this.node0.childNodes[1]._attrs.compileIf) { - Flex(FlexManager.flexOptions(this.node2)) { - Text(this.node2.childNodes[0].textContent) - .attrsText(getTextAttributes(this.node2.childNodes[0])) - .onVisibleAreaChange(getNodeThresholds(this.node2.childNodes[0]) || [0.0, 1.0], getComponentEventCallback(this.node2.childNodes[0], VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node2.childNodes[0], AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node2.childNodes[0]._nid].areaInfo = areaResult - })) + if ((this.node0.childNodes[1] as TaroElement)._attrs.compileIf) { + Column() { + if (this.node2.childNodes[0].nodeType === NodeType.TEXT_NODE) { + if (this.node2.childNodes[0].parentNode) { + if ((this.node2.childNodes[0].parentNode as TaroElement).tagName === 'BUTTON') { + Text(this.node2.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node2.childNodes[0]?.parentElement as TaroElement, { + fontSize: getButtonFontSize(this.node2.childNodes[0].parentNode as TaroButtonElement), + color: getButtonColor(this.node2.childNodes[0].parentNode as TaroButtonElement, BUTTON_THEME_COLOR.get((this.node2.childNodes[0].parentNode as TaroButtonElement)._attrs.type || '').text) + })) + } else { + Text(this.node2.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node2.childNodes[0]?.parentElement as TaroElement)) + .width(getTextInViewWidth(this.node2.childNodes[0].parentElement)) + } + } + } else { + Text(this.node2.childNodes[0].textContent) { + // text 下还有标签 + if (this.node2.childNodes[0].childNodes.length > 1 || ((this.node2.childNodes[0].childNodes[0] && this.node2.childNodes[0].childNodes[0] as TaroElement)?.nodeType === NodeType.ELEMENT_NODE)) { + ForEach(this.node2.childNodes[0].childNodes, (item: TaroElement) => { + createTextChildNode(item, getSpanVerticalAlign((this.node2.childNodes[0] as TaroElement).hmStyle?.verticalAlign)) + }, (item: TaroElement) => item._nid) + } + } + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', this.node2.childNodes[0] as TaroElement), this.node2.childNodes[0] as TaroElement, ['click'])) + .attributeModifier(textModify.setNode(this.node2.childNodes[0] as TaroElement).withNormalStyle()) + .onVisibleAreaChange(getNodeThresholds((this.node2.childNodes[0] as TaroElement)) || [0.0, 1.0], getComponentEventCallback((this.node2.childNodes[0] as TaroElement), VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback((this.node2.childNodes[0] as TaroElement), AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node2.childNodes[0] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } } - .attrs(getNormalAttributes(this.node2)) - .onVisibleAreaChange(getNodeThresholds(this.node2) || [0.0, 1.0], getComponentEventCallback(this.node2, VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node2, AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node2._nid].areaInfo = areaResult + .attributeModifier(columnModify.setNode(this.node2 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node2 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node2 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node2 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node2 as TaroElement)._nodeInfo.areaInfo = res[1] })) } - if (this.node0.childNodes[2]._attrs.compileIf) { - Flex(FlexManager.flexOptions(this.node3)) { - Text(this.node3.childNodes[0].textContent) - .attrsText(getTextAttributes(this.node3.childNodes[0])) - .onVisibleAreaChange(getNodeThresholds(this.node3.childNodes[0]) || [0.0, 1.0], getComponentEventCallback(this.node3.childNodes[0], VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node3.childNodes[0], AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node3.childNodes[0]._nid].areaInfo = areaResult - })) + if ((this.node0.childNodes[2] as TaroElement)._attrs.compileIf) { + Column() { + if (this.node3.childNodes[0].nodeType === NodeType.TEXT_NODE) { + if (this.node3.childNodes[0].parentNode) { + if ((this.node3.childNodes[0].parentNode as TaroElement).tagName === 'BUTTON') { + Text(this.node3.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node3.childNodes[0]?.parentElement as TaroElement, { + fontSize: getButtonFontSize(this.node3.childNodes[0].parentNode as TaroButtonElement), + color: getButtonColor(this.node3.childNodes[0].parentNode as TaroButtonElement, BUTTON_THEME_COLOR.get((this.node3.childNodes[0].parentNode as TaroButtonElement)._attrs.type || '').text) + })) + } else { + Text(this.node3.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node3.childNodes[0]?.parentElement as TaroElement)) + .width(getTextInViewWidth(this.node3.childNodes[0].parentElement)) + } + } + } else { + Text(this.node3.childNodes[0].textContent) { + // text 下还有标签 + if (this.node3.childNodes[0].childNodes.length > 1 || ((this.node3.childNodes[0].childNodes[0] && this.node3.childNodes[0].childNodes[0] as TaroElement)?.nodeType === NodeType.ELEMENT_NODE)) { + ForEach(this.node3.childNodes[0].childNodes, (item: TaroElement) => { + createTextChildNode(item, getSpanVerticalAlign((this.node3.childNodes[0] as TaroElement).hmStyle?.verticalAlign)) + }, (item: TaroElement) => item._nid) + } + } + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', this.node3.childNodes[0] as TaroElement), this.node3.childNodes[0] as TaroElement, ['click'])) + .attributeModifier(textModify.setNode(this.node3.childNodes[0] as TaroElement).withNormalStyle()) + .onVisibleAreaChange(getNodeThresholds((this.node3.childNodes[0] as TaroElement)) || [0.0, 1.0], getComponentEventCallback((this.node3.childNodes[0] as TaroElement), VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback((this.node3.childNodes[0] as TaroElement), AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node3.childNodes[0] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } } - .attrs(getNormalAttributes(this.node3)) - .onVisibleAreaChange(getNodeThresholds(this.node3) || [0.0, 1.0], getComponentEventCallback(this.node3, VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node3, AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node3._nid].areaInfo = areaResult + .attributeModifier(columnModify.setNode(this.node3 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node3 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node3 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node3 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node3 as TaroElement)._nodeInfo.areaInfo = res[1] })) } - if (this.node0.childNodes[3]._attrs.compileIf) { - Text(this.node0.childNodes[3].textContent) - .attrsText(getTextAttributes(this.node0.childNodes[3])) - .onVisibleAreaChange(getNodeThresholds(this.node0.childNodes[3]) || [0.0, 1.0], getComponentEventCallback(this.node0.childNodes[3], VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node0.childNodes[3], AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node0.childNodes[3]._nid].areaInfo = areaResult - })) + if ((this.node0.childNodes[3] as TaroElement)._attrs.compileIf) { + if (this.node0.childNodes[3].nodeType === NodeType.TEXT_NODE) { + if (this.node0.childNodes[3].parentNode) { + if ((this.node0.childNodes[3].parentNode as TaroElement).tagName === 'BUTTON') { + Text(this.node0.childNodes[3].textContent) + .attributeModifier(textModify.setNode(this.node0.childNodes[3]?.parentElement as TaroElement, { + fontSize: getButtonFontSize(this.node0.childNodes[3].parentNode as TaroButtonElement), + color: getButtonColor(this.node0.childNodes[3].parentNode as TaroButtonElement, BUTTON_THEME_COLOR.get((this.node0.childNodes[3].parentNode as TaroButtonElement)._attrs.type || '').text) + })) + } else { + Text(this.node0.childNodes[3].textContent) + .attributeModifier(textModify.setNode(this.node0.childNodes[3]?.parentElement as TaroElement)) + .width(getTextInViewWidth(this.node0.childNodes[3].parentElement)) + } + } + } else { + Text(this.node0.childNodes[3].textContent) { + // text 下还有标签 + if (this.node0.childNodes[3].childNodes.length > 1 || ((this.node0.childNodes[3].childNodes[0] && this.node0.childNodes[3].childNodes[0] as TaroElement)?.nodeType === NodeType.ELEMENT_NODE)) { + ForEach(this.node0.childNodes[3].childNodes, (item: TaroElement) => { + createTextChildNode(item, getSpanVerticalAlign((this.node0.childNodes[3] as TaroElement).hmStyle?.verticalAlign)) + }, (item: TaroElement) => item._nid) + } + } + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', this.node0.childNodes[3] as TaroElement), this.node0.childNodes[3] as TaroElement, ['click'])) + .attributeModifier(textModify.setNode(this.node0.childNodes[3] as TaroElement).withNormalStyle()) + .onVisibleAreaChange(getNodeThresholds((this.node0.childNodes[3] as TaroElement)) || [0.0, 1.0], getComponentEventCallback((this.node0.childNodes[3] as TaroElement), VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback((this.node0.childNodes[3] as TaroElement), AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0.childNodes[3] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } } else { - Text(this.node0.childNodes[3].textContent) - .attrsText(getTextAttributes(this.node0.childNodes[3])) - .onVisibleAreaChange(getNodeThresholds(this.node0.childNodes[3]) || [0.0, 1.0], getComponentEventCallback(this.node0.childNodes[3], VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node0.childNodes[3], AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node0.childNodes[3]._nid].areaInfo = areaResult - })) + if (this.node0.childNodes[3].nodeType === NodeType.TEXT_NODE) { + if (this.node0.childNodes[3].parentNode) { + if ((this.node0.childNodes[3].parentNode as TaroElement).tagName === 'BUTTON') { + Text(this.node0.childNodes[3].textContent) + .attributeModifier(textModify.setNode(this.node0.childNodes[3]?.parentElement as TaroElement, { + fontSize: getButtonFontSize(this.node0.childNodes[3].parentNode as TaroButtonElement), + color: getButtonColor(this.node0.childNodes[3].parentNode as TaroButtonElement, BUTTON_THEME_COLOR.get((this.node0.childNodes[3].parentNode as TaroButtonElement)._attrs.type || '').text) + })) + } else { + Text(this.node0.childNodes[3].textContent) + .attributeModifier(textModify.setNode(this.node0.childNodes[3]?.parentElement as TaroElement)) + .width(getTextInViewWidth(this.node0.childNodes[3].parentElement)) + } + } + } else { + Text(this.node0.childNodes[3].textContent) { + // text 下还有标签 + if (this.node0.childNodes[3].childNodes.length > 1 || ((this.node0.childNodes[3].childNodes[0] && this.node0.childNodes[3].childNodes[0] as TaroElement)?.nodeType === NodeType.ELEMENT_NODE)) { + ForEach(this.node0.childNodes[3].childNodes, (item: TaroElement) => { + createTextChildNode(item, getSpanVerticalAlign((this.node0.childNodes[3] as TaroElement).hmStyle?.verticalAlign)) + }, (item: TaroElement) => item._nid) + } + } + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', this.node0.childNodes[3] as TaroElement), this.node0.childNodes[3] as TaroElement, ['click'])) + .attributeModifier(textModify.setNode(this.node0.childNodes[3] as TaroElement).withNormalStyle()) + .onVisibleAreaChange(getNodeThresholds((this.node0.childNodes[3] as TaroElement)) || [0.0, 1.0], getComponentEventCallback((this.node0.childNodes[3] as TaroElement), VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback((this.node0.childNodes[3] as TaroElement), AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0.childNodes[3] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } } - Flex(FlexManager.flexOptions(this.node4)) {} - .attrs(getNormalAttributes(this.node4)) - .onVisibleAreaChange(getNodeThresholds(this.node4) || [0.0, 1.0], getComponentEventCallback(this.node4, VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node4, AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node4._nid].areaInfo = areaResult + Column() {} + .attributeModifier(columnModify.setNode(this.node4 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node4 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node4 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node4 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node4 as TaroElement)._nodeInfo.areaInfo = res[1] })) } - .attrs(getNormalAttributes(this.node0)) - .onVisibleAreaChange(getNodeThresholds(this.node0) || [0.0, 1.0], getComponentEventCallback(this.node0, VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node0, AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node0._nid].areaInfo = areaResult + .attributeModifier(columnModify.setNode(this.node0 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node0 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node0 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node0 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0 as TaroElement)._nodeInfo.areaInfo = res[1] })) } } -export default TARO_TEMPLATES_f0t0 `; function Index() { return diff --git a/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/condition.rs/should_support_complex_condition.js b/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/condition.rs/should_support_complex_condition.js new file mode 100644 index 000000000000..371538659bd2 --- /dev/null +++ b/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/condition.rs/should_support_complex_condition.js @@ -0,0 +1,384 @@ +const TARO_TEMPLATES_f0t0 = `import { + rowModify, + FlexManager, + columnModify, + DynamicCenter, + getButtonColor, + TOUCH_EVENT_MAP, + getFontAttributes, + commonStyleModify, + getNodeThresholds, + BUTTON_THEME_COLOR, + getStyleAttr, + getNormalAttributes, + shouldBindEvent, + textModify, + setNormalTextAttributeIntoInstance, + getImageMode +} from '@tarojs/components' +import { + NodeType, + convertNumber2VP, + TaroElement, + eventHandler, + getComponentEventCallback, + AREA_CHANGE_EVENT_NAME, + VISIBLE_CHANGE_EVENT_NAME +} from '@tarojs/runtime' +import { + createLazyChildren, + createChildItem +} from '../render' + +import type { + TaroTextElement, + HarmonyStyle, + TaroButtonElement, + TaroViewElement, + TaroAny, + TaroStyleType, + TaroTextStyleType +} from '@tarojs/runtime' +import { isString } from '@tarojs/shared' +@Extend(Text) +function textNormalFontStyle (style: HarmonyStyle) { + .id(style.id) + .key(style.id) + .opacity(style.opacity) + .fontColor(style.color) + .fontSize(style.fontSize) + .fontWeight(style.fontWeight) + .fontStyle(style.fontStyle) + .fontFamily(style.fontFamily) + .lineHeight(style.lineHeight) + .decoration({ + type: style.textDecoration?.type, + color: style.color + }) +} + +@Extend(Text) +function textSpecialFontStyle(attr: TaroTextStyleType) { + .textAlign(attr.textAlign) + .textOverflow(attr.textOverflow) + .maxLines(attr.WebkitLineClamp) + .letterSpacing(attr.letterSpacing) +} + +function getButtonFontSize (node: TaroButtonElement) { + const isMini = node._attrs.size === 'mini' + + return isMini ? convertNumber2VP(26) : convertNumber2VP(36) +} + +@Builder +function createTextChildNode (item: TaroElement, align: ImageSpanAlignment) { + if (item.tagName === 'IMAGE') { + ImageSpan(item.getAttribute('src')) + .objectFit(getImageMode(item.getAttribute('mode'))) + .verticalAlign(align) + .width(item._st.hmStyle.width) + .height(item._st.hmStyle.height) + .margin({ + top: item._st.hmStyle.marginTop, + left: item._st.hmStyle.marginLeft, + right: item._st.hmStyle.marginRight, + bottom: item._st.hmStyle.marginBottom, + }) + .padding({ + top: item._st.hmStyle.paddingTop, + left: item._st.hmStyle.paddingLeft, + right: item._st.hmStyle.paddingRight, + bottom: item._st.hmStyle.paddingBottom, + }) + .textBackgroundStyle({ + color: item._st.hmStyle.backgroundColor, + radius: { + topLeft: item._st.hmStyle.borderTopLeftRadius, + topRight: item._st.hmStyle.borderTopRightRadius, + bottomLeft: item._st.hmStyle.borderBottomLeftRadius, + bottomRight: item._st.hmStyle.borderBottomRightRadius, + } + }) + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', item), item, ['click'])) + } else if (item.nodeType === NodeType.TEXT_NODE) { + Span(item.textContent) + } else if (item.tagName === 'TEXT') { + Span(item.textContent) + .attributeModifier((new SpanStyleModify()).setNode(item as TaroTextElement)) + .letterSpacing(item._st.hmStyle.letterSpacing) + .textBackgroundStyle({ + color: item._st.hmStyle.backgroundColor, + radius: { + topLeft: item._st.hmStyle.borderTopLeftRadius, + topRight: item._st.hmStyle.borderTopRightRadius, + bottomLeft: item._st.hmStyle.borderBottomLeftRadius, + bottomRight: item._st.hmStyle.borderBottomRightRadius, + } + }) + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', item), item, ['click'])) + } +} + +class SpanStyleModify implements AttributeModifier { + node: TaroTextElement | null = null + style: HarmonyStyle | null = null + overwriteStyle: Record = {} + withNormal = false + + setNode (node: TaroTextElement) { + this.node = node + this.style = getNormalAttributes(this.node) + return this + } + + applyNormalAttribute(instance: SpanAttribute): void { + if (this.node && this.style) { + setNormalTextAttributeIntoInstance(instance, this.style, this.node) + } + } +} + +function getSpanVerticalAlign (verticalAlign?: Alignment) { + switch (verticalAlign) { + case Alignment.Start: + case Alignment.TopStart: + case Alignment.Top: + case Alignment.TopEnd: { + return ImageSpanAlignment.TOP + } + case Alignment.End: + case Alignment.BottomStart: + case Alignment.Bottom: + case Alignment.BottomEnd: { + return ImageSpanAlignment.BOTTOM + } + case Alignment.Center: { + return ImageSpanAlignment.CENTER + } + } + return ImageSpanAlignment.BASELINE +} + +function getTextInViewWidth (node: TaroElement | null): TaroAny { + if (node) { + const hmStyle = node.hmStyle || {} + const isFlexView = hmStyle.display === 'flex' + const width: TaroAny = getStyleAttr(node, 'width') + const isPercentWidth = isString(width) && width.includes('%') + + return isFlexView || isPercentWidth ? null : getStyleAttr(node, 'width') + } +} + +@Component +export default struct TARO_TEMPLATES_f0t0 { + node: TaroViewElement = new TaroElement('Ignore') + + dynamicCenter: DynamicCenter = new DynamicCenter() + + aboutToAppear () { + this.dynamicCenter.bindComponentToNodeWithDFS(this.node, this) + } + + @State node0: TaroElement = new TaroElement('Ignore') + @State node1: TaroElement = new TaroElement('Ignore') + @State node2: TaroElement = new TaroElement('Ignore') + @State node3: TaroElement = new TaroElement('Ignore') + @State node4: TaroElement = new TaroElement('Ignore') + @State node5: TaroElement = new TaroElement('Ignore') + + build() { + Column() { + if ((this.node0.childNodes[0] as TaroElement)._attrs.compileIf) { + Column() {} + .attributeModifier(columnModify.setNode(this.node0.childNodes[0] as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node0.childNodes[0] as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node0.childNodes[0] as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node0.childNodes[0] as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0.childNodes[0] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + .onClick(e => eventHandler(e, 'click', this.node0.childNodes[0] as TaroElement)) + } + Column() { + if (this.node1.childNodes[0].nodeType === NodeType.TEXT_NODE) { + if (this.node1.childNodes[0].parentNode) { + if ((this.node1.childNodes[0].parentNode as TaroElement).tagName === 'BUTTON') { + Text(this.node1.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node1.childNodes[0]?.parentElement as TaroElement, { + fontSize: getButtonFontSize(this.node1.childNodes[0].parentNode as TaroButtonElement), + color: getButtonColor(this.node1.childNodes[0].parentNode as TaroButtonElement, BUTTON_THEME_COLOR.get((this.node1.childNodes[0].parentNode as TaroButtonElement)._attrs.type || '').text) + })) + } else { + Text(this.node1.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node1.childNodes[0]?.parentElement as TaroElement)) + .width(getTextInViewWidth(this.node1.childNodes[0].parentElement)) + } + } + } else { + Text(this.node1.childNodes[0].textContent) { + // text 下还有标签 + if (this.node1.childNodes[0].childNodes.length > 1 || ((this.node1.childNodes[0].childNodes[0] && this.node1.childNodes[0].childNodes[0] as TaroElement)?.nodeType === NodeType.ELEMENT_NODE)) { + ForEach(this.node1.childNodes[0].childNodes, (item: TaroElement) => { + createTextChildNode(item, getSpanVerticalAlign((this.node1.childNodes[0] as TaroElement).hmStyle?.verticalAlign)) + }, (item: TaroElement) => item._nid) + } + } + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', this.node1.childNodes[0] as TaroElement), this.node1.childNodes[0] as TaroElement, ['click'])) + .attributeModifier(textModify.setNode(this.node1.childNodes[0] as TaroElement).withNormalStyle()) + .onVisibleAreaChange(getNodeThresholds((this.node1.childNodes[0] as TaroElement)) || [0.0, 1.0], getComponentEventCallback((this.node1.childNodes[0] as TaroElement), VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback((this.node1.childNodes[0] as TaroElement), AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node1.childNodes[0] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } + } + .attributeModifier(columnModify.setNode(this.node1 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node1 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node1 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node1 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node1 as TaroElement)._nodeInfo.areaInfo = res[1] + })) + Column() { + if (this.node2.childNodes[0].nodeType === NodeType.TEXT_NODE) { + if (this.node2.childNodes[0].parentNode) { + if ((this.node2.childNodes[0].parentNode as TaroElement).tagName === 'BUTTON') { + Text(this.node2.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node2.childNodes[0]?.parentElement as TaroElement, { + fontSize: getButtonFontSize(this.node2.childNodes[0].parentNode as TaroButtonElement), + color: getButtonColor(this.node2.childNodes[0].parentNode as TaroButtonElement, BUTTON_THEME_COLOR.get((this.node2.childNodes[0].parentNode as TaroButtonElement)._attrs.type || '').text) + })) + } else { + Text(this.node2.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node2.childNodes[0]?.parentElement as TaroElement)) + .width(getTextInViewWidth(this.node2.childNodes[0].parentElement)) + } + } + } else { + Text(this.node2.childNodes[0].textContent) { + // text 下还有标签 + if (this.node2.childNodes[0].childNodes.length > 1 || ((this.node2.childNodes[0].childNodes[0] && this.node2.childNodes[0].childNodes[0] as TaroElement)?.nodeType === NodeType.ELEMENT_NODE)) { + ForEach(this.node2.childNodes[0].childNodes, (item: TaroElement) => { + createTextChildNode(item, getSpanVerticalAlign((this.node2.childNodes[0] as TaroElement).hmStyle?.verticalAlign)) + }, (item: TaroElement) => item._nid) + } + } + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', this.node2.childNodes[0] as TaroElement), this.node2.childNodes[0] as TaroElement, ['click'])) + .attributeModifier(textModify.setNode(this.node2.childNodes[0] as TaroElement).withNormalStyle()) + .onVisibleAreaChange(getNodeThresholds((this.node2.childNodes[0] as TaroElement)) || [0.0, 1.0], getComponentEventCallback((this.node2.childNodes[0] as TaroElement), VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback((this.node2.childNodes[0] as TaroElement), AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node2.childNodes[0] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } + } + .attributeModifier(columnModify.setNode(this.node2 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node2 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node2 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node2 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node2 as TaroElement)._nodeInfo.areaInfo = res[1] + })) + Column() { + if (this.node3.childNodes[0].nodeType === NodeType.TEXT_NODE) { + if (this.node3.childNodes[0].parentNode) { + if ((this.node3.childNodes[0].parentNode as TaroElement).tagName === 'BUTTON') { + Text(this.node3.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node3.childNodes[0]?.parentElement as TaroElement, { + fontSize: getButtonFontSize(this.node3.childNodes[0].parentNode as TaroButtonElement), + color: getButtonColor(this.node3.childNodes[0].parentNode as TaroButtonElement, BUTTON_THEME_COLOR.get((this.node3.childNodes[0].parentNode as TaroButtonElement)._attrs.type || '').text) + })) + } else { + Text(this.node3.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node3.childNodes[0]?.parentElement as TaroElement)) + .width(getTextInViewWidth(this.node3.childNodes[0].parentElement)) + } + } + } else { + Text(this.node3.childNodes[0].textContent) { + // text 下还有标签 + if (this.node3.childNodes[0].childNodes.length > 1 || ((this.node3.childNodes[0].childNodes[0] && this.node3.childNodes[0].childNodes[0] as TaroElement)?.nodeType === NodeType.ELEMENT_NODE)) { + ForEach(this.node3.childNodes[0].childNodes, (item: TaroElement) => { + createTextChildNode(item, getSpanVerticalAlign((this.node3.childNodes[0] as TaroElement).hmStyle?.verticalAlign)) + }, (item: TaroElement) => item._nid) + } + } + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', this.node3.childNodes[0] as TaroElement), this.node3.childNodes[0] as TaroElement, ['click'])) + .attributeModifier(textModify.setNode(this.node3.childNodes[0] as TaroElement).withNormalStyle()) + .onVisibleAreaChange(getNodeThresholds((this.node3.childNodes[0] as TaroElement)) || [0.0, 1.0], getComponentEventCallback((this.node3.childNodes[0] as TaroElement), VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback((this.node3.childNodes[0] as TaroElement), AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node3.childNodes[0] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } + } + .attributeModifier(columnModify.setNode(this.node3 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node3 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node3 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node3 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node3 as TaroElement)._nodeInfo.areaInfo = res[1] + })) + if ((this.node0.childNodes[4] as TaroElement)._attrs.compileIf) { + Column() {} + .attributeModifier(columnModify.setNode(this.node4 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node4 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node4 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node4 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node4 as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } else { + Column() {} + .attributeModifier(columnModify.setNode(this.node0.childNodes[4] as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node0.childNodes[4] as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node0.childNodes[4] as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node0.childNodes[4] as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0.childNodes[4] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } + if ((this.node0.childNodes[5] as TaroElement)._attrs.compileIf) { + Column() { + if ((this.node5.childNodes[0] as TaroElement)._attrs.compileIf) { + Column() {} + .attributeModifier(columnModify.setNode(this.node5.childNodes[0] as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node5.childNodes[0] as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node5.childNodes[0] as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node5.childNodes[0] as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node5.childNodes[0] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } else { + Column() {} + .attributeModifier(columnModify.setNode(this.node5.childNodes[0] as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node5.childNodes[0] as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node5.childNodes[0] as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node5.childNodes[0] as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node5.childNodes[0] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } + } + .attributeModifier(columnModify.setNode(this.node5 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node5 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node5 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node5 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node5 as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } else { + Column() {} + .attributeModifier(columnModify.setNode(this.node0.childNodes[5] as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node0.childNodes[5] as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node0.childNodes[5] as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node0.childNodes[5] as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0.childNodes[5] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } + } + .attributeModifier(columnModify.setNode(this.node0 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node0 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node0 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node0 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0 as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } +} +`; +function Index() { + return + + {condition1 ? condition2 && doSth()} compileIf={condition1}/> : } + + {condition1 && ident} + + {condition1 && obj.property} + + {condition1 && fn()} + + {condition1 ? : } + + {condition1 ? {condition2 ? : } : } + + ; +} diff --git a/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/condition.rs/should_support_conditional_and_unkonw_component.js b/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/condition.rs/should_support_conditional_and_unkonw_component.js new file mode 100644 index 000000000000..a720aec4cfcb --- /dev/null +++ b/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/condition.rs/should_support_conditional_and_unkonw_component.js @@ -0,0 +1,244 @@ +const TARO_TEMPLATES_f0t0 = `import { + rowModify, + FlexManager, + columnModify, + DynamicCenter, + getButtonColor, + TOUCH_EVENT_MAP, + getFontAttributes, + commonStyleModify, + getNodeThresholds, + BUTTON_THEME_COLOR, + getStyleAttr, + getNormalAttributes, + shouldBindEvent, + textModify, + setNormalTextAttributeIntoInstance, + getImageMode +} from '@tarojs/components' +import { + NodeType, + convertNumber2VP, + TaroElement, + eventHandler, + getComponentEventCallback, + AREA_CHANGE_EVENT_NAME, + VISIBLE_CHANGE_EVENT_NAME +} from '@tarojs/runtime' +import { + createLazyChildren, + createChildItem +} from '../render' + +import type { + TaroTextElement, + HarmonyStyle, + TaroButtonElement, + TaroViewElement, + TaroAny, + TaroStyleType, + TaroTextStyleType +} from '@tarojs/runtime' +import { isString } from '@tarojs/shared' +@Extend(Text) +function textNormalFontStyle (style: HarmonyStyle) { + .id(style.id) + .key(style.id) + .opacity(style.opacity) + .fontColor(style.color) + .fontSize(style.fontSize) + .fontWeight(style.fontWeight) + .fontStyle(style.fontStyle) + .fontFamily(style.fontFamily) + .lineHeight(style.lineHeight) + .decoration({ + type: style.textDecoration?.type, + color: style.color + }) +} + +@Extend(Text) +function textSpecialFontStyle(attr: TaroTextStyleType) { + .textAlign(attr.textAlign) + .textOverflow(attr.textOverflow) + .maxLines(attr.WebkitLineClamp) + .letterSpacing(attr.letterSpacing) +} + +function getButtonFontSize (node: TaroButtonElement) { + const isMini = node._attrs.size === 'mini' + + return isMini ? convertNumber2VP(26) : convertNumber2VP(36) +} + +@Builder +function createTextChildNode (item: TaroElement, align: ImageSpanAlignment) { + if (item.tagName === 'IMAGE') { + ImageSpan(item.getAttribute('src')) + .objectFit(getImageMode(item.getAttribute('mode'))) + .verticalAlign(align) + .width(item._st.hmStyle.width) + .height(item._st.hmStyle.height) + .margin({ + top: item._st.hmStyle.marginTop, + left: item._st.hmStyle.marginLeft, + right: item._st.hmStyle.marginRight, + bottom: item._st.hmStyle.marginBottom, + }) + .padding({ + top: item._st.hmStyle.paddingTop, + left: item._st.hmStyle.paddingLeft, + right: item._st.hmStyle.paddingRight, + bottom: item._st.hmStyle.paddingBottom, + }) + .textBackgroundStyle({ + color: item._st.hmStyle.backgroundColor, + radius: { + topLeft: item._st.hmStyle.borderTopLeftRadius, + topRight: item._st.hmStyle.borderTopRightRadius, + bottomLeft: item._st.hmStyle.borderBottomLeftRadius, + bottomRight: item._st.hmStyle.borderBottomRightRadius, + } + }) + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', item), item, ['click'])) + } else if (item.nodeType === NodeType.TEXT_NODE) { + Span(item.textContent) + } else if (item.tagName === 'TEXT') { + Span(item.textContent) + .attributeModifier((new SpanStyleModify()).setNode(item as TaroTextElement)) + .letterSpacing(item._st.hmStyle.letterSpacing) + .textBackgroundStyle({ + color: item._st.hmStyle.backgroundColor, + radius: { + topLeft: item._st.hmStyle.borderTopLeftRadius, + topRight: item._st.hmStyle.borderTopRightRadius, + bottomLeft: item._st.hmStyle.borderBottomLeftRadius, + bottomRight: item._st.hmStyle.borderBottomRightRadius, + } + }) + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', item), item, ['click'])) + } +} + +class SpanStyleModify implements AttributeModifier { + node: TaroTextElement | null = null + style: HarmonyStyle | null = null + overwriteStyle: Record = {} + withNormal = false + + setNode (node: TaroTextElement) { + this.node = node + this.style = getNormalAttributes(this.node) + return this + } + + applyNormalAttribute(instance: SpanAttribute): void { + if (this.node && this.style) { + setNormalTextAttributeIntoInstance(instance, this.style, this.node) + } + } +} + +function getSpanVerticalAlign (verticalAlign?: Alignment) { + switch (verticalAlign) { + case Alignment.Start: + case Alignment.TopStart: + case Alignment.Top: + case Alignment.TopEnd: { + return ImageSpanAlignment.TOP + } + case Alignment.End: + case Alignment.BottomStart: + case Alignment.Bottom: + case Alignment.BottomEnd: { + return ImageSpanAlignment.BOTTOM + } + case Alignment.Center: { + return ImageSpanAlignment.CENTER + } + } + return ImageSpanAlignment.BASELINE +} + +function getTextInViewWidth (node: TaroElement | null): TaroAny { + if (node) { + const hmStyle = node.hmStyle || {} + const isFlexView = hmStyle.display === 'flex' + const width: TaroAny = getStyleAttr(node, 'width') + const isPercentWidth = isString(width) && width.includes('%') + + return isFlexView || isPercentWidth ? null : getStyleAttr(node, 'width') + } +} + +@Component +export default struct TARO_TEMPLATES_f0t0 { + node: TaroViewElement = new TaroElement('Ignore') + + dynamicCenter: DynamicCenter = new DynamicCenter() + + aboutToAppear () { + this.dynamicCenter.bindComponentToNodeWithDFS(this.node, this) + } + + @State node0: TaroElement = new TaroElement('Ignore') + + build() { + Column() { + if ((this.node0.childNodes[0] as TaroElement)._attrs.compileIf) { + Column() { + if (this.node0.childNodes[0].childNodes[0].nodeType === NodeType.TEXT_NODE) { + if (this.node0.childNodes[0].childNodes[0].parentNode) { + if ((this.node0.childNodes[0].childNodes[0].parentNode as TaroElement).tagName === 'BUTTON') { + Text(this.node0.childNodes[0].childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node0.childNodes[0].childNodes[0]?.parentElement as TaroElement, { + fontSize: getButtonFontSize(this.node0.childNodes[0].childNodes[0].parentNode as TaroButtonElement), + color: getButtonColor(this.node0.childNodes[0].childNodes[0].parentNode as TaroButtonElement, BUTTON_THEME_COLOR.get((this.node0.childNodes[0].childNodes[0].parentNode as TaroButtonElement)._attrs.type || '').text) + })) + } else { + Text(this.node0.childNodes[0].childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node0.childNodes[0].childNodes[0]?.parentElement as TaroElement)) + .width(getTextInViewWidth(this.node0.childNodes[0].childNodes[0].parentElement)) + } + } + } else { + Text(this.node0.childNodes[0].childNodes[0].textContent) { + // text 下还有标签 + if (this.node0.childNodes[0].childNodes[0].childNodes.length > 1 || ((this.node0.childNodes[0].childNodes[0].childNodes[0] && this.node0.childNodes[0].childNodes[0].childNodes[0] as TaroElement)?.nodeType === NodeType.ELEMENT_NODE)) { + ForEach(this.node0.childNodes[0].childNodes[0].childNodes, (item: TaroElement) => { + createTextChildNode(item, getSpanVerticalAlign((this.node0.childNodes[0].childNodes[0] as TaroElement).hmStyle?.verticalAlign)) + }, (item: TaroElement) => item._nid) + } + } + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', this.node0.childNodes[0].childNodes[0] as TaroElement), this.node0.childNodes[0].childNodes[0] as TaroElement, ['click'])) + .attributeModifier(textModify.setNode(this.node0.childNodes[0].childNodes[0] as TaroElement).withNormalStyle()) + .onVisibleAreaChange(getNodeThresholds((this.node0.childNodes[0].childNodes[0] as TaroElement)) || [0.0, 1.0], getComponentEventCallback((this.node0.childNodes[0].childNodes[0] as TaroElement), VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback((this.node0.childNodes[0].childNodes[0] as TaroElement), AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0.childNodes[0].childNodes[0] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } + } + .attributeModifier(columnModify.setNode(this.node0.childNodes[0] as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node0.childNodes[0] as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node0.childNodes[0] as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node0.childNodes[0] as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0.childNodes[0] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } else { + createChildItem(this.node0.childNodes[0] as TaroElement, createLazyChildren) + } + } + .attributeModifier(columnModify.setNode(this.node0 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node0 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node0 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node0 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0 as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } +} +`; +function Index() { + return + + {condition ? hello : hello} + + ; +} diff --git a/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/condition.rs/should_support_conditional_expr.js b/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/condition.rs/should_support_conditional_expr.js index 831487069fcf..bdb7f7c13c71 100644 --- a/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/condition.rs/should_support_conditional_expr.js +++ b/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/condition.rs/should_support_conditional_expr.js @@ -1,392 +1,686 @@ -const TARO_TEMPLATES_f0t0 = `import { FlexManager } from './utils/FlexManager' -import { getNodeThresholds, getNormalAttributes, getTextAttributes } from './utils/helper' -import { TaroIgnoreElement, eventHandler, DynamicCenter, getComponentEventCallback, AREA_CHANGE_EVENT_NAME, VISIBLE_CHANGE_EVENT_NAME } from '../runtime' -import type { TaroElement } from '../runtime' -import { TOUCH_EVENT_MAP } from './utils/constant/event' -@Extend(Flex) -function attrs ({ - flexBasis, - flexGrow, - flexShrink, - alignSelf, - clip, - width, - height, - margin, - padding, - linearGradient, - zIndex, - borderStyle, - borderWidth, - borderColor, - borderRadius, - opacity, - backgroundColor, - backgroundImage, - backgroundRepeat, - backgroundImageSize, - constraintSize, - rotate, - scale, - translate, - transform -}) { - .flexGrow(flexGrow) - .flexShrink(flexShrink) - .flexBasis(flexBasis) - .alignSelf(alignSelf) - .width(width) - .height(height) - .constraintSize(constraintSize) - .margin(margin) - .padding(padding) - .linearGradient(linearGradient) - .zIndex(zIndex) - .borderStyle(borderStyle) - .borderWidth(borderWidth) - .borderColor(borderColor) - .borderRadius(borderRadius) - .opacity(opacity) - .backgroundColor(backgroundColor) - .backgroundImage(backgroundImage, backgroundRepeat) - .backgroundImageSize(backgroundImageSize) - .rotate(rotate) - .scale(scale) - .translate(translate) - .transform(transform) - .clip(clip) +const TARO_TEMPLATES_f0t0 = `import { + rowModify, + FlexManager, + columnModify, + DynamicCenter, + getButtonColor, + TOUCH_EVENT_MAP, + getFontAttributes, + commonStyleModify, + getNodeThresholds, + BUTTON_THEME_COLOR, + getStyleAttr, + getNormalAttributes, + shouldBindEvent, + textModify, + setNormalTextAttributeIntoInstance, + getImageMode +} from '@tarojs/components' +import { + NodeType, + convertNumber2VP, + TaroElement, + eventHandler, + getComponentEventCallback, + AREA_CHANGE_EVENT_NAME, + VISIBLE_CHANGE_EVENT_NAME +} from '@tarojs/runtime' +import { + createLazyChildren, + createChildItem +} from '../render' + +import type { + TaroTextElement, + HarmonyStyle, + TaroButtonElement, + TaroViewElement, + TaroAny, + TaroStyleType, + TaroTextStyleType +} from '@tarojs/runtime' +import { isString } from '@tarojs/shared' +@Extend(Text) +function textNormalFontStyle (style: HarmonyStyle) { + .id(style.id) + .key(style.id) + .opacity(style.opacity) + .fontColor(style.color) + .fontSize(style.fontSize) + .fontWeight(style.fontWeight) + .fontStyle(style.fontStyle) + .fontFamily(style.fontFamily) + .lineHeight(style.lineHeight) + .decoration({ + type: style.textDecoration?.type, + color: style.color + }) } + @Extend(Text) -function attrsText ({ - id, - width, - height, - zIndex, - opacity, - margin, - padding, - decoration, - lineHeight, - letterSpacing, - maxLines, - fontColor, - fontSize, - fontWeight, - fontFamily, - textOverflow, - constraintSize, - border, - borderRadius, - backgroundColor, - backgroundImage, - backgroundRepeat, - backgroundImageSize, - rotate, - scale, - translate, - transform, - textAlign, - }) { - .id(id) - .key(id) - .constraintSize(constraintSize) - .zIndex(zIndex) - .opacity(opacity) - .margin(margin) - .padding(padding) - .decoration(decoration) - .lineHeight(lineHeight) - .letterSpacing(letterSpacing) - .maxLines(maxLines) - .fontColor(fontColor) - .fontSize(fontSize) - .fontWeight(fontWeight) - .fontFamily(fontFamily) - .textOverflow(textOverflow) - .border(border) - .borderRadius(borderRadius) - .backgroundColor(backgroundColor) - .backgroundImage(backgroundImage, backgroundRepeat) - .backgroundImageSize(backgroundImageSize) - .rotate(rotate) - .scale(scale) - .translate(translate) - .transform(transform) - .textAlign(textAlign) - .width(width) - .height(height) +function textSpecialFontStyle(attr: TaroTextStyleType) { + .textAlign(attr.textAlign) + .textOverflow(attr.textOverflow) + .maxLines(attr.WebkitLineClamp) + .letterSpacing(attr.letterSpacing) } -function getTextAttributes (node: TaroViewElement) { - const attrs = { - ...getNormalAttributes(node), - ...getFontAttributes(node) +function getButtonFontSize (node: TaroButtonElement) { + const isMini = node._attrs.size === 'mini' + + return isMini ? convertNumber2VP(26) : convertNumber2VP(36) +} + +@Builder +function createTextChildNode (item: TaroElement, align: ImageSpanAlignment) { + if (item.tagName === 'IMAGE') { + ImageSpan(item.getAttribute('src')) + .objectFit(getImageMode(item.getAttribute('mode'))) + .verticalAlign(align) + .width(item._st.hmStyle.width) + .height(item._st.hmStyle.height) + .margin({ + top: item._st.hmStyle.marginTop, + left: item._st.hmStyle.marginLeft, + right: item._st.hmStyle.marginRight, + bottom: item._st.hmStyle.marginBottom, + }) + .padding({ + top: item._st.hmStyle.paddingTop, + left: item._st.hmStyle.paddingLeft, + right: item._st.hmStyle.paddingRight, + bottom: item._st.hmStyle.paddingBottom, + }) + .textBackgroundStyle({ + color: item._st.hmStyle.backgroundColor, + radius: { + topLeft: item._st.hmStyle.borderTopLeftRadius, + topRight: item._st.hmStyle.borderTopRightRadius, + bottomLeft: item._st.hmStyle.borderBottomLeftRadius, + bottomRight: item._st.hmStyle.borderBottomRightRadius, + } + }) + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', item), item, ['click'])) + } else if (item.nodeType === NodeType.TEXT_NODE) { + Span(item.textContent) + } else if (item.tagName === 'TEXT') { + Span(item.textContent) + .attributeModifier((new SpanStyleModify()).setNode(item as TaroTextElement)) + .letterSpacing(item._st.hmStyle.letterSpacing) + .textBackgroundStyle({ + color: item._st.hmStyle.backgroundColor, + radius: { + topLeft: item._st.hmStyle.borderTopLeftRadius, + topRight: item._st.hmStyle.borderTopRightRadius, + bottomLeft: item._st.hmStyle.borderBottomLeftRadius, + bottomRight: item._st.hmStyle.borderBottomRightRadius, + } + }) + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', item), item, ['click'])) } +} - transformW3CToHarmonyInStyle(node._st, attrs) +class SpanStyleModify implements AttributeModifier { + node: TaroTextElement | null = null + style: HarmonyStyle | null = null + overwriteStyle: Record = {} + withNormal = false - return attrs + setNode (node: TaroTextElement) { + this.node = node + this.style = getNormalAttributes(this.node) + return this + } + + applyNormalAttribute(instance: SpanAttribute): void { + if (this.node && this.style) { + setNormalTextAttributeIntoInstance(instance, this.style, this.node) + } + } } + +function getSpanVerticalAlign (verticalAlign?: Alignment) { + switch (verticalAlign) { + case Alignment.Start: + case Alignment.TopStart: + case Alignment.Top: + case Alignment.TopEnd: { + return ImageSpanAlignment.TOP + } + case Alignment.End: + case Alignment.BottomStart: + case Alignment.Bottom: + case Alignment.BottomEnd: { + return ImageSpanAlignment.BOTTOM + } + case Alignment.Center: { + return ImageSpanAlignment.CENTER + } + } + return ImageSpanAlignment.BASELINE +} + +function getTextInViewWidth (node: TaroElement | null): TaroAny { + if (node) { + const hmStyle = node.hmStyle || {} + const isFlexView = hmStyle.display === 'flex' + const width: TaroAny = getStyleAttr(node, 'width') + const isPercentWidth = isString(width) && width.includes('%') + + return isFlexView || isPercentWidth ? null : getStyleAttr(node, 'width') + } +} + @Component -struct TARO_TEMPLATES_f0t0 { - nodeInfoMap: any = {} - dynamicCenter: DynamicCenter - @ObjectLink node: TaroElement +export default struct TARO_TEMPLATES_f0t0 { + node: TaroViewElement = new TaroElement('Ignore') + + dynamicCenter: DynamicCenter = new DynamicCenter() aboutToAppear () { - this.dynamicCenter = new DynamicCenter() this.dynamicCenter.bindComponentToNodeWithDFS(this.node, this) } - @State node0: TaroElement = new TaroIgnoreElement() - @State node1: TaroElement = new TaroIgnoreElement() - @State node2: TaroElement = new TaroIgnoreElement() - @State node3: TaroElement = new TaroIgnoreElement() - @State node4: TaroElement = new TaroIgnoreElement() - @State node5: TaroElement = new TaroIgnoreElement() - @State node6: TaroElement = new TaroIgnoreElement() - @State node7: TaroElement = new TaroIgnoreElement() - @State node8: TaroElement = new TaroIgnoreElement() - @State node9: TaroElement = new TaroIgnoreElement() - @State node10: TaroElement = new TaroIgnoreElement() - @State node11: TaroElement = new TaroIgnoreElement() - @State node12: TaroElement = new TaroIgnoreElement() - @State node13: TaroElement = new TaroIgnoreElement() + @State node0: TaroElement = new TaroElement('Ignore') + @State node1: TaroElement = new TaroElement('Ignore') + @State node2: TaroElement = new TaroElement('Ignore') + @State node3: TaroElement = new TaroElement('Ignore') + @State node4: TaroElement = new TaroElement('Ignore') + @State node5: TaroElement = new TaroElement('Ignore') + @State node6: TaroElement = new TaroElement('Ignore') + @State node7: TaroElement = new TaroElement('Ignore') + @State node8: TaroElement = new TaroElement('Ignore') + @State node9: TaroElement = new TaroElement('Ignore') + @State node10: TaroElement = new TaroElement('Ignore') + @State node11: TaroElement = new TaroElement('Ignore') build() { - Flex(FlexManager.flexOptions(this.node0)) { - if (this.node0.childNodes[0]._attrs.compileIf) { - Flex(FlexManager.flexOptions(this.node1)) { - Text(this.node1.childNodes[0].textContent) - .attrsText(getTextAttributes(this.node1.childNodes[0])) - .onVisibleAreaChange(getNodeThresholds(this.node1.childNodes[0]) || [0.0, 1.0], getComponentEventCallback(this.node1.childNodes[0], VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node1.childNodes[0], AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node1.childNodes[0]._nid].areaInfo = areaResult - })) + Column() { + if ((this.node0.childNodes[0] as TaroElement)._attrs.compileIf) { + Column() { + if (this.node1.childNodes[0].nodeType === NodeType.TEXT_NODE) { + if (this.node1.childNodes[0].parentNode) { + if ((this.node1.childNodes[0].parentNode as TaroElement).tagName === 'BUTTON') { + Text(this.node1.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node1.childNodes[0]?.parentElement as TaroElement, { + fontSize: getButtonFontSize(this.node1.childNodes[0].parentNode as TaroButtonElement), + color: getButtonColor(this.node1.childNodes[0].parentNode as TaroButtonElement, BUTTON_THEME_COLOR.get((this.node1.childNodes[0].parentNode as TaroButtonElement)._attrs.type || '').text) + })) + } else { + Text(this.node1.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node1.childNodes[0]?.parentElement as TaroElement)) + .width(getTextInViewWidth(this.node1.childNodes[0].parentElement)) + } + } + } else { + Text(this.node1.childNodes[0].textContent) { + // text 下还有标签 + if (this.node1.childNodes[0].childNodes.length > 1 || ((this.node1.childNodes[0].childNodes[0] && this.node1.childNodes[0].childNodes[0] as TaroElement)?.nodeType === NodeType.ELEMENT_NODE)) { + ForEach(this.node1.childNodes[0].childNodes, (item: TaroElement) => { + createTextChildNode(item, getSpanVerticalAlign((this.node1.childNodes[0] as TaroElement).hmStyle?.verticalAlign)) + }, (item: TaroElement) => item._nid) + } + } + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', this.node1.childNodes[0] as TaroElement), this.node1.childNodes[0] as TaroElement, ['click'])) + .attributeModifier(textModify.setNode(this.node1.childNodes[0] as TaroElement).withNormalStyle()) + .onVisibleAreaChange(getNodeThresholds((this.node1.childNodes[0] as TaroElement)) || [0.0, 1.0], getComponentEventCallback((this.node1.childNodes[0] as TaroElement), VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback((this.node1.childNodes[0] as TaroElement), AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node1.childNodes[0] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } } - .attrs(getNormalAttributes(this.node1)) - .onVisibleAreaChange(getNodeThresholds(this.node1) || [0.0, 1.0], getComponentEventCallback(this.node1, VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node1, AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node1._nid].areaInfo = areaResult + .attributeModifier(columnModify.setNode(this.node1 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node1 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node1 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node1 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node1 as TaroElement)._nodeInfo.areaInfo = res[1] })) } else { - Text(this.node0.childNodes[0].textContent) - .attrsText(getTextAttributes(this.node0.childNodes[0])) - .onVisibleAreaChange(getNodeThresholds(this.node0.childNodes[0]) || [0.0, 1.0], getComponentEventCallback(this.node0.childNodes[0], VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node0.childNodes[0], AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node0.childNodes[0]._nid].areaInfo = areaResult - })) + if (this.node0.childNodes[0].nodeType === NodeType.TEXT_NODE) { + if (this.node0.childNodes[0].parentNode) { + if ((this.node0.childNodes[0].parentNode as TaroElement).tagName === 'BUTTON') { + Text(this.node0.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node0.childNodes[0]?.parentElement as TaroElement, { + fontSize: getButtonFontSize(this.node0.childNodes[0].parentNode as TaroButtonElement), + color: getButtonColor(this.node0.childNodes[0].parentNode as TaroButtonElement, BUTTON_THEME_COLOR.get((this.node0.childNodes[0].parentNode as TaroButtonElement)._attrs.type || '').text) + })) + } else { + Text(this.node0.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node0.childNodes[0]?.parentElement as TaroElement)) + .width(getTextInViewWidth(this.node0.childNodes[0].parentElement)) + } + } + } else { + Text(this.node0.childNodes[0].textContent) { + // text 下还有标签 + if (this.node0.childNodes[0].childNodes.length > 1 || ((this.node0.childNodes[0].childNodes[0] && this.node0.childNodes[0].childNodes[0] as TaroElement)?.nodeType === NodeType.ELEMENT_NODE)) { + ForEach(this.node0.childNodes[0].childNodes, (item: TaroElement) => { + createTextChildNode(item, getSpanVerticalAlign((this.node0.childNodes[0] as TaroElement).hmStyle?.verticalAlign)) + }, (item: TaroElement) => item._nid) + } + } + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', this.node0.childNodes[0] as TaroElement), this.node0.childNodes[0] as TaroElement, ['click'])) + .attributeModifier(textModify.setNode(this.node0.childNodes[0] as TaroElement).withNormalStyle()) + .onVisibleAreaChange(getNodeThresholds((this.node0.childNodes[0] as TaroElement)) || [0.0, 1.0], getComponentEventCallback((this.node0.childNodes[0] as TaroElement), VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback((this.node0.childNodes[0] as TaroElement), AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0.childNodes[0] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } } - if (this.node0.childNodes[1]._attrs.compileIf) { - if (this.node0.childNodes[1]._attrs.compileIf) { - Flex(FlexManager.flexOptions(this.node4)) { - Text(this.node4.childNodes[0].textContent) - .attrsText(getTextAttributes(this.node4.childNodes[0])) - .onVisibleAreaChange(getNodeThresholds(this.node4.childNodes[0]) || [0.0, 1.0], getComponentEventCallback(this.node4.childNodes[0], VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node4.childNodes[0], AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node4.childNodes[0]._nid].areaInfo = areaResult - })) + if ((this.node0.childNodes[1] as TaroElement)._attrs.compileIf) { + if ((this.node0.childNodes[1] as TaroElement)._attrs.compileIf) { + Column() { + if (this.node4.childNodes[0].nodeType === NodeType.TEXT_NODE) { + if (this.node4.childNodes[0].parentNode) { + if ((this.node4.childNodes[0].parentNode as TaroElement).tagName === 'BUTTON') { + Text(this.node4.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node4.childNodes[0]?.parentElement as TaroElement, { + fontSize: getButtonFontSize(this.node4.childNodes[0].parentNode as TaroButtonElement), + color: getButtonColor(this.node4.childNodes[0].parentNode as TaroButtonElement, BUTTON_THEME_COLOR.get((this.node4.childNodes[0].parentNode as TaroButtonElement)._attrs.type || '').text) + })) + } else { + Text(this.node4.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node4.childNodes[0]?.parentElement as TaroElement)) + .width(getTextInViewWidth(this.node4.childNodes[0].parentElement)) + } + } + } else { + Text(this.node4.childNodes[0].textContent) { + // text 下还有标签 + if (this.node4.childNodes[0].childNodes.length > 1 || ((this.node4.childNodes[0].childNodes[0] && this.node4.childNodes[0].childNodes[0] as TaroElement)?.nodeType === NodeType.ELEMENT_NODE)) { + ForEach(this.node4.childNodes[0].childNodes, (item: TaroElement) => { + createTextChildNode(item, getSpanVerticalAlign((this.node4.childNodes[0] as TaroElement).hmStyle?.verticalAlign)) + }, (item: TaroElement) => item._nid) + } + } + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', this.node4.childNodes[0] as TaroElement), this.node4.childNodes[0] as TaroElement, ['click'])) + .attributeModifier(textModify.setNode(this.node4.childNodes[0] as TaroElement).withNormalStyle()) + .onVisibleAreaChange(getNodeThresholds((this.node4.childNodes[0] as TaroElement)) || [0.0, 1.0], getComponentEventCallback((this.node4.childNodes[0] as TaroElement), VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback((this.node4.childNodes[0] as TaroElement), AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node4.childNodes[0] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } } - .attrs(getNormalAttributes(this.node4)) - .onVisibleAreaChange(getNodeThresholds(this.node4) || [0.0, 1.0], getComponentEventCallback(this.node4, VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node4, AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node4._nid].areaInfo = areaResult + .attributeModifier(columnModify.setNode(this.node4 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node4 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node4 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node4 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node4 as TaroElement)._nodeInfo.areaInfo = res[1] })) } else { - Text(this.node3.textContent) - .attrsText(getTextAttributes(this.node3)) - .onVisibleAreaChange(getNodeThresholds(this.node3) || [0.0, 1.0], getComponentEventCallback(this.node3, VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node3, AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node3._nid].areaInfo = areaResult - })) + if (this.node3.nodeType === NodeType.TEXT_NODE) { + if (this.node3.parentNode) { + if ((this.node3.parentNode as TaroElement).tagName === 'BUTTON') { + Text(this.node3.textContent) + .attributeModifier(textModify.setNode(this.node3?.parentElement as TaroElement, { + fontSize: getButtonFontSize(this.node3.parentNode as TaroButtonElement), + color: getButtonColor(this.node3.parentNode as TaroButtonElement, BUTTON_THEME_COLOR.get((this.node3.parentNode as TaroButtonElement)._attrs.type || '').text) + })) + } else { + Text(this.node3.textContent) + .attributeModifier(textModify.setNode(this.node3?.parentElement as TaroElement)) + .width(getTextInViewWidth(this.node3.parentElement)) + } + } + } else { + Text(this.node3.textContent) { + // text 下还有标签 + if (this.node3.childNodes.length > 1 || ((this.node3.childNodes[0] && this.node3.childNodes[0] as TaroElement)?.nodeType === NodeType.ELEMENT_NODE)) { + ForEach(this.node3.childNodes, (item: TaroElement) => { + createTextChildNode(item, getSpanVerticalAlign((this.node3 as TaroElement).hmStyle?.verticalAlign)) + }, (item: TaroElement) => item._nid) + } + } + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', this.node3 as TaroElement), this.node3 as TaroElement, ['click'])) + .attributeModifier(textModify.setNode(this.node3 as TaroElement).withNormalStyle()) + .onVisibleAreaChange(getNodeThresholds((this.node3 as TaroElement)) || [0.0, 1.0], getComponentEventCallback((this.node3 as TaroElement), VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback((this.node3 as TaroElement), AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node3 as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } } } else { - Flex(FlexManager.flexOptions(this.node2)) { - Text(this.node2.childNodes[0].textContent) - .attrsText(getTextAttributes(this.node2.childNodes[0])) - .onVisibleAreaChange(getNodeThresholds(this.node2.childNodes[0]) || [0.0, 1.0], getComponentEventCallback(this.node2.childNodes[0], VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node2.childNodes[0], AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node2.childNodes[0]._nid].areaInfo = areaResult - })) + Column() { + if (this.node2.childNodes[0].nodeType === NodeType.TEXT_NODE) { + if (this.node2.childNodes[0].parentNode) { + if ((this.node2.childNodes[0].parentNode as TaroElement).tagName === 'BUTTON') { + Text(this.node2.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node2.childNodes[0]?.parentElement as TaroElement, { + fontSize: getButtonFontSize(this.node2.childNodes[0].parentNode as TaroButtonElement), + color: getButtonColor(this.node2.childNodes[0].parentNode as TaroButtonElement, BUTTON_THEME_COLOR.get((this.node2.childNodes[0].parentNode as TaroButtonElement)._attrs.type || '').text) + })) + } else { + Text(this.node2.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node2.childNodes[0]?.parentElement as TaroElement)) + .width(getTextInViewWidth(this.node2.childNodes[0].parentElement)) + } + } + } else { + Text(this.node2.childNodes[0].textContent) { + // text 下还有标签 + if (this.node2.childNodes[0].childNodes.length > 1 || ((this.node2.childNodes[0].childNodes[0] && this.node2.childNodes[0].childNodes[0] as TaroElement)?.nodeType === NodeType.ELEMENT_NODE)) { + ForEach(this.node2.childNodes[0].childNodes, (item: TaroElement) => { + createTextChildNode(item, getSpanVerticalAlign((this.node2.childNodes[0] as TaroElement).hmStyle?.verticalAlign)) + }, (item: TaroElement) => item._nid) + } + } + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', this.node2.childNodes[0] as TaroElement), this.node2.childNodes[0] as TaroElement, ['click'])) + .attributeModifier(textModify.setNode(this.node2.childNodes[0] as TaroElement).withNormalStyle()) + .onVisibleAreaChange(getNodeThresholds((this.node2.childNodes[0] as TaroElement)) || [0.0, 1.0], getComponentEventCallback((this.node2.childNodes[0] as TaroElement), VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback((this.node2.childNodes[0] as TaroElement), AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node2.childNodes[0] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } } - .attrs(getNormalAttributes(this.node2)) - .onVisibleAreaChange(getNodeThresholds(this.node2) || [0.0, 1.0], getComponentEventCallback(this.node2, VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node2, AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node2._nid].areaInfo = areaResult + .attributeModifier(columnModify.setNode(this.node2 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node2 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node2 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node2 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node2 as TaroElement)._nodeInfo.areaInfo = res[1] })) } - if (this.node0.childNodes[2]._attrs.compileIf) { - Flex(FlexManager.flexOptions(this.node7)) { - Text(this.node7.childNodes[0].textContent) - .attrsText(getTextAttributes(this.node7.childNodes[0])) - .onVisibleAreaChange(getNodeThresholds(this.node7.childNodes[0]) || [0.0, 1.0], getComponentEventCallback(this.node7.childNodes[0], VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node7.childNodes[0], AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node7.childNodes[0]._nid].areaInfo = areaResult - })) + if ((this.node0.childNodes[2] as TaroElement)._attrs.compileIf) { + Column() { + if (this.node7.childNodes[0].nodeType === NodeType.TEXT_NODE) { + if (this.node7.childNodes[0].parentNode) { + if ((this.node7.childNodes[0].parentNode as TaroElement).tagName === 'BUTTON') { + Text(this.node7.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node7.childNodes[0]?.parentElement as TaroElement, { + fontSize: getButtonFontSize(this.node7.childNodes[0].parentNode as TaroButtonElement), + color: getButtonColor(this.node7.childNodes[0].parentNode as TaroButtonElement, BUTTON_THEME_COLOR.get((this.node7.childNodes[0].parentNode as TaroButtonElement)._attrs.type || '').text) + })) + } else { + Text(this.node7.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node7.childNodes[0]?.parentElement as TaroElement)) + .width(getTextInViewWidth(this.node7.childNodes[0].parentElement)) + } + } + } else { + Text(this.node7.childNodes[0].textContent) { + // text 下还有标签 + if (this.node7.childNodes[0].childNodes.length > 1 || ((this.node7.childNodes[0].childNodes[0] && this.node7.childNodes[0].childNodes[0] as TaroElement)?.nodeType === NodeType.ELEMENT_NODE)) { + ForEach(this.node7.childNodes[0].childNodes, (item: TaroElement) => { + createTextChildNode(item, getSpanVerticalAlign((this.node7.childNodes[0] as TaroElement).hmStyle?.verticalAlign)) + }, (item: TaroElement) => item._nid) + } + } + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', this.node7.childNodes[0] as TaroElement), this.node7.childNodes[0] as TaroElement, ['click'])) + .attributeModifier(textModify.setNode(this.node7.childNodes[0] as TaroElement).withNormalStyle()) + .onVisibleAreaChange(getNodeThresholds((this.node7.childNodes[0] as TaroElement)) || [0.0, 1.0], getComponentEventCallback((this.node7.childNodes[0] as TaroElement), VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback((this.node7.childNodes[0] as TaroElement), AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node7.childNodes[0] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } } - .attrs(getNormalAttributes(this.node7)) - .onVisibleAreaChange(getNodeThresholds(this.node7) || [0.0, 1.0], getComponentEventCallback(this.node7, VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node7, AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node7._nid].areaInfo = areaResult + .attributeModifier(columnModify.setNode(this.node7 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node7 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node7 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node7 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node7 as TaroElement)._nodeInfo.areaInfo = res[1] })) } else { - if (this.node0.childNodes[2]._attrs.compileIf) { - Flex(FlexManager.flexOptions(this.node6)) { - Text(this.node6.childNodes[0].textContent) - .attrsText(getTextAttributes(this.node6.childNodes[0])) - .onVisibleAreaChange(getNodeThresholds(this.node6.childNodes[0]) || [0.0, 1.0], getComponentEventCallback(this.node6.childNodes[0], VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node6.childNodes[0], AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node6.childNodes[0]._nid].areaInfo = areaResult - })) + if ((this.node0.childNodes[2] as TaroElement)._attrs.compileIf) { + Column() { + if (this.node6.childNodes[0].nodeType === NodeType.TEXT_NODE) { + if (this.node6.childNodes[0].parentNode) { + if ((this.node6.childNodes[0].parentNode as TaroElement).tagName === 'BUTTON') { + Text(this.node6.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node6.childNodes[0]?.parentElement as TaroElement, { + fontSize: getButtonFontSize(this.node6.childNodes[0].parentNode as TaroButtonElement), + color: getButtonColor(this.node6.childNodes[0].parentNode as TaroButtonElement, BUTTON_THEME_COLOR.get((this.node6.childNodes[0].parentNode as TaroButtonElement)._attrs.type || '').text) + })) + } else { + Text(this.node6.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node6.childNodes[0]?.parentElement as TaroElement)) + .width(getTextInViewWidth(this.node6.childNodes[0].parentElement)) + } + } + } else { + Text(this.node6.childNodes[0].textContent) { + // text 下还有标签 + if (this.node6.childNodes[0].childNodes.length > 1 || ((this.node6.childNodes[0].childNodes[0] && this.node6.childNodes[0].childNodes[0] as TaroElement)?.nodeType === NodeType.ELEMENT_NODE)) { + ForEach(this.node6.childNodes[0].childNodes, (item: TaroElement) => { + createTextChildNode(item, getSpanVerticalAlign((this.node6.childNodes[0] as TaroElement).hmStyle?.verticalAlign)) + }, (item: TaroElement) => item._nid) + } + } + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', this.node6.childNodes[0] as TaroElement), this.node6.childNodes[0] as TaroElement, ['click'])) + .attributeModifier(textModify.setNode(this.node6.childNodes[0] as TaroElement).withNormalStyle()) + .onVisibleAreaChange(getNodeThresholds((this.node6.childNodes[0] as TaroElement)) || [0.0, 1.0], getComponentEventCallback((this.node6.childNodes[0] as TaroElement), VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback((this.node6.childNodes[0] as TaroElement), AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node6.childNodes[0] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } } - .attrs(getNormalAttributes(this.node6)) - .onVisibleAreaChange(getNodeThresholds(this.node6) || [0.0, 1.0], getComponentEventCallback(this.node6, VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node6, AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node6._nid].areaInfo = areaResult + .attributeModifier(columnModify.setNode(this.node6 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node6 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node6 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node6 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node6 as TaroElement)._nodeInfo.areaInfo = res[1] })) } else { - Text(this.node5.textContent) - .attrsText(getTextAttributes(this.node5)) - .onVisibleAreaChange(getNodeThresholds(this.node5) || [0.0, 1.0], getComponentEventCallback(this.node5, VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node5, AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node5._nid].areaInfo = areaResult - })) + if (this.node5.nodeType === NodeType.TEXT_NODE) { + if (this.node5.parentNode) { + if ((this.node5.parentNode as TaroElement).tagName === 'BUTTON') { + Text(this.node5.textContent) + .attributeModifier(textModify.setNode(this.node5?.parentElement as TaroElement, { + fontSize: getButtonFontSize(this.node5.parentNode as TaroButtonElement), + color: getButtonColor(this.node5.parentNode as TaroButtonElement, BUTTON_THEME_COLOR.get((this.node5.parentNode as TaroButtonElement)._attrs.type || '').text) + })) + } else { + Text(this.node5.textContent) + .attributeModifier(textModify.setNode(this.node5?.parentElement as TaroElement)) + .width(getTextInViewWidth(this.node5.parentElement)) + } + } + } else { + Text(this.node5.textContent) { + // text 下还有标签 + if (this.node5.childNodes.length > 1 || ((this.node5.childNodes[0] && this.node5.childNodes[0] as TaroElement)?.nodeType === NodeType.ELEMENT_NODE)) { + ForEach(this.node5.childNodes, (item: TaroElement) => { + createTextChildNode(item, getSpanVerticalAlign((this.node5 as TaroElement).hmStyle?.verticalAlign)) + }, (item: TaroElement) => item._nid) + } + } + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', this.node5 as TaroElement), this.node5 as TaroElement, ['click'])) + .attributeModifier(textModify.setNode(this.node5 as TaroElement).withNormalStyle()) + .onVisibleAreaChange(getNodeThresholds((this.node5 as TaroElement)) || [0.0, 1.0], getComponentEventCallback((this.node5 as TaroElement), VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback((this.node5 as TaroElement), AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node5 as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } } } - if (this.node0.childNodes[3]._attrs.compileIf) { - Flex(FlexManager.flexOptions(this.node8)) { - Text(this.node8.childNodes[0].textContent) - .attrsText(getTextAttributes(this.node8.childNodes[0])) - .onVisibleAreaChange(getNodeThresholds(this.node8.childNodes[0]) || [0.0, 1.0], getComponentEventCallback(this.node8.childNodes[0], VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node8.childNodes[0], AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node8.childNodes[0]._nid].areaInfo = areaResult - })) + if ((this.node0.childNodes[3] as TaroElement)._attrs.compileIf) { + Column() { + if (this.node8.childNodes[0].nodeType === NodeType.TEXT_NODE) { + if (this.node8.childNodes[0].parentNode) { + if ((this.node8.childNodes[0].parentNode as TaroElement).tagName === 'BUTTON') { + Text(this.node8.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node8.childNodes[0]?.parentElement as TaroElement, { + fontSize: getButtonFontSize(this.node8.childNodes[0].parentNode as TaroButtonElement), + color: getButtonColor(this.node8.childNodes[0].parentNode as TaroButtonElement, BUTTON_THEME_COLOR.get((this.node8.childNodes[0].parentNode as TaroButtonElement)._attrs.type || '').text) + })) + } else { + Text(this.node8.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node8.childNodes[0]?.parentElement as TaroElement)) + .width(getTextInViewWidth(this.node8.childNodes[0].parentElement)) + } + } + } else { + Text(this.node8.childNodes[0].textContent) { + // text 下还有标签 + if (this.node8.childNodes[0].childNodes.length > 1 || ((this.node8.childNodes[0].childNodes[0] && this.node8.childNodes[0].childNodes[0] as TaroElement)?.nodeType === NodeType.ELEMENT_NODE)) { + ForEach(this.node8.childNodes[0].childNodes, (item: TaroElement) => { + createTextChildNode(item, getSpanVerticalAlign((this.node8.childNodes[0] as TaroElement).hmStyle?.verticalAlign)) + }, (item: TaroElement) => item._nid) + } + } + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', this.node8.childNodes[0] as TaroElement), this.node8.childNodes[0] as TaroElement, ['click'])) + .attributeModifier(textModify.setNode(this.node8.childNodes[0] as TaroElement).withNormalStyle()) + .onVisibleAreaChange(getNodeThresholds((this.node8.childNodes[0] as TaroElement)) || [0.0, 1.0], getComponentEventCallback((this.node8.childNodes[0] as TaroElement), VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback((this.node8.childNodes[0] as TaroElement), AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node8.childNodes[0] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } } - .attrs(getNormalAttributes(this.node8)) - .onVisibleAreaChange(getNodeThresholds(this.node8) || [0.0, 1.0], getComponentEventCallback(this.node8, VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node8, AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node8._nid].areaInfo = areaResult + .attributeModifier(columnModify.setNode(this.node8 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node8 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node8 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node8 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node8 as TaroElement)._nodeInfo.areaInfo = res[1] })) } - if (this.node0.childNodes[4]._attrs.compileIf) { - if (this.node0.childNodes[4]._attrs.compileIf) { - Flex(FlexManager.flexOptions(this.node10)) { - Text(this.node10.childNodes[0].textContent) - .attrsText(getTextAttributes(this.node10.childNodes[0])) - .onVisibleAreaChange(getNodeThresholds(this.node10.childNodes[0]) || [0.0, 1.0], getComponentEventCallback(this.node10.childNodes[0], VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node10.childNodes[0], AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node10.childNodes[0]._nid].areaInfo = areaResult + if ((this.node0.childNodes[4] as TaroElement)._attrs.compileIf) { + } else { + Column() { + if (this.node9.childNodes[0].nodeType === NodeType.TEXT_NODE) { + if (this.node9.childNodes[0].parentNode) { + if ((this.node9.childNodes[0].parentNode as TaroElement).tagName === 'BUTTON') { + Text(this.node9.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node9.childNodes[0]?.parentElement as TaroElement, { + fontSize: getButtonFontSize(this.node9.childNodes[0].parentNode as TaroButtonElement), + color: getButtonColor(this.node9.childNodes[0].parentNode as TaroButtonElement, BUTTON_THEME_COLOR.get((this.node9.childNodes[0].parentNode as TaroButtonElement)._attrs.type || '').text) + })) + } else { + Text(this.node9.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node9.childNodes[0]?.parentElement as TaroElement)) + .width(getTextInViewWidth(this.node9.childNodes[0].parentElement)) + } + } + } else { + Text(this.node9.childNodes[0].textContent) { + // text 下还有标签 + if (this.node9.childNodes[0].childNodes.length > 1 || ((this.node9.childNodes[0].childNodes[0] && this.node9.childNodes[0].childNodes[0] as TaroElement)?.nodeType === NodeType.ELEMENT_NODE)) { + ForEach(this.node9.childNodes[0].childNodes, (item: TaroElement) => { + createTextChildNode(item, getSpanVerticalAlign((this.node9.childNodes[0] as TaroElement).hmStyle?.verticalAlign)) + }, (item: TaroElement) => item._nid) + } + } + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', this.node9.childNodes[0] as TaroElement), this.node9.childNodes[0] as TaroElement, ['click'])) + .attributeModifier(textModify.setNode(this.node9.childNodes[0] as TaroElement).withNormalStyle()) + .onVisibleAreaChange(getNodeThresholds((this.node9.childNodes[0] as TaroElement)) || [0.0, 1.0], getComponentEventCallback((this.node9.childNodes[0] as TaroElement), VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback((this.node9.childNodes[0] as TaroElement), AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node9.childNodes[0] as TaroElement)._nodeInfo.areaInfo = res[1] })) } - .attrs(getNormalAttributes(this.node10)) - .onVisibleAreaChange(getNodeThresholds(this.node10) || [0.0, 1.0], getComponentEventCallback(this.node10, VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node10, AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node10._nid].areaInfo = areaResult - })) } - } else { - Flex(FlexManager.flexOptions(this.node9)) { - Text(this.node9.childNodes[0].textContent) - .attrsText(getTextAttributes(this.node9.childNodes[0])) - .onVisibleAreaChange(getNodeThresholds(this.node9.childNodes[0]) || [0.0, 1.0], getComponentEventCallback(this.node9.childNodes[0], VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node9.childNodes[0], AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node9.childNodes[0]._nid].areaInfo = areaResult - })) + .attributeModifier(columnModify.setNode(this.node9 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node9 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node9 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node9 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node9 as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } + if ((this.node0.childNodes[5] as TaroElement)._attrs.compileIf) { + Column() { + if (this.node10.childNodes[0].nodeType === NodeType.TEXT_NODE) { + if (this.node10.childNodes[0].parentNode) { + if ((this.node10.childNodes[0].parentNode as TaroElement).tagName === 'BUTTON') { + Text(this.node10.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node10.childNodes[0]?.parentElement as TaroElement, { + fontSize: getButtonFontSize(this.node10.childNodes[0].parentNode as TaroButtonElement), + color: getButtonColor(this.node10.childNodes[0].parentNode as TaroButtonElement, BUTTON_THEME_COLOR.get((this.node10.childNodes[0].parentNode as TaroButtonElement)._attrs.type || '').text) + })) + } else { + Text(this.node10.childNodes[0].textContent) + .attributeModifier(textModify.setNode(this.node10.childNodes[0]?.parentElement as TaroElement)) + .width(getTextInViewWidth(this.node10.childNodes[0].parentElement)) + } + } + } else { + Text(this.node10.childNodes[0].textContent) { + // text 下还有标签 + if (this.node10.childNodes[0].childNodes.length > 1 || ((this.node10.childNodes[0].childNodes[0] && this.node10.childNodes[0].childNodes[0] as TaroElement)?.nodeType === NodeType.ELEMENT_NODE)) { + ForEach(this.node10.childNodes[0].childNodes, (item: TaroElement) => { + createTextChildNode(item, getSpanVerticalAlign((this.node10.childNodes[0] as TaroElement).hmStyle?.verticalAlign)) + }, (item: TaroElement) => item._nid) + } + } + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', this.node10.childNodes[0] as TaroElement), this.node10.childNodes[0] as TaroElement, ['click'])) + .attributeModifier(textModify.setNode(this.node10.childNodes[0] as TaroElement).withNormalStyle()) + .onVisibleAreaChange(getNodeThresholds((this.node10.childNodes[0] as TaroElement)) || [0.0, 1.0], getComponentEventCallback((this.node10.childNodes[0] as TaroElement), VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback((this.node10.childNodes[0] as TaroElement), AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node10.childNodes[0] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } } - .attrs(getNormalAttributes(this.node9)) - .onVisibleAreaChange(getNodeThresholds(this.node9) || [0.0, 1.0], getComponentEventCallback(this.node9, VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node9, AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node9._nid].areaInfo = areaResult + .attributeModifier(columnModify.setNode(this.node10 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node10 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node10 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node10 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node10 as TaroElement)._nodeInfo.areaInfo = res[1] })) } - if (this.node0.childNodes[5]._attrs.compileIf) { - Flex(FlexManager.flexOptions(this.node12)) { - Text(this.node12.childNodes[0].textContent) - .attrsText(getTextAttributes(this.node12.childNodes[0])) - .onVisibleAreaChange(getNodeThresholds(this.node12.childNodes[0]) || [0.0, 1.0], getComponentEventCallback(this.node12.childNodes[0], VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node12.childNodes[0], AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node12.childNodes[0]._nid].areaInfo = areaResult + if ((this.node0.childNodes[6] as TaroElement)._attrs.compileIf) { + if (this.node0.childNodes[6].nodeType === NodeType.TEXT_NODE) { + if (this.node0.childNodes[6].parentNode) { + if ((this.node0.childNodes[6].parentNode as TaroElement).tagName === 'BUTTON') { + Text(this.node0.childNodes[6].textContent) + .attributeModifier(textModify.setNode(this.node0.childNodes[6]?.parentElement as TaroElement, { + fontSize: getButtonFontSize(this.node0.childNodes[6].parentNode as TaroButtonElement), + color: getButtonColor(this.node0.childNodes[6].parentNode as TaroButtonElement, BUTTON_THEME_COLOR.get((this.node0.childNodes[6].parentNode as TaroButtonElement)._attrs.type || '').text) + })) + } else { + Text(this.node0.childNodes[6].textContent) + .attributeModifier(textModify.setNode(this.node0.childNodes[6]?.parentElement as TaroElement)) + .width(getTextInViewWidth(this.node0.childNodes[6].parentElement)) + } + } + } else { + Text(this.node0.childNodes[6].textContent) { + // text 下还有标签 + if (this.node0.childNodes[6].childNodes.length > 1 || ((this.node0.childNodes[6].childNodes[0] && this.node0.childNodes[6].childNodes[0] as TaroElement)?.nodeType === NodeType.ELEMENT_NODE)) { + ForEach(this.node0.childNodes[6].childNodes, (item: TaroElement) => { + createTextChildNode(item, getSpanVerticalAlign((this.node0.childNodes[6] as TaroElement).hmStyle?.verticalAlign)) + }, (item: TaroElement) => item._nid) + } + } + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', this.node0.childNodes[6] as TaroElement), this.node0.childNodes[6] as TaroElement, ['click'])) + .attributeModifier(textModify.setNode(this.node0.childNodes[6] as TaroElement).withNormalStyle()) + .onVisibleAreaChange(getNodeThresholds((this.node0.childNodes[6] as TaroElement)) || [0.0, 1.0], getComponentEventCallback((this.node0.childNodes[6] as TaroElement), VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback((this.node0.childNodes[6] as TaroElement), AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0.childNodes[6] as TaroElement)._nodeInfo.areaInfo = res[1] })) } - .attrs(getNormalAttributes(this.node12)) - .onVisibleAreaChange(getNodeThresholds(this.node12) || [0.0, 1.0], getComponentEventCallback(this.node12, VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node12, AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node12._nid].areaInfo = areaResult - })) } else { - if (this.node0.childNodes[5]._attrs.compileIf) { - Flex(FlexManager.flexOptions(this.node11)) { - Text(this.node11.childNodes[0].textContent) - .attrsText(getTextAttributes(this.node11.childNodes[0])) - .onVisibleAreaChange(getNodeThresholds(this.node11.childNodes[0]) || [0.0, 1.0], getComponentEventCallback(this.node11.childNodes[0], VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node11.childNodes[0], AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node11.childNodes[0]._nid].areaInfo = areaResult - })) + if (this.node0.childNodes[6].nodeType === NodeType.TEXT_NODE) { + if (this.node0.childNodes[6].parentNode) { + if ((this.node0.childNodes[6].parentNode as TaroElement).tagName === 'BUTTON') { + Text(this.node0.childNodes[6].textContent) + .attributeModifier(textModify.setNode(this.node0.childNodes[6]?.parentElement as TaroElement, { + fontSize: getButtonFontSize(this.node0.childNodes[6].parentNode as TaroButtonElement), + color: getButtonColor(this.node0.childNodes[6].parentNode as TaroButtonElement, BUTTON_THEME_COLOR.get((this.node0.childNodes[6].parentNode as TaroButtonElement)._attrs.type || '').text) + })) + } else { + Text(this.node0.childNodes[6].textContent) + .attributeModifier(textModify.setNode(this.node0.childNodes[6]?.parentElement as TaroElement)) + .width(getTextInViewWidth(this.node0.childNodes[6].parentElement)) + } + } + } else { + Text(this.node0.childNodes[6].textContent) { + // text 下还有标签 + if (this.node0.childNodes[6].childNodes.length > 1 || ((this.node0.childNodes[6].childNodes[0] && this.node0.childNodes[6].childNodes[0] as TaroElement)?.nodeType === NodeType.ELEMENT_NODE)) { + ForEach(this.node0.childNodes[6].childNodes, (item: TaroElement) => { + createTextChildNode(item, getSpanVerticalAlign((this.node0.childNodes[6] as TaroElement).hmStyle?.verticalAlign)) + }, (item: TaroElement) => item._nid) + } } - .attrs(getNormalAttributes(this.node11)) - .onVisibleAreaChange(getNodeThresholds(this.node11) || [0.0, 1.0], getComponentEventCallback(this.node11, VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node11, AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node11._nid].areaInfo = areaResult + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', this.node0.childNodes[6] as TaroElement), this.node0.childNodes[6] as TaroElement, ['click'])) + .attributeModifier(textModify.setNode(this.node0.childNodes[6] as TaroElement).withNormalStyle()) + .onVisibleAreaChange(getNodeThresholds((this.node0.childNodes[6] as TaroElement)) || [0.0, 1.0], getComponentEventCallback((this.node0.childNodes[6] as TaroElement), VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback((this.node0.childNodes[6] as TaroElement), AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0.childNodes[6] as TaroElement)._nodeInfo.areaInfo = res[1] })) } } - if (this.node0.childNodes[6]._attrs.compileIf) { - Text(this.node0.childNodes[6].textContent) - .attrsText(getTextAttributes(this.node0.childNodes[6])) - .onVisibleAreaChange(getNodeThresholds(this.node0.childNodes[6]) || [0.0, 1.0], getComponentEventCallback(this.node0.childNodes[6], VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node0.childNodes[6], AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node0.childNodes[6]._nid].areaInfo = areaResult - })) - } else { - Text(this.node0.childNodes[6].textContent) - .attrsText(getTextAttributes(this.node0.childNodes[6])) - .onVisibleAreaChange(getNodeThresholds(this.node0.childNodes[6]) || [0.0, 1.0], getComponentEventCallback(this.node0.childNodes[6], VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node0.childNodes[6], AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node0.childNodes[6]._nid].areaInfo = areaResult - })) - } - Flex(FlexManager.flexOptions(this.node13)) {} - .attrs(getNormalAttributes(this.node13)) - .onVisibleAreaChange(getNodeThresholds(this.node13) || [0.0, 1.0], getComponentEventCallback(this.node13, VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node13, AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node13._nid].areaInfo = areaResult + Column() {} + .attributeModifier(columnModify.setNode(this.node11 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node11 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node11 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node11 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node11 as TaroElement)._nodeInfo.areaInfo = res[1] })) } - .attrs(getNormalAttributes(this.node0)) - .onVisibleAreaChange(getNodeThresholds(this.node0) || [0.0, 1.0], getComponentEventCallback(this.node0, VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node0, AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node0._nid].areaInfo = areaResult + .attributeModifier(columnModify.setNode(this.node0 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node0 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node0 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node0 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0 as TaroElement)._nodeInfo.areaInfo = res[1] })) } } -export default TARO_TEMPLATES_f0t0 `; function Index() { return @@ -395,17 +689,17 @@ function Index() { {condition1 ? condition2 ? {a} : {b} : {c}} - {condition1 ? {a} : condition2 ? {b} : {c}} + {condition1 ? {a} : condition2 ? {b} : {c}} - {condition1 ? {a} : condition2 ? {b} : {c}} + {condition1 ? {a} : condition2 ? {b} : {c}} - {condition1 ? condition2 ? {a} : : {b}} + {condition1 ? condition2 && {a} : {b}} - {condition1 ? {a} : condition2 ? {b} : } + {condition1 ? {a} : condition2 && {b}} {condition1 ? "someText" : 789} - + ; } diff --git a/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/entry.rs/should_support_compile_child_node.js b/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/entry.rs/should_support_compile_child_node.js index 247a62723176..4c2892495e30 100644 --- a/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/entry.rs/should_support_compile_child_node.js +++ b/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/entry.rs/should_support_compile_child_node.js @@ -1,168 +1,98 @@ -const TARO_TEMPLATES_f0t0 = `import { FlexManager } from './utils/FlexManager' -import { getNodeThresholds, getNormalAttributes, getTextAttributes } from './utils/helper' -import { TaroIgnoreElement, eventHandler, DynamicCenter, getComponentEventCallback, AREA_CHANGE_EVENT_NAME, VISIBLE_CHANGE_EVENT_NAME } from '../runtime' -import type { TaroElement } from '../runtime' -import { TOUCH_EVENT_MAP } from './utils/constant/event' -@Extend(Flex) -function attrs ({ - flexBasis, - flexGrow, - flexShrink, - alignSelf, - clip, - width, - height, - margin, - padding, - linearGradient, - zIndex, - borderStyle, - borderWidth, - borderColor, - borderRadius, - opacity, - backgroundColor, - backgroundImage, - backgroundRepeat, - backgroundImageSize, - constraintSize, - rotate, - scale, - translate, - transform -}) { - .flexGrow(flexGrow) - .flexShrink(flexShrink) - .flexBasis(flexBasis) - .alignSelf(alignSelf) - .width(width) - .height(height) - .constraintSize(constraintSize) - .margin(margin) - .padding(padding) - .linearGradient(linearGradient) - .zIndex(zIndex) - .borderStyle(borderStyle) - .borderWidth(borderWidth) - .borderColor(borderColor) - .borderRadius(borderRadius) - .opacity(opacity) - .backgroundColor(backgroundColor) - .backgroundImage(backgroundImage, backgroundRepeat) - .backgroundImageSize(backgroundImageSize) - .rotate(rotate) - .scale(scale) - .translate(translate) - .transform(transform) - .clip(clip) -} -@Extend(Image) -function attrsImage ({ - flexBasis, - flexGrow, - flexShrink, - alignSelf, - clip, - width, - height, - margin, - padding, - linearGradient, - zIndex, - borderStyle, - borderWidth, - borderColor, - borderRadius, - opacity, - backgroundColor, - backgroundImage, - backgroundRepeat, - backgroundImageSize, - constraintSize, - rotate, - scale, - translate, - transform -}) { - .flexGrow(flexGrow) - .flexShrink(flexShrink) - .flexBasis(flexBasis) - .alignSelf(alignSelf) - .width(width) - .height(height) - .constraintSize(constraintSize) - .margin(margin) - .padding(padding) - .linearGradient(linearGradient) - .zIndex(zIndex) - .borderStyle(borderStyle) - .borderWidth(borderWidth) - .borderColor(borderColor) - .borderRadius(borderRadius) - .opacity(opacity) - .backgroundColor(backgroundColor) - .backgroundImage(backgroundImage, backgroundRepeat) - .backgroundImageSize(backgroundImageSize) - .rotate(rotate) - .scale(scale) - .translate(translate) - .transform(transform) - .clip(clip) - .objectFit(ImageFit.Contain) -} +const TARO_TEMPLATES_f0t0 = `import { + rowModify, + FlexManager, + columnModify, + DynamicCenter, + getButtonColor, + TOUCH_EVENT_MAP, + getFontAttributes, + commonStyleModify, + getNodeThresholds, + BUTTON_THEME_COLOR, + getStyleAttr, + getNormalAttributes, + shouldBindEvent, + textModify, + setNormalTextAttributeIntoInstance, + getImageMode +} from '@tarojs/components' +import { + NodeType, + convertNumber2VP, + TaroElement, + eventHandler, + getComponentEventCallback, + AREA_CHANGE_EVENT_NAME, + VISIBLE_CHANGE_EVENT_NAME +} from '@tarojs/runtime' +import { + createLazyChildren, + createChildItem +} from '../render' + +import type { + TaroTextElement, + HarmonyStyle, + TaroButtonElement, + TaroViewElement, + TaroAny, + TaroStyleType, + TaroTextStyleType +} from '@tarojs/runtime' +import { isString } from '@tarojs/shared' @Component -struct TARO_TEMPLATES_f0t0 { - nodeInfoMap: any = {} - dynamicCenter: DynamicCenter - @ObjectLink node: TaroElement +export default struct TARO_TEMPLATES_f0t0 { + node: TaroViewElement = new TaroElement('Ignore') + + dynamicCenter: DynamicCenter = new DynamicCenter() aboutToAppear () { - this.dynamicCenter = new DynamicCenter() this.dynamicCenter.bindComponentToNodeWithDFS(this.node, this) } - @State node0: TaroElement = new TaroIgnoreElement() + @State node0: TaroElement = new TaroElement('Ignore') build() { - Flex(FlexManager.flexOptions(this.node0)) { - Flex(FlexManager.flexOptions(this.node0.childNodes[0])) {} - .attrs(getNormalAttributes(this.node0.childNodes[0])) - .onVisibleAreaChange(getNodeThresholds(this.node0.childNodes[0]) || [0.0, 1.0], getComponentEventCallback(this.node0.childNodes[0], VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node0.childNodes[0], AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node0.childNodes[0]._nid].areaInfo = areaResult + Column() { + Column() {} + .attributeModifier(columnModify.setNode(this.node0.childNodes[0] as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node0.childNodes[0] as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node0.childNodes[0] as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node0.childNodes[0] as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0.childNodes[0] as TaroElement)._nodeInfo.areaInfo = res[1] })) - Flex(FlexManager.flexOptions(this.node0.childNodes[1])) { - Image(this.node0.childNodes[1].childNodes[0].getAttribute('src')) - .attrsImage(getNormalAttributes(this.node0.childNodes[1].childNodes[0])) - .onVisibleAreaChange(getNodeThresholds(this.node0.childNodes[1].childNodes[0]) || [0.0, 1.0], getComponentEventCallback(this.node0.childNodes[1].childNodes[0], VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node0.childNodes[1].childNodes[0], AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node0.childNodes[1].childNodes[0]._nid].areaInfo = areaResult + Column() { + Image((this.node0.childNodes[1].childNodes[0] as TaroElement).getAttribute('src')) + .objectFit(getImageMode((this.node0.childNodes[1].childNodes[0] as TaroElement).getAttribute('mode'))) + .attributeModifier(commonStyleModify.setNode(this.node0.childNodes[1].childNodes[0] as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node0.childNodes[1].childNodes[0] as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node0.childNodes[1].childNodes[0] as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node0.childNodes[1].childNodes[0] as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0.childNodes[1].childNodes[0] as TaroElement)._nodeInfo.areaInfo = res[1] })) } - .attrs(getNormalAttributes(this.node0.childNodes[1])) - .onVisibleAreaChange(getNodeThresholds(this.node0.childNodes[1]) || [0.0, 1.0], getComponentEventCallback(this.node0.childNodes[1], VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node0.childNodes[1], AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node0.childNodes[1]._nid].areaInfo = areaResult + .attributeModifier(columnModify.setNode(this.node0.childNodes[1] as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node0.childNodes[1] as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node0.childNodes[1] as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node0.childNodes[1] as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0.childNodes[1] as TaroElement)._nodeInfo.areaInfo = res[1] })) } - .attrs(getNormalAttributes(this.node0)) - .onVisibleAreaChange(getNodeThresholds(this.node0) || [0.0, 1.0], getComponentEventCallback(this.node0, VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node0, AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node0._nid].areaInfo = areaResult + .attributeModifier(columnModify.setNode(this.node0 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node0 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node0 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node0 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0 as TaroElement)._nodeInfo.areaInfo = res[1] })) } } -export default TARO_TEMPLATES_f0t0 -` +`; function Index() { return + + + + - + + ; } diff --git a/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/entry.rs/should_support_component_not_in_config.js b/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/entry.rs/should_support_component_not_in_config.js index 35dc23f96f62..435e7ed2bff6 100644 --- a/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/entry.rs/should_support_component_not_in_config.js +++ b/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/entry.rs/should_support_component_not_in_config.js @@ -1,108 +1,83 @@ -const TARO_TEMPLATES_f0t0 = `import { FlexManager } from './utils/FlexManager' -import { getNodeThresholds, getNormalAttributes, getTextAttributes } from './utils/helper' -import { TaroIgnoreElement, eventHandler, DynamicCenter, getComponentEventCallback, AREA_CHANGE_EVENT_NAME, VISIBLE_CHANGE_EVENT_NAME } from '../runtime' -import type { TaroElement } from '../runtime' -import { TOUCH_EVENT_MAP } from './utils/constant/event' -@Extend(Flex) -function attrs ({ - flexBasis, - flexGrow, - flexShrink, - alignSelf, - clip, - width, - height, - margin, - padding, - linearGradient, - zIndex, - borderStyle, - borderWidth, - borderColor, - borderRadius, - opacity, - backgroundColor, - backgroundImage, - backgroundRepeat, - backgroundImageSize, - constraintSize, - rotate, - scale, - translate, - transform -}) { - .flexGrow(flexGrow) - .flexShrink(flexShrink) - .flexBasis(flexBasis) - .alignSelf(alignSelf) - .width(width) - .height(height) - .constraintSize(constraintSize) - .margin(margin) - .padding(padding) - .linearGradient(linearGradient) - .zIndex(zIndex) - .borderStyle(borderStyle) - .borderWidth(borderWidth) - .borderColor(borderColor) - .borderRadius(borderRadius) - .opacity(opacity) - .backgroundColor(backgroundColor) - .backgroundImage(backgroundImage, backgroundRepeat) - .backgroundImageSize(backgroundImageSize) - .rotate(rotate) - .scale(scale) - .translate(translate) - .transform(transform) - .clip(clip) -} +const TARO_TEMPLATES_f0t0 = `import { + rowModify, + FlexManager, + columnModify, + DynamicCenter, + getButtonColor, + TOUCH_EVENT_MAP, + getFontAttributes, + commonStyleModify, + getNodeThresholds, + BUTTON_THEME_COLOR, + getStyleAttr, + getNormalAttributes, + shouldBindEvent, + textModify, + setNormalTextAttributeIntoInstance, + getImageMode +} from '@tarojs/components' +import { + NodeType, + convertNumber2VP, + TaroElement, + eventHandler, + getComponentEventCallback, + AREA_CHANGE_EVENT_NAME, + VISIBLE_CHANGE_EVENT_NAME +} from '@tarojs/runtime' +import { + createLazyChildren, + createChildItem +} from '../render' + +import type { + TaroTextElement, + HarmonyStyle, + TaroButtonElement, + TaroViewElement, + TaroAny, + TaroStyleType, + TaroTextStyleType +} from '@tarojs/runtime' +import { isString } from '@tarojs/shared' @Component -struct TARO_TEMPLATES_f0t0 { - nodeInfoMap: any = {} - dynamicCenter: DynamicCenter - @ObjectLink node: TaroElement +export default struct TARO_TEMPLATES_f0t0 { + node: TaroViewElement = new TaroElement('Ignore') + + dynamicCenter: DynamicCenter = new DynamicCenter() aboutToAppear () { - this.dynamicCenter = new DynamicCenter() this.dynamicCenter.bindComponentToNodeWithDFS(this.node, this) } - @State node0: TaroElement = new TaroIgnoreElement() + @State node0: TaroElement = new TaroElement('Ignore') build() { - Flex(FlexManager.flexOptions(this.node0)) { - Flex(FlexManager.flexOptions(this.node0.childNodes[0])) { - ForEach(this.node0.childNodes, item => { - createNode(item) - }, item => item._nid) + Column() { + Column() { + createChildItem(this.node0.childNodes[0].childNodes[0] as TaroElement, createLazyChildren) } - .attrs(getNormalAttributes(this.node0.childNodes[0])) - .onVisibleAreaChange(getNodeThresholds(this.node0.childNodes[0]) || [0.0, 1.0], getComponentEventCallback(this.node0.childNodes[0], VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node0.childNodes[0], AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node0.childNodes[0]._nid].areaInfo = areaResult + .attributeModifier(columnModify.setNode(this.node0.childNodes[0] as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node0.childNodes[0] as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node0.childNodes[0] as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node0.childNodes[0] as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0.childNodes[0] as TaroElement)._nodeInfo.areaInfo = res[1] })) - Flex(FlexManager.flexOptions(this.node0.childNodes[1])) { - ForEach(this.node0.childNodes, item => { - createNode(item) - }, item => item._nid) + Column() { + createChildItem(this.node0.childNodes[1].childNodes[0] as TaroElement, createLazyChildren) } - .attrs(getNormalAttributes(this.node0.childNodes[1])) - .onVisibleAreaChange(getNodeThresholds(this.node0.childNodes[1]) || [0.0, 1.0], getComponentEventCallback(this.node0.childNodes[1], VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node0.childNodes[1], AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node0.childNodes[1]._nid].areaInfo = areaResult + .attributeModifier(columnModify.setNode(this.node0.childNodes[1] as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node0.childNodes[1] as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node0.childNodes[1] as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node0.childNodes[1] as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0.childNodes[1] as TaroElement)._nodeInfo.areaInfo = res[1] })) } - .attrs(getNormalAttributes(this.node0)) - .onVisibleAreaChange(getNodeThresholds(this.node0) || [0.0, 1.0], getComponentEventCallback(this.node0, VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node0, AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node0._nid].areaInfo = areaResult + .attributeModifier(columnModify.setNode(this.node0 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node0 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node0 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node0 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0 as TaroElement)._nodeInfo.areaInfo = res[1] })) } } -export default TARO_TEMPLATES_f0t0 `; function Index() { return diff --git a/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/entry.rs/should_support_multi_compile_mode.js b/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/entry.rs/should_support_multi_compile_mode.js index c0820bc38727..59e75d20bdae 100644 --- a/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/entry.rs/should_support_multi_compile_mode.js +++ b/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/entry.rs/should_support_multi_compile_mode.js @@ -1,255 +1,305 @@ -const TARO_TEMPLATES_f0t0 = `import { FlexManager } from './utils/FlexManager' -import { getNodeThresholds, getNormalAttributes, getTextAttributes } from './utils/helper' -import { TaroIgnoreElement, eventHandler, DynamicCenter, getComponentEventCallback, AREA_CHANGE_EVENT_NAME, VISIBLE_CHANGE_EVENT_NAME } from '../runtime' -import type { TaroElement } from '../runtime' -import { TOUCH_EVENT_MAP } from './utils/constant/event' -@Extend(Image) -function attrsImage ({ - flexBasis, - flexGrow, - flexShrink, - alignSelf, - clip, - width, - height, - margin, - padding, - linearGradient, - zIndex, - borderStyle, - borderWidth, - borderColor, - borderRadius, - opacity, - backgroundColor, - backgroundImage, - backgroundRepeat, - backgroundImageSize, - constraintSize, - rotate, - scale, - translate, - transform -}) { - .flexGrow(flexGrow) - .flexShrink(flexShrink) - .flexBasis(flexBasis) - .alignSelf(alignSelf) - .width(width) - .height(height) - .constraintSize(constraintSize) - .margin(margin) - .padding(padding) - .linearGradient(linearGradient) - .zIndex(zIndex) - .borderStyle(borderStyle) - .borderWidth(borderWidth) - .borderColor(borderColor) - .borderRadius(borderRadius) - .opacity(opacity) - .backgroundColor(backgroundColor) - .backgroundImage(backgroundImage, backgroundRepeat) - .backgroundImageSize(backgroundImageSize) - .rotate(rotate) - .scale(scale) - .translate(translate) - .transform(transform) - .clip(clip) - .objectFit(ImageFit.Contain) -} +const TARO_TEMPLATES_f0t0 = `import { + rowModify, + FlexManager, + columnModify, + DynamicCenter, + getButtonColor, + TOUCH_EVENT_MAP, + getFontAttributes, + commonStyleModify, + getNodeThresholds, + BUTTON_THEME_COLOR, + getStyleAttr, + getNormalAttributes, + shouldBindEvent, + textModify, + setNormalTextAttributeIntoInstance, + getImageMode +} from '@tarojs/components' +import { + NodeType, + convertNumber2VP, + TaroElement, + eventHandler, + getComponentEventCallback, + AREA_CHANGE_EVENT_NAME, + VISIBLE_CHANGE_EVENT_NAME +} from '@tarojs/runtime' +import { + createLazyChildren, + createChildItem +} from '../render' + +import type { + TaroTextElement, + HarmonyStyle, + TaroButtonElement, + TaroViewElement, + TaroAny, + TaroStyleType, + TaroTextStyleType +} from '@tarojs/runtime' +import { isString } from '@tarojs/shared' @Component -struct TARO_TEMPLATES_f0t0 { - nodeInfoMap: any = {} - dynamicCenter: DynamicCenter - @ObjectLink node: TaroElement +export default struct TARO_TEMPLATES_f0t0 { + node: TaroViewElement = new TaroElement('Ignore') + + dynamicCenter: DynamicCenter = new DynamicCenter() aboutToAppear () { - this.dynamicCenter = new DynamicCenter() this.dynamicCenter.bindComponentToNodeWithDFS(this.node, this) } - @State node0: TaroElement = new TaroIgnoreElement() + @State node0: TaroElement = new TaroElement('Ignore') build() { - Image(this.node0.getAttribute('src')) - .attrsImage(getNormalAttributes(this.node0)) - .onVisibleAreaChange(getNodeThresholds(this.node0) || [0.0, 1.0], getComponentEventCallback(this.node0, VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node0, AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node0._nid].areaInfo = areaResult + Image((this.node0 as TaroElement).getAttribute('src')) + .objectFit(getImageMode((this.node0 as TaroElement).getAttribute('mode'))) + .attributeModifier(commonStyleModify.setNode(this.node0 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node0 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node0 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node0 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0 as TaroElement)._nodeInfo.areaInfo = res[1] })) } } -export default TARO_TEMPLATES_f0t0 -` -const TARO_TEMPLATES_f0t1 = `import { FlexManager } from './utils/FlexManager' -import { getNodeThresholds, getNormalAttributes, getTextAttributes } from './utils/helper' -import { TaroIgnoreElement, eventHandler, DynamicCenter, getComponentEventCallback, AREA_CHANGE_EVENT_NAME, VISIBLE_CHANGE_EVENT_NAME } from '../runtime' -import type { TaroElement } from '../runtime' -import { TOUCH_EVENT_MAP } from './utils/constant/event' -@Extend(Flex) -function attrs ({ - flexBasis, - flexGrow, - flexShrink, - alignSelf, - clip, - width, - height, - margin, - padding, - linearGradient, - zIndex, - borderStyle, - borderWidth, - borderColor, - borderRadius, - opacity, - backgroundColor, - backgroundImage, - backgroundRepeat, - backgroundImageSize, - constraintSize, - rotate, - scale, - translate, - transform -}) { - .flexGrow(flexGrow) - .flexShrink(flexShrink) - .flexBasis(flexBasis) - .alignSelf(alignSelf) - .width(width) - .height(height) - .constraintSize(constraintSize) - .margin(margin) - .padding(padding) - .linearGradient(linearGradient) - .zIndex(zIndex) - .borderStyle(borderStyle) - .borderWidth(borderWidth) - .borderColor(borderColor) - .borderRadius(borderRadius) - .opacity(opacity) - .backgroundColor(backgroundColor) - .backgroundImage(backgroundImage, backgroundRepeat) - .backgroundImageSize(backgroundImageSize) - .rotate(rotate) - .scale(scale) - .translate(translate) - .transform(transform) - .clip(clip) +`; +const TARO_TEMPLATES_f0t1 = `import { + rowModify, + FlexManager, + columnModify, + DynamicCenter, + getButtonColor, + TOUCH_EVENT_MAP, + getFontAttributes, + commonStyleModify, + getNodeThresholds, + BUTTON_THEME_COLOR, + getStyleAttr, + getNormalAttributes, + shouldBindEvent, + textModify, + setNormalTextAttributeIntoInstance, + getImageMode +} from '@tarojs/components' +import { + NodeType, + convertNumber2VP, + TaroElement, + eventHandler, + getComponentEventCallback, + AREA_CHANGE_EVENT_NAME, + VISIBLE_CHANGE_EVENT_NAME +} from '@tarojs/runtime' +import { + createLazyChildren, + createChildItem +} from '../render' + +import type { + TaroTextElement, + HarmonyStyle, + TaroButtonElement, + TaroViewElement, + TaroAny, + TaroStyleType, + TaroTextStyleType +} from '@tarojs/runtime' +import { isString } from '@tarojs/shared' +@Extend(Text) +function textNormalFontStyle (style: HarmonyStyle) { + .id(style.id) + .key(style.id) + .opacity(style.opacity) + .fontColor(style.color) + .fontSize(style.fontSize) + .fontWeight(style.fontWeight) + .fontStyle(style.fontStyle) + .fontFamily(style.fontFamily) + .lineHeight(style.lineHeight) + .decoration({ + type: style.textDecoration?.type, + color: style.color + }) } + @Extend(Text) -function attrsText ({ - id, - width, - height, - zIndex, - opacity, - margin, - padding, - decoration, - lineHeight, - letterSpacing, - maxLines, - fontColor, - fontSize, - fontWeight, - fontFamily, - textOverflow, - constraintSize, - border, - borderRadius, - backgroundColor, - backgroundImage, - backgroundRepeat, - backgroundImageSize, - rotate, - scale, - translate, - transform, - textAlign, - }) { - .id(id) - .key(id) - .constraintSize(constraintSize) - .zIndex(zIndex) - .opacity(opacity) - .margin(margin) - .padding(padding) - .decoration(decoration) - .lineHeight(lineHeight) - .letterSpacing(letterSpacing) - .maxLines(maxLines) - .fontColor(fontColor) - .fontSize(fontSize) - .fontWeight(fontWeight) - .fontFamily(fontFamily) - .textOverflow(textOverflow) - .border(border) - .borderRadius(borderRadius) - .backgroundColor(backgroundColor) - .backgroundImage(backgroundImage, backgroundRepeat) - .backgroundImageSize(backgroundImageSize) - .rotate(rotate) - .scale(scale) - .translate(translate) - .transform(transform) - .textAlign(textAlign) - .width(width) - .height(height) +function textSpecialFontStyle(attr: TaroTextStyleType) { + .textAlign(attr.textAlign) + .textOverflow(attr.textOverflow) + .maxLines(attr.WebkitLineClamp) + .letterSpacing(attr.letterSpacing) +} + +function getButtonFontSize (node: TaroButtonElement) { + const isMini = node._attrs.size === 'mini' + + return isMini ? convertNumber2VP(26) : convertNumber2VP(36) } -function getTextAttributes (node: TaroViewElement) { - const attrs = { - ...getNormalAttributes(node), - ...getFontAttributes(node) +@Builder +function createTextChildNode (item: TaroElement, align: ImageSpanAlignment) { + if (item.tagName === 'IMAGE') { + ImageSpan(item.getAttribute('src')) + .objectFit(getImageMode(item.getAttribute('mode'))) + .verticalAlign(align) + .width(item._st.hmStyle.width) + .height(item._st.hmStyle.height) + .margin({ + top: item._st.hmStyle.marginTop, + left: item._st.hmStyle.marginLeft, + right: item._st.hmStyle.marginRight, + bottom: item._st.hmStyle.marginBottom, + }) + .padding({ + top: item._st.hmStyle.paddingTop, + left: item._st.hmStyle.paddingLeft, + right: item._st.hmStyle.paddingRight, + bottom: item._st.hmStyle.paddingBottom, + }) + .textBackgroundStyle({ + color: item._st.hmStyle.backgroundColor, + radius: { + topLeft: item._st.hmStyle.borderTopLeftRadius, + topRight: item._st.hmStyle.borderTopRightRadius, + bottomLeft: item._st.hmStyle.borderBottomLeftRadius, + bottomRight: item._st.hmStyle.borderBottomRightRadius, + } + }) + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', item), item, ['click'])) + } else if (item.nodeType === NodeType.TEXT_NODE) { + Span(item.textContent) + } else if (item.tagName === 'TEXT') { + Span(item.textContent) + .attributeModifier((new SpanStyleModify()).setNode(item as TaroTextElement)) + .letterSpacing(item._st.hmStyle.letterSpacing) + .textBackgroundStyle({ + color: item._st.hmStyle.backgroundColor, + radius: { + topLeft: item._st.hmStyle.borderTopLeftRadius, + topRight: item._st.hmStyle.borderTopRightRadius, + bottomLeft: item._st.hmStyle.borderBottomLeftRadius, + bottomRight: item._st.hmStyle.borderBottomRightRadius, + } + }) + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', item), item, ['click'])) } +} - transformW3CToHarmonyInStyle(node._st, attrs) +class SpanStyleModify implements AttributeModifier { + node: TaroTextElement | null = null + style: HarmonyStyle | null = null + overwriteStyle: Record = {} + withNormal = false + + setNode (node: TaroTextElement) { + this.node = node + this.style = getNormalAttributes(this.node) + return this + } - return attrs + applyNormalAttribute(instance: SpanAttribute): void { + if (this.node && this.style) { + setNormalTextAttributeIntoInstance(instance, this.style, this.node) + } + } } + +function getSpanVerticalAlign (verticalAlign?: Alignment) { + switch (verticalAlign) { + case Alignment.Start: + case Alignment.TopStart: + case Alignment.Top: + case Alignment.TopEnd: { + return ImageSpanAlignment.TOP + } + case Alignment.End: + case Alignment.BottomStart: + case Alignment.Bottom: + case Alignment.BottomEnd: { + return ImageSpanAlignment.BOTTOM + } + case Alignment.Center: { + return ImageSpanAlignment.CENTER + } + } + return ImageSpanAlignment.BASELINE +} + +function getTextInViewWidth (node: TaroElement | null): TaroAny { + if (node) { + const hmStyle = node.hmStyle || {} + const isFlexView = hmStyle.display === 'flex' + const width: TaroAny = getStyleAttr(node, 'width') + const isPercentWidth = isString(width) && width.includes('%') + + return isFlexView || isPercentWidth ? null : getStyleAttr(node, 'width') + } +} + @Component -struct TARO_TEMPLATES_f0t1 { - nodeInfoMap: any = {} - dynamicCenter: DynamicCenter - @ObjectLink node: TaroElement +export default struct TARO_TEMPLATES_f0t1 { + node: TaroViewElement = new TaroElement('Ignore') + + dynamicCenter: DynamicCenter = new DynamicCenter() aboutToAppear () { - this.dynamicCenter = new DynamicCenter() this.dynamicCenter.bindComponentToNodeWithDFS(this.node, this) } - @State node0: TaroElement = new TaroIgnoreElement() - @State node1: TaroElement = new TaroIgnoreElement() + @State node0: TaroElement = new TaroElement('Ignore') + @State node1: TaroElement = new TaroElement('Ignore') build() { - Flex(FlexManager.flexOptions(this.node0)) { - Text(this.node1.textContent) - .attrsText(getTextAttributes(this.node1)) - .onVisibleAreaChange(getNodeThresholds(this.node1) || [0.0, 1.0], getComponentEventCallback(this.node1, VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node1, AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node1._nid].areaInfo = areaResult - })) + Column() { + if (this.node1.nodeType === NodeType.TEXT_NODE) { + if (this.node1.parentNode) { + if ((this.node1.parentNode as TaroElement).tagName === 'BUTTON') { + Text(this.node1.textContent) + .attributeModifier(textModify.setNode(this.node1?.parentElement as TaroElement, { + fontSize: getButtonFontSize(this.node1.parentNode as TaroButtonElement), + color: getButtonColor(this.node1.parentNode as TaroButtonElement, BUTTON_THEME_COLOR.get((this.node1.parentNode as TaroButtonElement)._attrs.type || '').text) + })) + } else { + Text(this.node1.textContent) + .attributeModifier(textModify.setNode(this.node1?.parentElement as TaroElement)) + .width(getTextInViewWidth(this.node1.parentElement)) + } + } + } else { + Text(this.node1.textContent) { + // text 下还有标签 + if (this.node1.childNodes.length > 1 || ((this.node1.childNodes[0] && this.node1.childNodes[0] as TaroElement)?.nodeType === NodeType.ELEMENT_NODE)) { + ForEach(this.node1.childNodes, (item: TaroElement) => { + createTextChildNode(item, getSpanVerticalAlign((this.node1 as TaroElement).hmStyle?.verticalAlign)) + }, (item: TaroElement) => item._nid) + } + } + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', this.node1 as TaroElement), this.node1 as TaroElement, ['click'])) + .attributeModifier(textModify.setNode(this.node1 as TaroElement).withNormalStyle()) + .onVisibleAreaChange(getNodeThresholds((this.node1 as TaroElement)) || [0.0, 1.0], getComponentEventCallback((this.node1 as TaroElement), VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback((this.node1 as TaroElement), AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node1 as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } } - .attrs(getNormalAttributes(this.node0)) - .onVisibleAreaChange(getNodeThresholds(this.node0) || [0.0, 1.0], getComponentEventCallback(this.node0, VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node0, AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node0._nid].areaInfo = areaResult + .attributeModifier(columnModify.setNode(this.node0 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node0 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node0 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node0 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0 as TaroElement)._nodeInfo.areaInfo = res[1] })) } } -export default TARO_TEMPLATES_f0t1 -` +`; function Index() { return + + + {myText} + - + + ; } diff --git a/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/entry.rs/should_support_single_compile_mode.js b/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/entry.rs/should_support_single_compile_mode.js index a17219333158..ec979d7c07d8 100644 --- a/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/entry.rs/should_support_single_compile_mode.js +++ b/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/entry.rs/should_support_single_compile_mode.js @@ -1,86 +1,67 @@ -const TARO_TEMPLATES_f0t0 = `import { FlexManager } from './utils/FlexManager' -import { getNodeThresholds, getNormalAttributes, getTextAttributes } from './utils/helper' -import { TaroIgnoreElement, eventHandler, DynamicCenter, getComponentEventCallback, AREA_CHANGE_EVENT_NAME, VISIBLE_CHANGE_EVENT_NAME } from '../runtime' -import type { TaroElement } from '../runtime' -import { TOUCH_EVENT_MAP } from './utils/constant/event' -@Extend(Flex) -function attrs ({ - flexBasis, - flexGrow, - flexShrink, - alignSelf, - clip, - width, - height, - margin, - padding, - linearGradient, - zIndex, - borderStyle, - borderWidth, - borderColor, - borderRadius, - opacity, - backgroundColor, - backgroundImage, - backgroundRepeat, - backgroundImageSize, - constraintSize, - rotate, - scale, - translate, - transform -}) { - .flexGrow(flexGrow) - .flexShrink(flexShrink) - .flexBasis(flexBasis) - .alignSelf(alignSelf) - .width(width) - .height(height) - .constraintSize(constraintSize) - .margin(margin) - .padding(padding) - .linearGradient(linearGradient) - .zIndex(zIndex) - .borderStyle(borderStyle) - .borderWidth(borderWidth) - .borderColor(borderColor) - .borderRadius(borderRadius) - .opacity(opacity) - .backgroundColor(backgroundColor) - .backgroundImage(backgroundImage, backgroundRepeat) - .backgroundImageSize(backgroundImageSize) - .rotate(rotate) - .scale(scale) - .translate(translate) - .transform(transform) - .clip(clip) -} +const TARO_TEMPLATES_f0t0 = `import { + rowModify, + FlexManager, + columnModify, + DynamicCenter, + getButtonColor, + TOUCH_EVENT_MAP, + getFontAttributes, + commonStyleModify, + getNodeThresholds, + BUTTON_THEME_COLOR, + getStyleAttr, + getNormalAttributes, + shouldBindEvent, + textModify, + setNormalTextAttributeIntoInstance, + getImageMode +} from '@tarojs/components' +import { + NodeType, + convertNumber2VP, + TaroElement, + eventHandler, + getComponentEventCallback, + AREA_CHANGE_EVENT_NAME, + VISIBLE_CHANGE_EVENT_NAME +} from '@tarojs/runtime' +import { + createLazyChildren, + createChildItem +} from '../render' + +import type { + TaroTextElement, + HarmonyStyle, + TaroButtonElement, + TaroViewElement, + TaroAny, + TaroStyleType, + TaroTextStyleType +} from '@tarojs/runtime' +import { isString } from '@tarojs/shared' @Component -struct TARO_TEMPLATES_f0t0 { - nodeInfoMap: any = {} - dynamicCenter: DynamicCenter - @ObjectLink node: TaroElement +export default struct TARO_TEMPLATES_f0t0 { + node: TaroViewElement = new TaroElement('Ignore') + + dynamicCenter: DynamicCenter = new DynamicCenter() aboutToAppear () { - this.dynamicCenter = new DynamicCenter() this.dynamicCenter.bindComponentToNodeWithDFS(this.node, this) } - @State node0: TaroElement = new TaroIgnoreElement() + @State node0: TaroElement = new TaroElement('Ignore') build() { - Flex(FlexManager.flexOptions(this.node0)) {} - .attrs(getNormalAttributes(this.node0)) - .onVisibleAreaChange(getNodeThresholds(this.node0) || [0.0, 1.0], getComponentEventCallback(this.node0, VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node0, AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node0._nid].areaInfo = areaResult + Column() {} + .attributeModifier(columnModify.setNode(this.node0 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node0 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node0 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node0 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0 as TaroElement)._nodeInfo.areaInfo = res[1] })) } } -export default TARO_TEMPLATES_f0t0 -` +`; function Index() { - return + return ; } diff --git a/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/looping.rs/should_loop_with_arrow_function_with_blockstmt.js b/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/looping.rs/should_loop_with_arrow_function_with_blockstmt.js index 4dd3704cf651..2a681e9e6925 100644 --- a/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/looping.rs/should_loop_with_arrow_function_with_blockstmt.js +++ b/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/looping.rs/should_loop_with_arrow_function_with_blockstmt.js @@ -1,95 +1,243 @@ -const TARO_TEMPLATES_f0t0 = `import { FlexManager } from './utils/FlexManager' -import { getNodeThresholds, getNormalAttributes, getTextAttributes } from './utils/helper' -import { TaroIgnoreElement, eventHandler, DynamicCenter, getComponentEventCallback, AREA_CHANGE_EVENT_NAME, VISIBLE_CHANGE_EVENT_NAME } from '../runtime' -import type { TaroElement } from '../runtime' -import { TOUCH_EVENT_MAP } from './utils/constant/event' -@Extend(Flex) -function attrs ({ - flexBasis, - flexGrow, - flexShrink, - alignSelf, - clip, - width, - height, - margin, - padding, - linearGradient, - zIndex, - borderStyle, - borderWidth, - borderColor, - borderRadius, - opacity, - backgroundColor, - backgroundImage, - backgroundRepeat, - backgroundImageSize, - constraintSize, - rotate, - scale, - translate, - transform -}) { - .flexGrow(flexGrow) - .flexShrink(flexShrink) - .flexBasis(flexBasis) - .alignSelf(alignSelf) - .width(width) - .height(height) - .constraintSize(constraintSize) - .margin(margin) - .padding(padding) - .linearGradient(linearGradient) - .zIndex(zIndex) - .borderStyle(borderStyle) - .borderWidth(borderWidth) - .borderColor(borderColor) - .borderRadius(borderRadius) - .opacity(opacity) - .backgroundColor(backgroundColor) - .backgroundImage(backgroundImage, backgroundRepeat) - .backgroundImageSize(backgroundImageSize) - .rotate(rotate) - .scale(scale) - .translate(translate) - .transform(transform) - .clip(clip) +const TARO_TEMPLATES_f0t0 = `import { + rowModify, + FlexManager, + columnModify, + DynamicCenter, + getButtonColor, + TOUCH_EVENT_MAP, + getFontAttributes, + commonStyleModify, + getNodeThresholds, + BUTTON_THEME_COLOR, + getStyleAttr, + getNormalAttributes, + shouldBindEvent, + textModify, + setNormalTextAttributeIntoInstance, + getImageMode +} from '@tarojs/components' +import { + NodeType, + convertNumber2VP, + TaroElement, + eventHandler, + getComponentEventCallback, + AREA_CHANGE_EVENT_NAME, + VISIBLE_CHANGE_EVENT_NAME +} from '@tarojs/runtime' +import { + createLazyChildren, + createChildItem +} from '../render' + +import type { + TaroTextElement, + HarmonyStyle, + TaroButtonElement, + TaroViewElement, + TaroAny, + TaroStyleType, + TaroTextStyleType +} from '@tarojs/runtime' +import { isString } from '@tarojs/shared' +@Extend(Text) +function textNormalFontStyle (style: HarmonyStyle) { + .id(style.id) + .key(style.id) + .opacity(style.opacity) + .fontColor(style.color) + .fontSize(style.fontSize) + .fontWeight(style.fontWeight) + .fontStyle(style.fontStyle) + .fontFamily(style.fontFamily) + .lineHeight(style.lineHeight) + .decoration({ + type: style.textDecoration?.type, + color: style.color + }) +} + +@Extend(Text) +function textSpecialFontStyle(attr: TaroTextStyleType) { + .textAlign(attr.textAlign) + .textOverflow(attr.textOverflow) + .maxLines(attr.WebkitLineClamp) + .letterSpacing(attr.letterSpacing) +} + +function getButtonFontSize (node: TaroButtonElement) { + const isMini = node._attrs.size === 'mini' + + return isMini ? convertNumber2VP(26) : convertNumber2VP(36) +} + +@Builder +function createTextChildNode (item: TaroElement, align: ImageSpanAlignment) { + if (item.tagName === 'IMAGE') { + ImageSpan(item.getAttribute('src')) + .objectFit(getImageMode(item.getAttribute('mode'))) + .verticalAlign(align) + .width(item._st.hmStyle.width) + .height(item._st.hmStyle.height) + .margin({ + top: item._st.hmStyle.marginTop, + left: item._st.hmStyle.marginLeft, + right: item._st.hmStyle.marginRight, + bottom: item._st.hmStyle.marginBottom, + }) + .padding({ + top: item._st.hmStyle.paddingTop, + left: item._st.hmStyle.paddingLeft, + right: item._st.hmStyle.paddingRight, + bottom: item._st.hmStyle.paddingBottom, + }) + .textBackgroundStyle({ + color: item._st.hmStyle.backgroundColor, + radius: { + topLeft: item._st.hmStyle.borderTopLeftRadius, + topRight: item._st.hmStyle.borderTopRightRadius, + bottomLeft: item._st.hmStyle.borderBottomLeftRadius, + bottomRight: item._st.hmStyle.borderBottomRightRadius, + } + }) + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', item), item, ['click'])) + } else if (item.nodeType === NodeType.TEXT_NODE) { + Span(item.textContent) + } else if (item.tagName === 'TEXT') { + Span(item.textContent) + .attributeModifier((new SpanStyleModify()).setNode(item as TaroTextElement)) + .letterSpacing(item._st.hmStyle.letterSpacing) + .textBackgroundStyle({ + color: item._st.hmStyle.backgroundColor, + radius: { + topLeft: item._st.hmStyle.borderTopLeftRadius, + topRight: item._st.hmStyle.borderTopRightRadius, + bottomLeft: item._st.hmStyle.borderBottomLeftRadius, + bottomRight: item._st.hmStyle.borderBottomRightRadius, + } + }) + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', item), item, ['click'])) + } +} + +class SpanStyleModify implements AttributeModifier { + node: TaroTextElement | null = null + style: HarmonyStyle | null = null + overwriteStyle: Record = {} + withNormal = false + + setNode (node: TaroTextElement) { + this.node = node + this.style = getNormalAttributes(this.node) + return this + } + + applyNormalAttribute(instance: SpanAttribute): void { + if (this.node && this.style) { + setNormalTextAttributeIntoInstance(instance, this.style, this.node) + } + } +} + +function getSpanVerticalAlign (verticalAlign?: Alignment) { + switch (verticalAlign) { + case Alignment.Start: + case Alignment.TopStart: + case Alignment.Top: + case Alignment.TopEnd: { + return ImageSpanAlignment.TOP + } + case Alignment.End: + case Alignment.BottomStart: + case Alignment.Bottom: + case Alignment.BottomEnd: { + return ImageSpanAlignment.BOTTOM + } + case Alignment.Center: { + return ImageSpanAlignment.CENTER + } + } + return ImageSpanAlignment.BASELINE } + +function getTextInViewWidth (node: TaroElement | null): TaroAny { + if (node) { + const hmStyle = node.hmStyle || {} + const isFlexView = hmStyle.display === 'flex' + const width: TaroAny = getStyleAttr(node, 'width') + const isPercentWidth = isString(width) && width.includes('%') + + return isFlexView || isPercentWidth ? null : getStyleAttr(node, 'width') + } +} + @Component -struct TARO_TEMPLATES_f0t0 { - nodeInfoMap: any = {} - dynamicCenter: DynamicCenter - @ObjectLink node: TaroElement +export default struct TARO_TEMPLATES_f0t0 { + node: TaroViewElement = new TaroElement('Ignore') + + dynamicCenter: DynamicCenter = new DynamicCenter() aboutToAppear () { - this.dynamicCenter = new DynamicCenter() this.dynamicCenter.bindComponentToNodeWithDFS(this.node, this) } - @State node0: TaroElement = new TaroIgnoreElement() + @State node0: TaroElement = new TaroElement('Ignore') build() { - Flex(FlexManager.flexOptions(this.node0)) { - ForEach(this.node0.childNodes, item => { - createNode(item) - }, item => item._nid) + Column() { + ForEach(this.node0.childNodes, (item: TaroElement) => { + Column() { + if (item.childNodes[0].nodeType === NodeType.TEXT_NODE) { + if (item.childNodes[0].parentNode) { + if ((item.childNodes[0].parentNode as TaroElement).tagName === 'BUTTON') { + Text(item.childNodes[0].textContent) + .attributeModifier(textModify.setNode(item.childNodes[0]?.parentElement as TaroElement, { + fontSize: getButtonFontSize(item.childNodes[0].parentNode as TaroButtonElement), + color: getButtonColor(item.childNodes[0].parentNode as TaroButtonElement, BUTTON_THEME_COLOR.get((item.childNodes[0].parentNode as TaroButtonElement)._attrs.type || '').text) + })) + } else { + Text(item.childNodes[0].textContent) + .attributeModifier(textModify.setNode(item.childNodes[0]?.parentElement as TaroElement)) + .width(getTextInViewWidth(item.childNodes[0].parentElement)) + } + } + } else { + Text(item.childNodes[0].textContent) { + // text 下还有标签 + if (item.childNodes[0].childNodes.length > 1 || ((item.childNodes[0].childNodes[0] && item.childNodes[0].childNodes[0] as TaroElement)?.nodeType === NodeType.ELEMENT_NODE)) { + ForEach(item.childNodes[0].childNodes, (item: TaroElement) => { + createTextChildNode(item, getSpanVerticalAlign((item.childNodes[0] as TaroElement).hmStyle?.verticalAlign)) + }, (item: TaroElement) => item._nid) + } + } + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', item.childNodes[0] as TaroElement), item.childNodes[0] as TaroElement, ['click'])) + .attributeModifier(textModify.setNode(item.childNodes[0] as TaroElement).withNormalStyle()) + .onVisibleAreaChange(getNodeThresholds((item.childNodes[0] as TaroElement)) || [0.0, 1.0], getComponentEventCallback((item.childNodes[0] as TaroElement), VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback((item.childNodes[0] as TaroElement), AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (item.childNodes[0] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } + } + .attributeModifier(columnModify.setNode(item as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(item as TaroElement) || [0.0, 1.0], getComponentEventCallback(item as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(item as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (item as TaroElement)._nodeInfo.areaInfo = res[1] + })) + }, (item: TaroElement) => item._nid); } - .attrs(getNormalAttributes(this.node0)) - .onVisibleAreaChange(getNodeThresholds(this.node0) || [0.0, 1.0], getComponentEventCallback(this.node0, VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node0, AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node0._nid].areaInfo = areaResult + .attributeModifier(columnModify.setNode(this.node0 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node0 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node0 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node0 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0 as TaroElement)._nodeInfo.areaInfo = res[1] })) } } -export default TARO_TEMPLATES_f0t0 `; function Index() { return {list.map((item)=>{ - return {item}; + return {item}; })} ; diff --git a/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/looping.rs/should_loop_with_arrow_function_with_blockstmt_and_set_parent_dynamic_id.js b/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/looping.rs/should_loop_with_arrow_function_with_blockstmt_and_set_parent_dynamic_id.js index fc4a2224dec9..bdc8851a3979 100644 --- a/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/looping.rs/should_loop_with_arrow_function_with_blockstmt_and_set_parent_dynamic_id.js +++ b/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/looping.rs/should_loop_with_arrow_function_with_blockstmt_and_set_parent_dynamic_id.js @@ -1,105 +1,256 @@ -const TARO_TEMPLATES_f0t0 = `import { FlexManager } from './utils/FlexManager' -import { getNodeThresholds, getNormalAttributes, getTextAttributes } from './utils/helper' -import { TaroIgnoreElement, eventHandler, DynamicCenter, getComponentEventCallback, AREA_CHANGE_EVENT_NAME, VISIBLE_CHANGE_EVENT_NAME } from '../runtime' -import type { TaroElement } from '../runtime' -import { TOUCH_EVENT_MAP } from './utils/constant/event' -@Extend(Flex) -function attrs ({ - flexBasis, - flexGrow, - flexShrink, - alignSelf, - clip, - width, - height, - margin, - padding, - linearGradient, - zIndex, - borderStyle, - borderWidth, - borderColor, - borderRadius, - opacity, - backgroundColor, - backgroundImage, - backgroundRepeat, - backgroundImageSize, - constraintSize, - rotate, - scale, - translate, - transform -}) { - .flexGrow(flexGrow) - .flexShrink(flexShrink) - .flexBasis(flexBasis) - .alignSelf(alignSelf) - .width(width) - .height(height) - .constraintSize(constraintSize) - .margin(margin) - .padding(padding) - .linearGradient(linearGradient) - .zIndex(zIndex) - .borderStyle(borderStyle) - .borderWidth(borderWidth) - .borderColor(borderColor) - .borderRadius(borderRadius) - .opacity(opacity) - .backgroundColor(backgroundColor) - .backgroundImage(backgroundImage, backgroundRepeat) - .backgroundImageSize(backgroundImageSize) - .rotate(rotate) - .scale(scale) - .translate(translate) - .transform(transform) - .clip(clip) +const TARO_TEMPLATES_f0t0 = `import { + rowModify, + FlexManager, + columnModify, + DynamicCenter, + getButtonColor, + TOUCH_EVENT_MAP, + getFontAttributes, + commonStyleModify, + getNodeThresholds, + BUTTON_THEME_COLOR, + getStyleAttr, + getNormalAttributes, + shouldBindEvent, + textModify, + setNormalTextAttributeIntoInstance, + getImageMode +} from '@tarojs/components' +import { + NodeType, + convertNumber2VP, + TaroElement, + eventHandler, + getComponentEventCallback, + AREA_CHANGE_EVENT_NAME, + VISIBLE_CHANGE_EVENT_NAME +} from '@tarojs/runtime' +import { + createLazyChildren, + createChildItem +} from '../render' + +import type { + TaroTextElement, + HarmonyStyle, + TaroButtonElement, + TaroViewElement, + TaroAny, + TaroStyleType, + TaroTextStyleType +} from '@tarojs/runtime' +import { isString } from '@tarojs/shared' +@Extend(Text) +function textNormalFontStyle (style: HarmonyStyle) { + .id(style.id) + .key(style.id) + .opacity(style.opacity) + .fontColor(style.color) + .fontSize(style.fontSize) + .fontWeight(style.fontWeight) + .fontStyle(style.fontStyle) + .fontFamily(style.fontFamily) + .lineHeight(style.lineHeight) + .decoration({ + type: style.textDecoration?.type, + color: style.color + }) +} + +@Extend(Text) +function textSpecialFontStyle(attr: TaroTextStyleType) { + .textAlign(attr.textAlign) + .textOverflow(attr.textOverflow) + .maxLines(attr.WebkitLineClamp) + .letterSpacing(attr.letterSpacing) +} + +function getButtonFontSize (node: TaroButtonElement) { + const isMini = node._attrs.size === 'mini' + + return isMini ? convertNumber2VP(26) : convertNumber2VP(36) +} + +@Builder +function createTextChildNode (item: TaroElement, align: ImageSpanAlignment) { + if (item.tagName === 'IMAGE') { + ImageSpan(item.getAttribute('src')) + .objectFit(getImageMode(item.getAttribute('mode'))) + .verticalAlign(align) + .width(item._st.hmStyle.width) + .height(item._st.hmStyle.height) + .margin({ + top: item._st.hmStyle.marginTop, + left: item._st.hmStyle.marginLeft, + right: item._st.hmStyle.marginRight, + bottom: item._st.hmStyle.marginBottom, + }) + .padding({ + top: item._st.hmStyle.paddingTop, + left: item._st.hmStyle.paddingLeft, + right: item._st.hmStyle.paddingRight, + bottom: item._st.hmStyle.paddingBottom, + }) + .textBackgroundStyle({ + color: item._st.hmStyle.backgroundColor, + radius: { + topLeft: item._st.hmStyle.borderTopLeftRadius, + topRight: item._st.hmStyle.borderTopRightRadius, + bottomLeft: item._st.hmStyle.borderBottomLeftRadius, + bottomRight: item._st.hmStyle.borderBottomRightRadius, + } + }) + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', item), item, ['click'])) + } else if (item.nodeType === NodeType.TEXT_NODE) { + Span(item.textContent) + } else if (item.tagName === 'TEXT') { + Span(item.textContent) + .attributeModifier((new SpanStyleModify()).setNode(item as TaroTextElement)) + .letterSpacing(item._st.hmStyle.letterSpacing) + .textBackgroundStyle({ + color: item._st.hmStyle.backgroundColor, + radius: { + topLeft: item._st.hmStyle.borderTopLeftRadius, + topRight: item._st.hmStyle.borderTopRightRadius, + bottomLeft: item._st.hmStyle.borderBottomLeftRadius, + bottomRight: item._st.hmStyle.borderBottomRightRadius, + } + }) + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', item), item, ['click'])) + } +} + +class SpanStyleModify implements AttributeModifier { + node: TaroTextElement | null = null + style: HarmonyStyle | null = null + overwriteStyle: Record = {} + withNormal = false + + setNode (node: TaroTextElement) { + this.node = node + this.style = getNormalAttributes(this.node) + return this + } + + applyNormalAttribute(instance: SpanAttribute): void { + if (this.node && this.style) { + setNormalTextAttributeIntoInstance(instance, this.style, this.node) + } + } } + +function getSpanVerticalAlign (verticalAlign?: Alignment) { + switch (verticalAlign) { + case Alignment.Start: + case Alignment.TopStart: + case Alignment.Top: + case Alignment.TopEnd: { + return ImageSpanAlignment.TOP + } + case Alignment.End: + case Alignment.BottomStart: + case Alignment.Bottom: + case Alignment.BottomEnd: { + return ImageSpanAlignment.BOTTOM + } + case Alignment.Center: { + return ImageSpanAlignment.CENTER + } + } + return ImageSpanAlignment.BASELINE +} + +function getTextInViewWidth (node: TaroElement | null): TaroAny { + if (node) { + const hmStyle = node.hmStyle || {} + const isFlexView = hmStyle.display === 'flex' + const width: TaroAny = getStyleAttr(node, 'width') + const isPercentWidth = isString(width) && width.includes('%') + + return isFlexView || isPercentWidth ? null : getStyleAttr(node, 'width') + } +} + @Component -struct TARO_TEMPLATES_f0t0 { - nodeInfoMap: any = {} - dynamicCenter: DynamicCenter - @ObjectLink node: TaroElement +export default struct TARO_TEMPLATES_f0t0 { + node: TaroViewElement = new TaroElement('Ignore') + + dynamicCenter: DynamicCenter = new DynamicCenter() aboutToAppear () { - this.dynamicCenter = new DynamicCenter() this.dynamicCenter.bindComponentToNodeWithDFS(this.node, this) } - @State node0: TaroElement = new TaroIgnoreElement() - @State node1: TaroElement = new TaroIgnoreElement() + @State node0: TaroElement = new TaroElement('Ignore') + @State node1: TaroElement = new TaroElement('Ignore') build() { - Flex(FlexManager.flexOptions(this.node0)) { - Flex(FlexManager.flexOptions(this.node1)) { - ForEach(this.node1.childNodes, item => { - createNode(item) - }, item => item._nid) + Column() { + Column() { + ForEach(this.node1.childNodes, (item: TaroElement) => { + Column() { + if (item.childNodes[0].nodeType === NodeType.TEXT_NODE) { + if (item.childNodes[0].parentNode) { + if ((item.childNodes[0].parentNode as TaroElement).tagName === 'BUTTON') { + Text(item.childNodes[0].textContent) + .attributeModifier(textModify.setNode(item.childNodes[0]?.parentElement as TaroElement, { + fontSize: getButtonFontSize(item.childNodes[0].parentNode as TaroButtonElement), + color: getButtonColor(item.childNodes[0].parentNode as TaroButtonElement, BUTTON_THEME_COLOR.get((item.childNodes[0].parentNode as TaroButtonElement)._attrs.type || '').text) + })) + } else { + Text(item.childNodes[0].textContent) + .attributeModifier(textModify.setNode(item.childNodes[0]?.parentElement as TaroElement)) + .width(getTextInViewWidth(item.childNodes[0].parentElement)) + } + } + } else { + Text(item.childNodes[0].textContent) { + // text 下还有标签 + if (item.childNodes[0].childNodes.length > 1 || ((item.childNodes[0].childNodes[0] && item.childNodes[0].childNodes[0] as TaroElement)?.nodeType === NodeType.ELEMENT_NODE)) { + ForEach(item.childNodes[0].childNodes, (item: TaroElement) => { + createTextChildNode(item, getSpanVerticalAlign((item.childNodes[0] as TaroElement).hmStyle?.verticalAlign)) + }, (item: TaroElement) => item._nid) + } + } + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', item.childNodes[0] as TaroElement), item.childNodes[0] as TaroElement, ['click'])) + .attributeModifier(textModify.setNode(item.childNodes[0] as TaroElement).withNormalStyle()) + .onVisibleAreaChange(getNodeThresholds((item.childNodes[0] as TaroElement)) || [0.0, 1.0], getComponentEventCallback((item.childNodes[0] as TaroElement), VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback((item.childNodes[0] as TaroElement), AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (item.childNodes[0] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } + } + .attributeModifier(columnModify.setNode(item as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(item as TaroElement) || [0.0, 1.0], getComponentEventCallback(item as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(item as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (item as TaroElement)._nodeInfo.areaInfo = res[1] + })) + }, (item: TaroElement) => item._nid); } - .attrs(getNormalAttributes(this.node1)) - .onVisibleAreaChange(getNodeThresholds(this.node1) || [0.0, 1.0], getComponentEventCallback(this.node1, VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node1, AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node1._nid].areaInfo = areaResult + .attributeModifier(columnModify.setNode(this.node1 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node1 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node1 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node1 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node1 as TaroElement)._nodeInfo.areaInfo = res[1] })) } - .attrs(getNormalAttributes(this.node0)) - .onVisibleAreaChange(getNodeThresholds(this.node0) || [0.0, 1.0], getComponentEventCallback(this.node0, VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node0, AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node0._nid].areaInfo = areaResult + .attributeModifier(columnModify.setNode(this.node0 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node0 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node0 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node0 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0 as TaroElement)._nodeInfo.areaInfo = res[1] })) } } -export default TARO_TEMPLATES_f0t0 `; function Index() { return + + {list.map((item)=>{ - return {item}; + return {item}; })} + + ; } diff --git a/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/looping.rs/should_loop_with_function_expr.js b/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/looping.rs/should_loop_with_function_expr.js index c81d692bba46..80a62c7b7e08 100644 --- a/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/looping.rs/should_loop_with_function_expr.js +++ b/crates/swc_plugin_compile_mode/tests/__swc_snapshots__/src/tests/harmony/looping.rs/should_loop_with_function_expr.js @@ -1,99 +1,344 @@ -const TARO_TEMPLATES_f0t0 = `import { FlexManager } from './utils/FlexManager' -import { getNodeThresholds, getNormalAttributes, getTextAttributes } from './utils/helper' -import { TaroIgnoreElement, eventHandler, DynamicCenter, getComponentEventCallback, AREA_CHANGE_EVENT_NAME, VISIBLE_CHANGE_EVENT_NAME } from '../runtime' -import type { TaroElement } from '../runtime' -import { TOUCH_EVENT_MAP } from './utils/constant/event' -@Extend(Flex) -function attrs ({ - flexBasis, - flexGrow, - flexShrink, - alignSelf, - clip, - width, - height, - margin, - padding, - linearGradient, - zIndex, - borderStyle, - borderWidth, - borderColor, - borderRadius, - opacity, - backgroundColor, - backgroundImage, - backgroundRepeat, - backgroundImageSize, - constraintSize, - rotate, - scale, - translate, - transform -}) { - .flexGrow(flexGrow) - .flexShrink(flexShrink) - .flexBasis(flexBasis) - .alignSelf(alignSelf) - .width(width) - .height(height) - .constraintSize(constraintSize) - .margin(margin) - .padding(padding) - .linearGradient(linearGradient) - .zIndex(zIndex) - .borderStyle(borderStyle) - .borderWidth(borderWidth) - .borderColor(borderColor) - .borderRadius(borderRadius) - .opacity(opacity) - .backgroundColor(backgroundColor) - .backgroundImage(backgroundImage, backgroundRepeat) - .backgroundImageSize(backgroundImageSize) - .rotate(rotate) - .scale(scale) - .translate(translate) - .transform(transform) - .clip(clip) +const TARO_TEMPLATES_f0t0 = `import { + rowModify, + FlexManager, + columnModify, + DynamicCenter, + getButtonColor, + TOUCH_EVENT_MAP, + getFontAttributes, + commonStyleModify, + getNodeThresholds, + BUTTON_THEME_COLOR, + getStyleAttr, + getNormalAttributes, + shouldBindEvent, + textModify, + setNormalTextAttributeIntoInstance, + getImageMode +} from '@tarojs/components' +import { + NodeType, + convertNumber2VP, + TaroElement, + eventHandler, + getComponentEventCallback, + AREA_CHANGE_EVENT_NAME, + VISIBLE_CHANGE_EVENT_NAME +} from '@tarojs/runtime' +import { + createLazyChildren, + createChildItem +} from '../render' + +import type { + TaroTextElement, + HarmonyStyle, + TaroButtonElement, + TaroViewElement, + TaroAny, + TaroStyleType, + TaroTextStyleType +} from '@tarojs/runtime' +import { isString } from '@tarojs/shared' +@Extend(Text) +function textNormalFontStyle (style: HarmonyStyle) { + .id(style.id) + .key(style.id) + .opacity(style.opacity) + .fontColor(style.color) + .fontSize(style.fontSize) + .fontWeight(style.fontWeight) + .fontStyle(style.fontStyle) + .fontFamily(style.fontFamily) + .lineHeight(style.lineHeight) + .decoration({ + type: style.textDecoration?.type, + color: style.color + }) +} + +@Extend(Text) +function textSpecialFontStyle(attr: TaroTextStyleType) { + .textAlign(attr.textAlign) + .textOverflow(attr.textOverflow) + .maxLines(attr.WebkitLineClamp) + .letterSpacing(attr.letterSpacing) +} + +function getButtonFontSize (node: TaroButtonElement) { + const isMini = node._attrs.size === 'mini' + + return isMini ? convertNumber2VP(26) : convertNumber2VP(36) +} + +@Builder +function createTextChildNode (item: TaroElement, align: ImageSpanAlignment) { + if (item.tagName === 'IMAGE') { + ImageSpan(item.getAttribute('src')) + .objectFit(getImageMode(item.getAttribute('mode'))) + .verticalAlign(align) + .width(item._st.hmStyle.width) + .height(item._st.hmStyle.height) + .margin({ + top: item._st.hmStyle.marginTop, + left: item._st.hmStyle.marginLeft, + right: item._st.hmStyle.marginRight, + bottom: item._st.hmStyle.marginBottom, + }) + .padding({ + top: item._st.hmStyle.paddingTop, + left: item._st.hmStyle.paddingLeft, + right: item._st.hmStyle.paddingRight, + bottom: item._st.hmStyle.paddingBottom, + }) + .textBackgroundStyle({ + color: item._st.hmStyle.backgroundColor, + radius: { + topLeft: item._st.hmStyle.borderTopLeftRadius, + topRight: item._st.hmStyle.borderTopRightRadius, + bottomLeft: item._st.hmStyle.borderBottomLeftRadius, + bottomRight: item._st.hmStyle.borderBottomRightRadius, + } + }) + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', item), item, ['click'])) + } else if (item.nodeType === NodeType.TEXT_NODE) { + Span(item.textContent) + } else if (item.tagName === 'TEXT') { + Span(item.textContent) + .attributeModifier((new SpanStyleModify()).setNode(item as TaroTextElement)) + .letterSpacing(item._st.hmStyle.letterSpacing) + .textBackgroundStyle({ + color: item._st.hmStyle.backgroundColor, + radius: { + topLeft: item._st.hmStyle.borderTopLeftRadius, + topRight: item._st.hmStyle.borderTopRightRadius, + bottomLeft: item._st.hmStyle.borderBottomLeftRadius, + bottomRight: item._st.hmStyle.borderBottomRightRadius, + } + }) + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', item), item, ['click'])) + } } + +class SpanStyleModify implements AttributeModifier { + node: TaroTextElement | null = null + style: HarmonyStyle | null = null + overwriteStyle: Record = {} + withNormal = false + + setNode (node: TaroTextElement) { + this.node = node + this.style = getNormalAttributes(this.node) + return this + } + + applyNormalAttribute(instance: SpanAttribute): void { + if (this.node && this.style) { + setNormalTextAttributeIntoInstance(instance, this.style, this.node) + } + } +} + +function getSpanVerticalAlign (verticalAlign?: Alignment) { + switch (verticalAlign) { + case Alignment.Start: + case Alignment.TopStart: + case Alignment.Top: + case Alignment.TopEnd: { + return ImageSpanAlignment.TOP + } + case Alignment.End: + case Alignment.BottomStart: + case Alignment.Bottom: + case Alignment.BottomEnd: { + return ImageSpanAlignment.BOTTOM + } + case Alignment.Center: { + return ImageSpanAlignment.CENTER + } + } + return ImageSpanAlignment.BASELINE +} + +function getTextInViewWidth (node: TaroElement | null): TaroAny { + if (node) { + const hmStyle = node.hmStyle || {} + const isFlexView = hmStyle.display === 'flex' + const width: TaroAny = getStyleAttr(node, 'width') + const isPercentWidth = isString(width) && width.includes('%') + + return isFlexView || isPercentWidth ? null : getStyleAttr(node, 'width') + } +} + @Component -struct TARO_TEMPLATES_f0t0 { - nodeInfoMap: any = {} - dynamicCenter: DynamicCenter - @ObjectLink node: TaroElement +export default struct TARO_TEMPLATES_f0t0 { + node: TaroViewElement = new TaroElement('Ignore') + + dynamicCenter: DynamicCenter = new DynamicCenter() aboutToAppear () { - this.dynamicCenter = new DynamicCenter() this.dynamicCenter.bindComponentToNodeWithDFS(this.node, this) } - @State node0: TaroElement = new TaroIgnoreElement() + @State node0: TaroElement = new TaroElement('Ignore') build() { - Flex(FlexManager.flexOptions(this.node0)) { - ForEach(this.node0.childNodes, item => { - createNode(item) - }, item => item._nid) + Column() { + ForEach(this.node0.childNodes, (item: TaroElement) => { + Column() { + if (item.childNodes[0].nodeType === NodeType.TEXT_NODE) { + if (item.childNodes[0].parentNode) { + if ((item.childNodes[0].parentNode as TaroElement).tagName === 'BUTTON') { + Text(item.childNodes[0].textContent) + .attributeModifier(textModify.setNode(item.childNodes[0]?.parentElement as TaroElement, { + fontSize: getButtonFontSize(item.childNodes[0].parentNode as TaroButtonElement), + color: getButtonColor(item.childNodes[0].parentNode as TaroButtonElement, BUTTON_THEME_COLOR.get((item.childNodes[0].parentNode as TaroButtonElement)._attrs.type || '').text) + })) + } else { + Text(item.childNodes[0].textContent) + .attributeModifier(textModify.setNode(item.childNodes[0]?.parentElement as TaroElement)) + .width(getTextInViewWidth(item.childNodes[0].parentElement)) + } + } + } else { + Text(item.childNodes[0].textContent) { + // text 下还有标签 + if (item.childNodes[0].childNodes.length > 1 || ((item.childNodes[0].childNodes[0] && item.childNodes[0].childNodes[0] as TaroElement)?.nodeType === NodeType.ELEMENT_NODE)) { + ForEach(item.childNodes[0].childNodes, (item: TaroElement) => { + createTextChildNode(item, getSpanVerticalAlign((item.childNodes[0] as TaroElement).hmStyle?.verticalAlign)) + }, (item: TaroElement) => item._nid) + } + } + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', item.childNodes[0] as TaroElement), item.childNodes[0] as TaroElement, ['click'])) + .attributeModifier(textModify.setNode(item.childNodes[0] as TaroElement).withNormalStyle()) + .onVisibleAreaChange(getNodeThresholds((item.childNodes[0] as TaroElement)) || [0.0, 1.0], getComponentEventCallback((item.childNodes[0] as TaroElement), VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback((item.childNodes[0] as TaroElement), AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (item.childNodes[0] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } + if (item.childNodes[1].nodeType === NodeType.TEXT_NODE) { + if (item.childNodes[1].parentNode) { + if ((item.childNodes[1].parentNode as TaroElement).tagName === 'BUTTON') { + Text(item.childNodes[1].textContent) + .attributeModifier(textModify.setNode(item.childNodes[1]?.parentElement as TaroElement, { + fontSize: getButtonFontSize(item.childNodes[1].parentNode as TaroButtonElement), + color: getButtonColor(item.childNodes[1].parentNode as TaroButtonElement, BUTTON_THEME_COLOR.get((item.childNodes[1].parentNode as TaroButtonElement)._attrs.type || '').text) + })) + } else { + Text(item.childNodes[1].textContent) + .attributeModifier(textModify.setNode(item.childNodes[1]?.parentElement as TaroElement)) + .width(getTextInViewWidth(item.childNodes[1].parentElement)) + } + } + } else { + Text(item.childNodes[1].textContent) { + // text 下还有标签 + if (item.childNodes[1].childNodes.length > 1 || ((item.childNodes[1].childNodes[0] && item.childNodes[1].childNodes[0] as TaroElement)?.nodeType === NodeType.ELEMENT_NODE)) { + ForEach(item.childNodes[1].childNodes, (item: TaroElement) => { + createTextChildNode(item, getSpanVerticalAlign((item.childNodes[1] as TaroElement).hmStyle?.verticalAlign)) + }, (item: TaroElement) => item._nid) + } + } + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', item.childNodes[1] as TaroElement), item.childNodes[1] as TaroElement, ['click'])) + .attributeModifier(textModify.setNode(item.childNodes[1] as TaroElement).withNormalStyle()) + .onVisibleAreaChange(getNodeThresholds((item.childNodes[1] as TaroElement)) || [0.0, 1.0], getComponentEventCallback((item.childNodes[1] as TaroElement), VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback((item.childNodes[1] as TaroElement), AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (item.childNodes[1] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } + if (item.childNodes[2].nodeType === NodeType.TEXT_NODE) { + if (item.childNodes[2].parentNode) { + if ((item.childNodes[2].parentNode as TaroElement).tagName === 'BUTTON') { + Text(item.childNodes[2].textContent) + .attributeModifier(textModify.setNode(item.childNodes[2]?.parentElement as TaroElement, { + fontSize: getButtonFontSize(item.childNodes[2].parentNode as TaroButtonElement), + color: getButtonColor(item.childNodes[2].parentNode as TaroButtonElement, BUTTON_THEME_COLOR.get((item.childNodes[2].parentNode as TaroButtonElement)._attrs.type || '').text) + })) + } else { + Text(item.childNodes[2].textContent) + .attributeModifier(textModify.setNode(item.childNodes[2]?.parentElement as TaroElement)) + .width(getTextInViewWidth(item.childNodes[2].parentElement)) + } + } + } else { + Text(item.childNodes[2].textContent) { + // text 下还有标签 + if (item.childNodes[2].childNodes.length > 1 || ((item.childNodes[2].childNodes[0] && item.childNodes[2].childNodes[0] as TaroElement)?.nodeType === NodeType.ELEMENT_NODE)) { + ForEach(item.childNodes[2].childNodes, (item: TaroElement) => { + createTextChildNode(item, getSpanVerticalAlign((item.childNodes[2] as TaroElement).hmStyle?.verticalAlign)) + }, (item: TaroElement) => item._nid) + } + } + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', item.childNodes[2] as TaroElement), item.childNodes[2] as TaroElement, ['click'])) + .attributeModifier(textModify.setNode(item.childNodes[2] as TaroElement).withNormalStyle()) + .onVisibleAreaChange(getNodeThresholds((item.childNodes[2] as TaroElement)) || [0.0, 1.0], getComponentEventCallback((item.childNodes[2] as TaroElement), VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback((item.childNodes[2] as TaroElement), AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (item.childNodes[2] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } + if (item.childNodes[3].nodeType === NodeType.TEXT_NODE) { + if (item.childNodes[3].parentNode) { + if ((item.childNodes[3].parentNode as TaroElement).tagName === 'BUTTON') { + Text(item.childNodes[3].textContent) + .attributeModifier(textModify.setNode(item.childNodes[3]?.parentElement as TaroElement, { + fontSize: getButtonFontSize(item.childNodes[3].parentNode as TaroButtonElement), + color: getButtonColor(item.childNodes[3].parentNode as TaroButtonElement, BUTTON_THEME_COLOR.get((item.childNodes[3].parentNode as TaroButtonElement)._attrs.type || '').text) + })) + } else { + Text(item.childNodes[3].textContent) + .attributeModifier(textModify.setNode(item.childNodes[3]?.parentElement as TaroElement)) + .width(getTextInViewWidth(item.childNodes[3].parentElement)) + } + } + } else { + Text(item.childNodes[3].textContent) { + // text 下还有标签 + if (item.childNodes[3].childNodes.length > 1 || ((item.childNodes[3].childNodes[0] && item.childNodes[3].childNodes[0] as TaroElement)?.nodeType === NodeType.ELEMENT_NODE)) { + ForEach(item.childNodes[3].childNodes, (item: TaroElement) => { + createTextChildNode(item, getSpanVerticalAlign((item.childNodes[3] as TaroElement).hmStyle?.verticalAlign)) + }, (item: TaroElement) => item._nid) + } + } + .onClick(shouldBindEvent((e: ClickEvent) => eventHandler(e, 'click', item.childNodes[3] as TaroElement), item.childNodes[3] as TaroElement, ['click'])) + .attributeModifier(textModify.setNode(item.childNodes[3] as TaroElement).withNormalStyle()) + .onVisibleAreaChange(getNodeThresholds((item.childNodes[3] as TaroElement)) || [0.0, 1.0], getComponentEventCallback((item.childNodes[3] as TaroElement), VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback((item.childNodes[3] as TaroElement), AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (item.childNodes[3] as TaroElement)._nodeInfo.areaInfo = res[1] + })) + } + } + .attributeModifier(columnModify.setNode(item as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(item as TaroElement) || [0.0, 1.0], getComponentEventCallback(item as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(item as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (item as TaroElement)._nodeInfo.areaInfo = res[1] + })) + }, (item: TaroElement) => item._nid); } - .attrs(getNormalAttributes(this.node0)) - .onVisibleAreaChange(getNodeThresholds(this.node0) || [0.0, 1.0], getComponentEventCallback(this.node0, VISIBLE_CHANGE_EVENT_NAME)) - .onAreaChange(getComponentEventCallback(this.node0, AREA_CHANGE_EVENT_NAME, ({ eventResult }) => { - const [_, areaResult] = eventResult - this.nodeInfoMap[this.node0._nid].areaInfo = areaResult + .attributeModifier(columnModify.setNode(this.node0 as TaroElement)) + .onVisibleAreaChange(getNodeThresholds(this.node0 as TaroElement) || [0.0, 1.0], getComponentEventCallback(this.node0 as TaroElement, VISIBLE_CHANGE_EVENT_NAME)) + .onAreaChange(getComponentEventCallback(this.node0 as TaroElement, AREA_CHANGE_EVENT_NAME, (res: TaroAny) => { + (this.node0 as TaroElement)._nodeInfo.areaInfo = res[1] })) } } -export default TARO_TEMPLATES_f0t0 -` +`; function Index() { return + {list.map(function(item, index) { - return + return + index: + {index} + item: + {item} - + + ; })} - + + ; } diff --git a/crates/taro_init/src/constants.rs b/crates/taro_init/src/constants.rs index 64e945566477..6f827261b927 100644 --- a/crates/taro_init/src/constants.rs +++ b/crates/taro_init/src/constants.rs @@ -68,7 +68,7 @@ pub static PACKAGES_MANAGEMENT: Lazy> = Lazy:: }); pub static MEDIA_REGEX: Lazy = - Lazy::new(|| regex::Regex::new(r"\.(png|jpe?g|gif|svg|webp|jar|keystore)$").unwrap()); + Lazy::new(|| regex::Regex::new(r"\.(png|jpe?g|gif|svg|webp|jar|keystore|tgz)$").unwrap()); pub static TEMPLATE_CREATOR: &str = "template_creator.js"; diff --git a/crates/taro_init/src/creator.rs b/crates/taro_init/src/creator.rs index 89356f7c0b49..9072201fa432 100644 --- a/crates/taro_init/src/creator.rs +++ b/crates/taro_init/src/creator.rs @@ -34,6 +34,9 @@ pub struct CreateOptions { pub page_name: Option, pub compiler: Option, pub set_page_name: Option, + pub sub_pkg: Option, + pub page_dir: Option, + pub set_sub_pkg_page_name: Option, pub change_ext: Option, pub is_custom_template: Option, pub plugin_type: Option, @@ -43,6 +46,7 @@ pub struct CreateOptions { pub struct JSReturnObject { pub set_page_name: Option, pub change_ext: Option, + pub set_sub_pkg_page_name: Option, } impl FromNapiValue for JSReturnObject { @@ -51,12 +55,17 @@ impl FromNapiValue for JSReturnObject { let mut js_return_object = JSReturnObject { set_page_name: None, change_ext: None, + set_sub_pkg_page_name: None, }; let has_set_page_name = obj.has_named_property("setPageName")?; let has_change_ext = obj.has_named_property("changeExt")?; + let has_set_sub_pkg_page_name = obj.has_named_property("setSubPkgName")?; if has_set_page_name { js_return_object.set_page_name = Some(obj.get_named_property::("setPageName")?); } + if has_set_sub_pkg_page_name { + js_return_object.set_sub_pkg_page_name = Some(obj.get_named_property::("setSubPkgName")?); + } if has_change_ext { js_return_object.change_ext = Some(obj.get_named_property::("changeExt")?); } @@ -226,8 +235,17 @@ impl Creator { JSReturn::Object(obj) => { let set_page_name = obj.set_page_name; let change_ext_re = obj.change_ext; - if let Some(set_page_name) = set_page_name { - page_name = set_page_name; + let set_sub_pkg_page_name = obj.set_sub_pkg_page_name; + let sub_pkg = &options.sub_pkg; + if sub_pkg.is_some() { + // 创建分包页面模式 + if let Some(set_sub_pkg_page_name) = set_sub_pkg_page_name { + page_name = set_sub_pkg_page_name; + } + } else { + if let Some(set_page_name) = set_page_name { + page_name = set_page_name; + } } if let Some(change_ext_re) = change_ext_re { change_ext = change_ext_re; diff --git a/crates/taro_init/src/page.rs b/crates/taro_init/src/page.rs index caab73d0126d..49897e507ae7 100644 --- a/crates/taro_init/src/page.rs +++ b/crates/taro_init/src/page.rs @@ -29,6 +29,8 @@ pub struct Page { pub custom_template_path: Option, pub base_page_files: Vec, pub period: PeriodType, + pub sub_pkg: Option, + pub page_dir: Option, } impl Page { @@ -49,6 +51,8 @@ impl Page { custom_template_path: Option, base_page_files: Vec, period: PeriodType, + sub_pkg: Option, + page_dir: Option, ) -> Self { Page { project_dir, @@ -67,6 +71,8 @@ impl Page { custom_template_path, base_page_files, period, + sub_pkg, + page_dir, } } @@ -101,8 +107,11 @@ impl Page { typescript: self.typescript.clone(), template: self.template.clone(), page_name: Some(self.page_name.clone()), + sub_pkg: self.sub_pkg.clone(), + page_dir: self.page_dir.clone(), compiler: self.compiler.clone(), set_page_name: None, + set_sub_pkg_page_name: None, change_ext: None, is_custom_template: self.is_custom_template.clone(), plugin_type: None, diff --git a/crates/taro_init/src/plugin.rs b/crates/taro_init/src/plugin.rs index 8a04d1f5cf1b..e9210999c500 100644 --- a/crates/taro_init/src/plugin.rs +++ b/crates/taro_init/src/plugin.rs @@ -63,6 +63,9 @@ impl Plugin { change_ext: None, is_custom_template: None, plugin_type: Some(self.plugin_type.clone()), + sub_pkg: None, + page_dir: None, + set_sub_pkg_page_name: None, }; let all_files = all_files.iter().map(|f| f.as_str()).collect::>(); println!(); diff --git a/crates/taro_init/src/project.rs b/crates/taro_init/src/project.rs index b7c5f11e2225..4c71c019b246 100644 --- a/crates/taro_init/src/project.rs +++ b/crates/taro_init/src/project.rs @@ -107,6 +107,9 @@ impl Project { page_name: Some("index".to_string()), compiler: self.compiler.clone(), set_page_name: None, + set_sub_pkg_page_name: None, + sub_pkg: None, + page_dir: None, change_ext: None, is_custom_template: None, plugin_type: None, diff --git a/examples/custom-tabbar-vue3/package.json b/examples/custom-tabbar-vue3/package.json index 6d752cc51594..3362fe1e1d9a 100644 --- a/examples/custom-tabbar-vue3/package.json +++ b/examples/custom-tabbar-vue3/package.json @@ -40,7 +40,7 @@ "@tarojs/components": "3.4.3", "@tarojs/plugin-framework-vue3": "3.4.3", "vuex": "^4.0.0-beta.4", - "vue": "^3.0.0" + "vue": "3.2.47" }, "devDependencies": { "@types/webpack-env": "^1.13.6", @@ -48,7 +48,7 @@ "@tarojs/webpack-runner": "3.4.3", "@babel/core": "^7.8.0", "babel-preset-taro": "3.4.3", - "@vue/compiler-sfc": "^3.0.0", + "@vue/compiler-sfc": "3.2.47", "vue-loader": "^16.0.0-beta.8", "eslint-plugin-vue": "^7.0.0", "eslint-config-taro": "3.4.3", diff --git a/examples/new-blended/miniapp/project.config.json b/examples/new-blended/miniapp/project.config.json index 775f1a0d6783..e68102fb2ac9 100644 --- a/examples/new-blended/miniapp/project.config.json +++ b/examples/new-blended/miniapp/project.config.json @@ -49,4 +49,4 @@ "include": [] }, "appid": "wxa9abf43f10a7bdb0" -} \ No newline at end of file +} diff --git a/examples/new-blended/miniapp/project.private.config.json b/examples/new-blended/miniapp/project.private.config.json index 5fba65235c00..0f43df783847 100644 --- a/examples/new-blended/miniapp/project.private.config.json +++ b/examples/new-blended/miniapp/project.private.config.json @@ -17,4 +17,4 @@ ] } } -} \ No newline at end of file +} diff --git a/npm/darwin-arm64/package.json b/npm/darwin-arm64/package.json index b50470acaec4..4bc27ea4cfc7 100644 --- a/npm/darwin-arm64/package.json +++ b/npm/darwin-arm64/package.json @@ -1,7 +1,7 @@ { "name": "@tarojs/binding-darwin-arm64", "description": "Native binding for taro", - "version": "3.6.23", + "version": "4.0.0-beta.58", "os": [ "darwin" ], @@ -14,7 +14,7 @@ ], "license": "MIT", "engines": { - "node": ">= 10" + "node": ">= 18" }, "publishConfig": { "access": "public" diff --git a/npm/darwin-x64/package.json b/npm/darwin-x64/package.json index deb97daeb412..9df21a6578b5 100644 --- a/npm/darwin-x64/package.json +++ b/npm/darwin-x64/package.json @@ -1,7 +1,7 @@ { "name": "@tarojs/binding-darwin-x64", "description": "Native binding for taro", - "version": "3.6.23", + "version": "4.0.0-beta.58", "os": [ "darwin" ], @@ -14,7 +14,7 @@ ], "license": "MIT", "engines": { - "node": ">= 10" + "node": ">= 18" }, "publishConfig": { "access": "public" diff --git a/npm/linux-x64-gnu/package.json b/npm/linux-x64-gnu/package.json index 3be48772ec26..9a3354b80b51 100644 --- a/npm/linux-x64-gnu/package.json +++ b/npm/linux-x64-gnu/package.json @@ -1,7 +1,7 @@ { "name": "@tarojs/binding-linux-x64-gnu", "description": "Native binding for taro", - "version": "3.6.23", + "version": "4.0.0-beta.58", "os": [ "linux" ], @@ -14,7 +14,7 @@ ], "license": "MIT", "engines": { - "node": ">= 10" + "node": ">= 18" }, "libc": [ "glibc" diff --git a/npm/win32-x64-msvc/package.json b/npm/win32-x64-msvc/package.json index a83f3354fa63..3c1771e1bc45 100644 --- a/npm/win32-x64-msvc/package.json +++ b/npm/win32-x64-msvc/package.json @@ -1,7 +1,7 @@ { "name": "@tarojs/binding-win32-x64-msvc", "description": "Native binding for taro", - "version": "3.6.23", + "version": "4.0.0-beta.58", "os": [ "win32" ], @@ -14,7 +14,7 @@ ], "license": "MIT", "engines": { - "node": ">= 10" + "node": ">= 18" }, "publishConfig": { "access": "public" diff --git a/package.json b/package.json index ed6a90f4aaab..7a56aa48ce9d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "taro", - "version": "3.6.23", + "version": "4.0.0-beta.58", "description": "开放式跨端跨框架开发解决方案", "homepage": "https://github.com/NervJS/taro#readme", "author": "O2Team", @@ -21,7 +21,7 @@ "scripts": { "preinstall": "npx only-allow pnpm", "prepare": "husky install", - "build": "pnpm -r --aggregate-output --filter=./packages/* build", + "build": "pnpm -r --filter=./packages/* build", "build:binding:debug": "pnpm --filter @tarojs/binding run build:debug", "build:binding:release": "pnpm --filter @tarojs/binding run build", "format::rs": "cargo fmt --all", @@ -58,10 +58,11 @@ "@babel/plugin-transform-react-jsx": "^7.14.5", "@babel/plugin-transform-runtime": "^7.14.5", "@babel/preset-env": "^7.14.5", - "@babel/preset-react": "^7.14.5", + "@babel/preset-react": "^7.22.15", "@babel/preset-typescript": "^7.14.5", "@babel/runtime": "^7.14.5", "@babel/traverse": "^7.14.5", + "@babel/types": "^7.14.5", "@commitlint/cli": "^17.6.6", "@commitlint/config-conventional": "^17.6.6", "@tarojs/components": "workspace:*", @@ -72,12 +73,12 @@ "@tarojs/plugin-framework-vue3": "workspace:*", "@tarojs/plugin-platform-alipay": "workspace:*", "@tarojs/plugin-platform-h5": "workspace:*", + "@tarojs/plugin-platform-harmony-hybrid": "workspace:*", "@tarojs/plugin-platform-jd": "workspace:*", "@tarojs/plugin-platform-qq": "workspace:*", "@tarojs/plugin-platform-swan": "workspace:*", "@tarojs/plugin-platform-tt": "workspace:*", "@tarojs/plugin-platform-weapp": "workspace:*", - "@tarojs/plugin-platform-harmony-hybrid": "workspace:*", "@tarojs/router": "workspace:*", "@tarojs/runner-utils": "workspace:*", "@tarojs/runtime": "workspace:*", @@ -100,9 +101,11 @@ "@types/less": "^3.0.2", "@types/lodash": "^4.14.142", "@types/lodash-es": "^4.17.6", - "@types/node": "^14.14.31", + "@types/node": "^18.19.12", "@types/postcss-import": "^14.0.0", + "@types/postcss-url": "^10.0.0", "@types/react": "^18.0.0", + "@types/react-dom": "^18.0.0", "@types/react-reconciler": "0.28.1", "@types/request": "^2.48.1", "@types/resolve": "^1.20.6", @@ -119,6 +122,7 @@ "core-js": "^3.6.5", "cpy-cli": "^4.1.0", "cross-env": "^7.0.2", + "escodegen": "^2.0.0", "eslint": "^8.12.0", "eslint-config-prettier": "^6.4.0", "eslint-config-standard": "^14.1.1", @@ -128,7 +132,7 @@ "eslint-plugin-node": "^10.0.0", "eslint-plugin-prettier": "^4.2.1", "eslint-plugin-promise": "^6.1.1", - "eslint-plugin-react": "^7.4.0", + "eslint-plugin-react": "^7.33.2", "eslint-plugin-simple-import-sort": "^7.0.0", "eslint-plugin-standard": "^4.0.1", "husky": "^8.0.1", @@ -136,6 +140,7 @@ "jest-cli": "^27.4.5", "jest-environment-node": "^27.4.4", "lint-staged": "^13.0.2", + "mkdirp": "^3.0.1", "nervjs": "^1.4.6", "npm-run-all": "^4.1.2", "postcss": "^8.4.18", @@ -148,6 +153,7 @@ "react-dom": "^18.2.0", "react-test-renderer": "^18.2.0", "rimraf": "^5.0.0", + "rollup": "^3.8.1", "stylelint": "^14.6.1", "stylelint-config-standard-scss": "^3.0.0", "stylelint-config-taro-rn": "workspace:*", @@ -155,9 +161,9 @@ "stylelint-taro-rn": "workspace:*", "tslib": "^2.6.2", "typescript": "^4.7.4", - "vue": "^2.6.11", + "vue": "~2.6.11", "vue-loader": "^17.0.0", - "vue-template-compiler": "^2.6.11", + "vue-template-compiler": "~2.6.11", "webpack": "5.78.0", "webpack-chain": "6.5.1", "webpack-dev-server": "4.11.1", @@ -174,7 +180,7 @@ }, "react-native-root-siblings": { "peerDependencies": { - "react": "18.1.0" + "react": "18.2.0" }, "peerDependenciesMeta": { "react": { @@ -182,6 +188,9 @@ } } } + }, + "overrides": { + "browserslist": "^4.23.0" } } } diff --git a/packages/babel-plugin-transform-react-jsx-to-rn-stylesheet/package.json b/packages/babel-plugin-transform-react-jsx-to-rn-stylesheet/package.json index 415c24fe909b..db518e66b1fb 100644 --- a/packages/babel-plugin-transform-react-jsx-to-rn-stylesheet/package.json +++ b/packages/babel-plugin-transform-react-jsx-to-rn-stylesheet/package.json @@ -1,6 +1,6 @@ { "name": "babel-plugin-transform-react-jsx-to-rn-stylesheet", - "version": "3.6.23", + "version": "4.0.0-beta.58", "description": "Transform stylesheet selector to style in JSX Elements.", "license": "MIT", "main": "dist/index.js", @@ -19,8 +19,8 @@ }, "homepage": "https://github.com/NervJS/taro#readme", "engines": { - "node": ">=12.0.0", - "npm": ">=6.0.0" + "node": ">= 18", + "npm": ">= 6" }, "dependencies": { "camelize": "^1.0.0", @@ -28,7 +28,7 @@ }, "devDependencies": { "@babel/core": "^7.14.5", - "babel-jest": "^29.5.0", + "babel-jest": "^29.7.0", "jest": "^29.3.1", "jest-cli": "^29.3.1", "ts-jest": "^29.0.5", diff --git a/packages/babel-plugin-transform-react-jsx-to-rn-stylesheet/src/index.ts b/packages/babel-plugin-transform-react-jsx-to-rn-stylesheet/src/index.ts index 7205f4adb9b3..13de9c997dac 100644 --- a/packages/babel-plugin-transform-react-jsx-to-rn-stylesheet/src/index.ts +++ b/packages/babel-plugin-transform-react-jsx-to-rn-stylesheet/src/index.ts @@ -140,11 +140,10 @@ export default function (babel: { const getModuleClassNameFunctionStmt = template(getModuleClassNameFunction)() - function getMap (str) { return str.split(/\s+/).map((className) => { // return template(`${STYLE_SHEET_NAME}["${className}"]`)().expression - const stmt = template(`${STYLE_SHEET_NAME}["${className}"]`)() + const stmt = template(`${STYLE_SHEET_NAME}["${className}"]`)() as Types.Node if (t.isExpressionStatement(stmt)) { return stmt.expression } diff --git a/packages/babel-plugin-transform-taroapi/babel.config.json b/packages/babel-plugin-transform-taroapi/babel.config.json index 52bbf45dfe07..6117dbb1e9d8 100644 --- a/packages/babel-plugin-transform-taroapi/babel.config.json +++ b/packages/babel-plugin-transform-taroapi/babel.config.json @@ -4,8 +4,7 @@ "@babel/preset-env", { "targets": { - "ios": "9", - "android": "4.4" + "node": "current" } } ] diff --git a/packages/babel-plugin-transform-taroapi/package.json b/packages/babel-plugin-transform-taroapi/package.json index 8e43a759783a..a27521e46efd 100644 --- a/packages/babel-plugin-transform-taroapi/package.json +++ b/packages/babel-plugin-transform-taroapi/package.json @@ -1,6 +1,6 @@ { "name": "babel-plugin-transform-taroapi", - "version": "3.6.23", + "version": "4.0.0-beta.58", "main": "dist/index.js", "scripts": { "build": "tsc", @@ -16,7 +16,7 @@ "devDependencies": { "@babel/core": "^7.14.5", "@babel/types": "^7.14.5", - "babel-jest": "^29.5.0", + "babel-jest": "^29.7.0", "jest": "^29.3.1", "jest-cli": "^29.3.1", "ts-jest": "^29.0.5", diff --git a/packages/babel-plugin-transform-taroapi/src/index.ts b/packages/babel-plugin-transform-taroapi/src/index.ts index c0c9a848db70..f43e91fb737a 100644 --- a/packages/babel-plugin-transform-taroapi/src/index.ts +++ b/packages/babel-plugin-transform-taroapi/src/index.ts @@ -60,7 +60,7 @@ const plugin = function (babel: typeof BabelCore): BabelCore.PluginObj { this.apis = apis }, visitor: { - ImportDeclaration (ast) { + ImportDeclaration (ast: BabelCore.NodePath) { if (ast.node.source.value !== this.packageName) return ast.node.specifiers.forEach(node => { @@ -91,7 +91,7 @@ const plugin = function (babel: typeof BabelCore): BabelCore.PluginObj { } }) }, - MemberExpression (ast) { + MemberExpression (ast: BabelCore.NodePath) { /* 处理Taro.xxx */ const isTaro = t.isIdentifier(ast.node.object, { name: taroName }) const property = ast.node.property @@ -110,7 +110,7 @@ const plugin = function (babel: typeof BabelCore): BabelCore.PluginObj { // 同一api使用多次, 读取变量名 if (this.apis.has(propertyName)) { - const parentNode = ast.parent + const parentNode = ast.parent as BabelCore.types.AssignmentExpression const isAssignment = t.isAssignmentExpression(parentNode) && parentNode.left === ast.node if (!isAssignment) { @@ -129,7 +129,7 @@ const plugin = function (babel: typeof BabelCore): BabelCore.PluginObj { needDefault = true } }, - CallExpression (ast) { + CallExpression (ast: BabelCore.NodePath) { if (!ast.scope.hasReference(this.canIUse)) return const callee = ast.node.callee if (t.isMemberExpression(callee) && t.isIdentifier(callee.object, { name: taroName })) { @@ -188,7 +188,7 @@ const plugin = function (babel: typeof BabelCore): BabelCore.PluginObj { ast.node.specifiers = namedImports } }, - CallExpression (ast) { + CallExpression (ast: BabelCore.NodePath) { if (!invokedApis.has(that.canIUse)) return const callee = ast.node.callee const { name } = t.identifier(invokedApis.get(that.canIUse)!) diff --git a/packages/babel-preset-taro/index.js b/packages/babel-preset-taro/index.js index df04463e4bd8..2bd3f05b6be0 100644 --- a/packages/babel-preset-taro/index.js +++ b/packages/babel-preset-taro/index.js @@ -28,10 +28,13 @@ module.exports = (_, options = {}) => { const presets = [] const plugins = [] const overrides = [] - const isReact = options.framework === 'react' || options.framework === 'preact' - const isNerv = options.framework === 'nerv' - const isVue = options.framework === 'vue' - const isVue3 = options.framework === 'vue3' + const isVite = options.compiler === 'vite' + const isReact = options.framework === 'react' || options.framework === 'preact' && !isVite + const isSolid = options.framework === 'solid' + const isNerv = options.framework === 'nerv' && !isVite + const isVue = options.framework === 'vue' && !isVite + const isVue3 = options.framework === 'vue3' && !isVite + const isTs = options.ts && !isVite const moduleName = options.framework.charAt(0).toUpperCase() + options.framework.slice(1) const presetReactConfig = options.react || {} @@ -58,6 +61,11 @@ module.exports = (_, options = {}) => { }) } } + } else if (isSolid) { + presets.push([require('babel-preset-solid'), { + moduleName: '@tarojs/plugin-framework-react/dist/reconciler', + generate: 'universal', + }]) } if (isVue || isVue3) { @@ -71,7 +79,7 @@ module.exports = (_, options = {}) => { } } - if (options.ts) { + if (isTs) { const config = typeof options.ts === 'object' ? options.ts : {} if (isNerv || isReact) { config.jsxPragma = moduleName diff --git a/packages/babel-preset-taro/package.json b/packages/babel-preset-taro/package.json index 44102d8a440c..b19060681e46 100644 --- a/packages/babel-preset-taro/package.json +++ b/packages/babel-preset-taro/package.json @@ -1,6 +1,6 @@ { "name": "babel-preset-taro", - "version": "3.6.23", + "version": "4.0.0-beta.58", "description": "Taro babel preset", "author": "yuche ", "homepage": "https://github.com/nervjs/taro/tree/master/packages/babel-preset-taro#readme", @@ -28,17 +28,17 @@ "@babel/plugin-syntax-jsx": "^7.14.5", "@babel/plugin-transform-runtime": "^7.14.5", "@babel/preset-env": "^7.14.5", - "@babel/preset-react": "^7.14.5", + "@babel/preset-react": "^7.22.15", "@babel/preset-typescript": "^7.14.5", "@babel/runtime": "^7.14.5", "@babel/runtime-corejs3": "^7.14.5", + "@react-native/babel-preset": "^0.73.18", "@tarojs/helper": "workspace:*", "babel-plugin-dynamic-import-node": "2.3.3", "babel-plugin-minify-dead-code-elimination": "^0.5.2", "babel-plugin-transform-imports-api": "1.0.0", + "babel-preset-solid": "^1.8.15", "core-js": "^3.6.5", - "lodash": "^4.17.21", - "metro-react-native-babel-preset": "^0.72.1", "react-refresh": "^0.11.0" }, "devDependencies": { diff --git a/packages/babel-preset-taro/rn/index.js b/packages/babel-preset-taro/rn/index.js index 42ef78216ed3..9af3c068abf6 100644 --- a/packages/babel-preset-taro/rn/index.js +++ b/packages/babel-preset-taro/rn/index.js @@ -1,6 +1,9 @@ -const reactNativeBabelPreset = require('metro-react-native-babel-preset') +const reactNativeBabelPreset = require('@react-native/babel-preset') module.exports = (_, options = {}) => { + if (!process.env.NODE_ENV) { + process.env.NODE_ENV = 'development' + } const { decoratorsBeforeExport, decoratorsLegacy diff --git a/packages/create-app/package.json b/packages/create-app/package.json index 235c8bfdfc7d..67648743ca0b 100644 --- a/packages/create-app/package.json +++ b/packages/create-app/package.json @@ -1,6 +1,6 @@ { "name": "@tarojs/create-app", - "version": "3.6.23", + "version": "4.0.0-beta.58", "description": "create taro app with one command", "author": "VincentW ", "homepage": "https://github.com/nervjs/taro/tree/master/packages/create-app#readme", @@ -10,7 +10,7 @@ "dev": "tsc -w", "prod": "tsc", "build": "run-s clean prod", - "clean": "rimraf dist" + "clean": "rimraf --impl=move-remove dist" }, "files": [ "dist" @@ -27,7 +27,7 @@ "cli" ], "engines": { - "node": ">=12" + "node": ">= 18" }, "dependencies": { "@tarojs/cli": "workspace:*", diff --git a/packages/create-app/src/createApp.ts b/packages/create-app/src/createApp.ts old mode 100755 new mode 100644 diff --git a/packages/create-app/src/index.ts b/packages/create-app/src/index.ts old mode 100755 new mode 100644 diff --git a/packages/css-to-react-native/package.json b/packages/css-to-react-native/package.json index 75f1b4b777c5..7cb8ee7b6a0d 100644 --- a/packages/css-to-react-native/package.json +++ b/packages/css-to-react-native/package.json @@ -1,7 +1,7 @@ { "name": "taro-css-to-react-native", "description": "Convert CSS text to a React Native stylesheet object", - "version": "3.6.23", + "version": "4.0.0-beta.58", "main": "dist/index.js", "license": "MIT", "files": [ @@ -56,7 +56,7 @@ }, "devDependencies": { "@babel/core": "^7.14.5", - "babel-jest": "^29.5.0", + "babel-jest": "^29.7.0", "jest": "^29.3.1", "jest-cli": "^29.3.1" } diff --git a/packages/eslint-config-taro/package.json b/packages/eslint-config-taro/package.json index 7681d36a987d..34a7b0203876 100644 --- a/packages/eslint-config-taro/package.json +++ b/packages/eslint-config-taro/package.json @@ -1,6 +1,6 @@ { "name": "eslint-config-taro", - "version": "3.6.23", + "version": "4.0.0-beta.58", "description": "Taro specific linting rules for ESLint", "main": "index.js", "files": [ @@ -32,9 +32,9 @@ "@typescript-eslint/eslint-plugin": "^5.17.0", "eslint": "^8.12.0", "eslint-plugin-import": "^2.26.0", - "eslint-plugin-react": "^7.4.0", + "eslint-plugin-react": "^7.33.2", "eslint-plugin-react-hooks": "^4.4.0", - "eslint-plugin-vue": "^8.6.0", + "eslint-plugin-vue": "^9.17.0", "typescript": "^4.7.4" }, "peerDependencies": { diff --git a/packages/jest-helper/package.json b/packages/jest-helper/package.json new file mode 100644 index 000000000000..461a121fb09d --- /dev/null +++ b/packages/jest-helper/package.json @@ -0,0 +1,24 @@ +{ + "name": "jest-taro-helper", + "version": "4.0.0-beta.58", + "description": "jest helper for taro", + "private": true, + "main": "index.js", + "files": [ + "lib" + ], + "scripts": { + "build": "tsc", + "dev": "tsc -w" + }, + "keywords": [], + "author": "", + "license": "ISC", + "devDependencies": { + "@jest/test-sequencer": "^29.5.0", + "jest-resolve": "^29.5.0", + "jest-runner": "^29.5.0", + "pretty-format": "^29.5.0", + "typescript": "^4.7.4" + } +} diff --git a/packages/jest-helper/src/resolver.ts b/packages/jest-helper/src/resolver.ts new file mode 100644 index 000000000000..571ab332e5d9 --- /dev/null +++ b/packages/jest-helper/src/resolver.ts @@ -0,0 +1,14 @@ +import type { ResolverOptions } from 'jest-resolve' + +export = (path: string, options: ResolverOptions) => { + return options.defaultResolver(path, { + ...options, + packageFilter: (pkg) => { + const field = ['module', 'main'].find((e) => pkg[e] && typeof pkg[e] === 'string') + if (field) { + pkg.main = pkg[field] || pkg.main + } + return pkg + }, + }) +} diff --git a/packages/jest-helper/src/sequencer.ts b/packages/jest-helper/src/sequencer.ts new file mode 100644 index 000000000000..cddc40cb46b2 --- /dev/null +++ b/packages/jest-helper/src/sequencer.ts @@ -0,0 +1,10 @@ +import type { Test } from 'jest-runner' + +const Sequencer = require('@jest/test-sequencer').default + +export default class CustomSequencer extends Sequencer { + sort (tests: Test[]) { + const copyTests = Array.from(tests) + return copyTests.sort((testA, testB) => testA.path.localeCompare(testB.path)) + } +} diff --git a/packages/jest-helper/src/snapshot/resolver.ts b/packages/jest-helper/src/snapshot/resolver.ts new file mode 100644 index 000000000000..1834b04ac40f --- /dev/null +++ b/packages/jest-helper/src/snapshot/resolver.ts @@ -0,0 +1,20 @@ +import * as path from 'path' + +const TEST_DIR = '__tests__' +const SNAPSHOT_DIR = '__snapshots__' + +export const resolveSnapshotPath = (testPath: string, snapshotExtension: string) => { + return testPath.replace(TEST_DIR, SNAPSHOT_DIR) + snapshotExtension +} + +export const resolveTestPath = (snapshotPath: string, snapshotExtension: string) => { + return snapshotPath.replace(snapshotExtension, '').replace(SNAPSHOT_DIR, TEST_DIR) +} + +export const testPathForConsistencyCheck = path.posix.join('consistency_check', TEST_DIR, 'example.test.js') + +export default { + resolveSnapshotPath, + resolveTestPath, + testPathForConsistencyCheck, +} diff --git a/packages/jest-helper/src/snapshot/serializers.ts b/packages/jest-helper/src/snapshot/serializers.ts new file mode 100644 index 000000000000..190ed1973aa2 --- /dev/null +++ b/packages/jest-helper/src/snapshot/serializers.ts @@ -0,0 +1,58 @@ +import * as os from 'os' +// import type { Config, Refs, Printer } from 'pretty-format' + +export const print = (val: string) => { + // Note: 对齐各平台的路径分隔符 + return val.replace(/\\*\*\sfilePath:\s(.*)\s\*\*\//g, (replaceValue) => replaceValue.replace(/\\/g, '/')) +} + +const mockFilePath = '/** filePath:mockFilePath **/' +export const parseSnapshotByFilePath = (val: string) => { + const arr = val.split(new RegExp(os.EOL + '|\n')) + let key = mockFilePath + return arr.reduce((acc, cur) => { + if (cur.startsWith('/** filePath:')) { + key = cur.replace(/\\/g, '/') + acc[key] = '' + } else { + acc[key] ||= '' + if (acc[key] !== '') { + acc[key] += '\n' + } + acc[key] += cur + } + return acc + }, {}) +} + +export const snapshotObject2String = (val: Record) => { + const arr = Object.entries(val) + const hasMockFilePath = arr.some(([key]) => key === mockFilePath) && arr.length <= 1 + return `${hasMockFilePath ? '' : '"\n'}${arr + .sort(([key1], [key2]) => key1.localeCompare(key2)) + .filter(([key, value]) => (!!key && key !== mockFilePath) || (key === mockFilePath && !!value)) + .map(([key, value]) => `${key === mockFilePath ? '' : `${key}\n`}${value}`) + .join('\n')}${hasMockFilePath ? '' : '"'}` +} + +export const serialize = ( + val: any, + // config: Config, + // indentation: string, + // depth: number, + // refs: Refs, + // printer: Printer, +) => { + if (typeof val === 'string') { + return snapshotObject2String(parseSnapshotByFilePath(val)) + } + return val +} + +export const test = (val: unknown) => typeof val === 'string' + +export default { + // print, + serialize, + test, +} diff --git a/packages/jest-helper/tsconfig.json b/packages/jest-helper/tsconfig.json new file mode 100644 index 000000000000..90ec8083ddee --- /dev/null +++ b/packages/jest-helper/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../../tsconfig.root.json", + "compilerOptions": { + "baseUrl": ".", + "outDir": "lib", + "rootDir": "./src", + "module": "commonjs" + }, + "include": ["./src"], + "exclude": ["./src/__tests__"] +} diff --git a/packages/postcss-html-transform/package.json b/packages/postcss-html-transform/package.json index 37bd2ea853fe..de1ecc00fec0 100644 --- a/packages/postcss-html-transform/package.json +++ b/packages/postcss-html-transform/package.json @@ -1,6 +1,6 @@ { "name": "postcss-html-transform", - "version": "3.6.23", + "version": "4.0.0-beta.58", "description": "transform html tag name selector", "main": "index.js", "author": "drchan", diff --git a/packages/postcss-plugin-constparse/package.json b/packages/postcss-plugin-constparse/package.json index 92b43a468f79..fd381a872f2b 100644 --- a/packages/postcss-plugin-constparse/package.json +++ b/packages/postcss-plugin-constparse/package.json @@ -1,6 +1,6 @@ { "name": "postcss-plugin-constparse", - "version": "3.6.23", + "version": "4.0.0-beta.58", "description": "parse constants defined in config", "main": "index.js", "author": "Simba", diff --git a/packages/postcss-pxtransform/__tests__/index.test.js b/packages/postcss-pxtransform/__tests__/index.test.js index d025877ffaf5..2da7ac304296 100644 --- a/packages/postcss-pxtransform/__tests__/index.test.js +++ b/packages/postcss-pxtransform/__tests__/index.test.js @@ -865,6 +865,6 @@ describe('platform 为 harmony,适配', () => { } } const processed = postcss(px2rem(options)).process(rules).css - expect(processed).toBe('view { width: 100vp; }') + expect(processed).toBe('view { width: 100ch; }') }) }) diff --git a/packages/postcss-pxtransform/index.js b/packages/postcss-pxtransform/index.js index 150c69be556a..37785ccacb57 100644 --- a/packages/postcss-pxtransform/index.js +++ b/packages/postcss-pxtransform/index.js @@ -1,8 +1,8 @@ const pxRegex = require('./lib/pixel-unit-regex') -const PXRegex = require('./lib/pixel-upper-unit-regex') const filterPropList = require('./lib/filter-prop-list') const defaults = { + methods: ['platform', 'size'], rootValue: 16, unitPrecision: 5, selectorBlackList: [], @@ -36,32 +36,41 @@ const DEFAULT_WEAPP_OPTIONS = { const processed = Symbol('processed') - let targetUnit +const SPECIAL_PIXEL = ['Px', 'PX', 'pX'] +let unConvertTargetUnit +let platform + module.exports = (options = {}) => { options = Object.assign({}, DEFAULT_WEAPP_OPTIONS, options) - + const exclude = options.exclude const transUnits = ['px'] const baseFontSize = options.baseFontSize || (options.minRootSize >= 1 ? options.minRootSize : 20) const designWidth = (input) => typeof options.designWidth === 'function' ? options.designWidth(input) : options.designWidth + platform = options.platform switch (options.platform) { case 'h5': { targetUnit = options.targetUnit ?? 'rem' - if (targetUnit === 'vw') { - options.rootValue = (input) => { - return designWidth(input) / 100 - } - } else if (targetUnit === 'px') { - options.rootValue = (input) => (1 / options.deviceRatio[designWidth(input)]) * 2 - } else { - // rem - options.rootValue = (input) => { - return (baseFontSize / options.deviceRatio[designWidth(input)]) * 2 - } + switch (targetUnit) { + case 'vw': + case 'vmin': + options.rootValue = (input) => { + return designWidth(input) / 100 + } + break + case 'px': + options.rootValue = (input) => (1 / options.deviceRatio[designWidth(input)]) * 2 + break + default: + // rem + options.rootValue = (input) => { + return (baseFontSize / options.deviceRatio[designWidth(input)]) * 2 + } + break } transUnits.push('rpx') @@ -80,6 +89,8 @@ module.exports = (options = {}) => { case 'harmony': { options.rootValue = (input) => 1 / options.deviceRatio[designWidth(input)] targetUnit = 'px' + unConvertTargetUnit = 'ch' // harmony对于大小写的PX转换成其他单位,用于rust解析 + transUnits.push(...SPECIAL_PIXEL) break } default: { @@ -117,6 +128,10 @@ module.exports = (options = {}) => { /** 是否跳过当前文件不处理 */ let skip = false + + if (exclude && exclude?.(result.opts.from)) { + return null + } return { // 注意:钩子在节点变动时会重新执行,Once,OnceExit只执行一次,https://github.com/NervJS/taro/issues/13238 @@ -126,6 +141,8 @@ module.exports = (options = {}) => { return } + if (!opts.methods.includes('platform')) return + // delete code between comment in RN // 有死循环的问题 if (options.platform === 'rn') { @@ -183,47 +200,46 @@ module.exports = (options = {}) => { }, Declaration (decl) { if (skip) return + if (!opts.methods.includes('size')) return if (decl[processed]) return // 标记当前 node 已处理 decl[processed] = true - if (options.platform === 'harmony') { - if (decl.value.indexOf('PX') === -1) return - const value = decl.value.replace(PXRegex, function (m, _$1, $2) { - return m.replace($2, 'vp') - }) - decl.value = value - } else { - if (decl.value.indexOf('px') === -1) return + if (!/px/i.test(decl.value)) return - if (!satisfyPropList(decl.prop)) return + if (!satisfyPropList(decl.prop)) return - if (blacklistedSelector(opts.selectorBlackList, decl.parent.selector)) return - const value = decl.value.replace(pxRgx, pxReplace) - // if rem unit already exists, do not add or replace - if (declarationExists(decl.parent, decl.prop, value)) return - if (opts.replace) { - decl.value = value + const isBlacklisted = blacklistedSelector(opts.selectorBlackList, decl.parent.selector) + if (isBlacklisted && platform !== 'harmony') return + let value + if (isBlacklisted) { + // 如果是harmony平台,黑名单的样式单位做特殊处理 + if (platform === 'harmony') { + value = decl.value.replace(pxRgx, (m, $1) => $1 ? $1 + unConvertTargetUnit : m) } else { - decl.cloneAfter({ value: value }) + // 如果是其他平台,黑名单的样式单位不做处理 + return } + } else { + value = decl.value.replace(pxRgx, pxReplace) + } + // if rem unit already exists, do not add or replace + if (declarationExists(decl.parent, decl.prop, value)) return + if (opts.replace) { + decl.value = value + } else { + decl.cloneAfter({ value: value }) } }, AtRule: { media: (rule) => { if (skip) return - if (options.platform === 'harmony') { - if (rule.params.indexOf('PX') === -1) return - const value = rule.params.replace(PXRegex, function (m, _$1, $2) { - return m.replace($2, 'vp') - }) - rule.params = value - } else { - if (rule.params.indexOf('px') === -1) return - rule.params = rule.params.replace(pxRgx, pxReplace) - } + if (!opts.methods.includes('size')) return + + if (!/px/i.test(rule.params)) return + rule.params = rule.params.replace(pxRgx, pxReplace) }, }, } @@ -255,14 +271,28 @@ function convertLegacyOptions (options) { } function createPxReplace (rootValue, unitPrecision, minPixelValue, onePxTransform) { + const specialPxRgx = pxRegex(SPECIAL_PIXEL) return function (input) { return function (m, $1) { if (!$1) return m + + if (platform === 'harmony' && specialPxRgx.test(m)) { + // harmony对大小写的PX转换成其他单位,用于rust解析 + return $1 + unConvertTargetUnit + } + if (!onePxTransform && parseInt($1, 10) === 1) { + if (platform === 'harmony') { return $1 + unConvertTargetUnit } return m } const pixels = parseFloat($1) - if (pixels < minPixelValue) return m + if (pixels < minPixelValue) { + if (platform === 'harmony') { return $1 + unConvertTargetUnit } + return m + } + + // 转换工作,如果是harmony的话不转换 + if (platform === 'harmony') { return m } let val = pixels / rootValue(input, m, $1) if (unitPrecision >= 0 && unitPrecision <= 100) { val = toFixed(val, unitPrecision) diff --git a/packages/postcss-pxtransform/package.json b/packages/postcss-pxtransform/package.json index 755432238359..e4652f4d8caa 100644 --- a/packages/postcss-pxtransform/package.json +++ b/packages/postcss-pxtransform/package.json @@ -1,6 +1,6 @@ { "name": "postcss-pxtransform", - "version": "3.6.23", + "version": "4.0.0-beta.58", "description": "PostCSS plugin px 转小程序 rpx及h5 rem 单位", "main": "index.js", "keywords": [ diff --git a/packages/postcss-unit-transform/package.json b/packages/postcss-unit-transform/package.json index 84fc671d06e1..984fc55c6e79 100644 --- a/packages/postcss-unit-transform/package.json +++ b/packages/postcss-unit-transform/package.json @@ -1,6 +1,6 @@ { "name": "postcss-taro-unit-transform", - "version": "3.6.23", + "version": "4.0.0-beta.58", "description": "小程序单位转换", "main": "index.js", "scripts": { diff --git a/packages/rollup-plugin-copy/.gitignore b/packages/rollup-plugin-copy/.gitignore new file mode 100644 index 000000000000..a65b41774ad5 --- /dev/null +++ b/packages/rollup-plugin-copy/.gitignore @@ -0,0 +1 @@ +lib diff --git a/packages/rollup-plugin-copy/index.js b/packages/rollup-plugin-copy/index.js new file mode 100644 index 000000000000..c368c43314c0 --- /dev/null +++ b/packages/rollup-plugin-copy/index.js @@ -0,0 +1,3 @@ +module.exports = require('./lib/index.js').default + +module.exports.default = module.exports diff --git a/packages/rollup-plugin-copy/package.json b/packages/rollup-plugin-copy/package.json new file mode 100644 index 000000000000..6f2458c8e8bf --- /dev/null +++ b/packages/rollup-plugin-copy/package.json @@ -0,0 +1,22 @@ +{ + "name": "rollup-plugin-copy", + "version": "4.0.0-beta.58", + "description": "rollup-plugin-copy for taro", + "private": true, + "main": "index.js", + "files": [ + "lib" + ], + "scripts": { + "build": "tsc", + "dev": "tsc -w" + }, + "keywords": [], + "author": "", + "license": "ISC", + "devDependencies": { + "@tarojs/helper": "workspace:*", + "rollup": "^3.8.1", + "typescript": "^4.7.4" + } +} diff --git a/packages/rollup-plugin-copy/src/index.ts b/packages/rollup-plugin-copy/src/index.ts new file mode 100644 index 000000000000..fc338f66559e --- /dev/null +++ b/packages/rollup-plugin-copy/src/index.ts @@ -0,0 +1,63 @@ +import { fs } from '@tarojs/helper' +import path from 'path' + +const cwd = process.cwd() + +interface ITarget { + readonly src: string + readonly dest: string +} + +interface IOptions { + hook?: string + targets?: ITarget[] +} + +export default function handleRollupCopy ({ + targets = [], + hook = 'buildEnd' +}: IOptions) { + let isWatched = false + + return { + name: 'rollup-plugin:taro-copy', + async [hook] () { + if (isWatched) return + + for (const item of targets) { + try { + let src = item.src + let dest = item.dest + const { base, dir } = path.parse(src) + dest = !dir ? dest : path.join(dest, base) + + src = path.join(cwd, src) + dest = path.join(cwd, dest) + if (path.extname(src)) { + fs.ensureDirSync(path.dirname(dest)) + } else { + fs.ensureDirSync(dest) + } + + const stat = fs.statSync(src) + if (stat.isDirectory()) { + fs.copySync(src, dest, { recursive: true }) + fs.watch(src, { recursive: true }, (_event, filename) => { + if (!filename) return + fs.copyFileSync(path.join(src, filename), path.join(dest, filename)) + }) + } else if (stat.isFile()) { + fs.copyFileSync(src, dest) + fs.watchFile(src, () => { + fs.copyFileSync(path.join(src), dest) + }) + } + } catch (error) { + console.error(error) + } + } + + isWatched = true + } + } +} diff --git a/packages/rollup-plugin-copy/tsconfig.json b/packages/rollup-plugin-copy/tsconfig.json new file mode 100644 index 000000000000..e934ffe0043f --- /dev/null +++ b/packages/rollup-plugin-copy/tsconfig.json @@ -0,0 +1,12 @@ +{ + "extends": "../../tsconfig.root.json", + "compilerOptions": { + "baseUrl": ".", + "esModuleInterop": true, + "outDir": "lib", + "rootDir": "./src", + "module": "commonjs" + }, + "include": ["./src"], + "exclude": ["./src/__tests__"] +} diff --git a/packages/shared/package.json b/packages/shared/package.json index 1d1675fe9530..274a8945f3bf 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -1,6 +1,6 @@ { "name": "@tarojs/shared", - "version": "3.6.23", + "version": "4.0.0-beta.58", "description": "Taro utils internal use.", "author": "yuche ", "homepage": "https://github.com/nervjs/taro/tree/master/packages/shared#readme", diff --git a/packages/shared/src/runtime-hooks.ts b/packages/shared/src/runtime-hooks.ts index 89b317880a43..12d275f007fb 100644 --- a/packages/shared/src/runtime-hooks.ts +++ b/packages/shared/src/runtime-hooks.ts @@ -253,6 +253,8 @@ type ITaroHooks = { modifyAddEventListener: (element, sideEffect: boolean, getComponentsAlias: () => Record) => void /** 元素删除事件监听钩子 */ modifyRemoveEventListener: (element, sideEffect: boolean, getComponentsAlias: () => Record) => void + /** 鸿蒙用于监听 memory 等级的钩子 */ + getMemoryLevel: (level: { level: number }) => void } export const hooks = new TaroHooks({ @@ -353,4 +355,6 @@ export const hooks = new TaroHooks({ modifyAddEventListener: TaroHook(HOOK_TYPE.SINGLE), modifyRemoveEventListener: TaroHook(HOOK_TYPE.SINGLE), + + getMemoryLevel: TaroHook(HOOK_TYPE.SINGLE), }) diff --git a/packages/shared/src/template.ts b/packages/shared/src/template.ts index 03f3ad8152cc..835254194fa9 100644 --- a/packages/shared/src/template.ts +++ b/packages/shared/src/template.ts @@ -495,7 +495,7 @@ export class BaseTemplate { return '' } - public buildPageTemplate = (baseTempPath: string, _page: { content: Record, path: string }) => { + public buildPageTemplate = (baseTempPath: string, _page?: { content: Record, path: string }) => { const template = `