Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: deDuplicated BuiltinComponentsMap #1073

Merged

Conversation

chilingling
Copy link
Member

@chilingling chilingling commented Jan 25, 2025

English | 简体中文

PR

PR Checklist

Please check if your PR fulfills the following requirements:

  • The commit message follows our Commit Message Guidelines
  • Tests for the changes have been added (for bug fixes / features)
  • Docs have been added / updated (for bug fixes / features)
  • Built its own designer, fully self-validated

PR Type

What kind of change does this PR introduce?

  • Bugfix
  • Feature
  • Code style update (formatting, local variables)
  • Refactoring (no functional changes, no api changes)
  • Build related changes
  • CI related changes
  • Documentation content changes
  • Other... Please describe:

Background and solution

【问题描述】
页面中存在多个 CanvasCol、CanvasRow、CanvasRowColContainer 组件的时候,会重复生成多个相同的 import 语句。
image

【问题分析】
componentsMap 中包含多个内置组件(被导入了多次)。
比如:

[
  {
    componentName: 'CanvasRow',
    exportName: 'CanvasRow',
    package: '@opentiny/tiny-engine-builtin-component',
    version: '^2.0.0',
    destructuring: true
  },
  {
    componentName: 'CanvasRow',
    exportName: 'CanvasRow',
    package: '@opentiny/tiny-engine-builtin-component',
    version: '^2.0.0',
    destructuring: true
  }
]

然后页面中,包含多个 CanvasRow 组件。就会生成重复的:
import { CanvasRow, CanvasRow } from '@opentiny/tiny-engine-builtin-component'

【解决方案】
生成 import 语句时,需要进行查重。

What is the current behavior?

Issue Number: N/A

What is the new behavior?

Builtin 组件映射去重

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

Summary by CodeRabbit

  • New Features

    • Introduced a responsive grid layout component offering flexible row and column arrangements.
    • Updated the application's navigation with a reorganized route structure and additional pages.
  • Bug Fixes

    • Refined component management processes to prevent duplicate entries and improve overall reliability.
  • Chores

    • Upgraded key dependencies to specific versions, enhancing stability and consistency.

1. Builtin 组件映射去重
Copy link
Contributor

coderabbitai bot commented Jan 25, 2025

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

packages/vue-generator/src/plugins/parseSchemaPlugin.js

Oops! Something went wrong! :(

ESLint: 8.57.1

Error: Cannot read config file: /packages/vue-generator/.eslintrc.cjs
Error: Cannot find module '@rushstack/eslint-patch/modern-module-resolution'
Require stack:

  • /packages/vue-generator/.eslintrc.cjs
  • /node_modules/.pnpm/@eslint+eslintrc@2.1.4/node_modules/@eslint/eslintrc/dist/eslintrc.cjs
  • /node_modules/.pnpm/eslint@8.57.1/node_modules/eslint/lib/cli-engine/cli-engine.js
  • /node_modules/.pnpm/eslint@8.57.1/node_modules/eslint/lib/eslint/eslint.js
  • /node_modules/.pnpm/eslint@8.57.1/node_modules/eslint/lib/eslint/index.js
  • /node_modules/.pnpm/eslint@8.57.1/node_modules/eslint/lib/cli.js
  • /node_modules/.pnpm/eslint@8.57.1/node_modules/eslint/bin/eslint.js
    at Module._resolveFilename (node:internal/modules/cjs/loader:1248:15)
    at Module._load (node:internal/modules/cjs/loader:1074:27)
    at TracingChannel.traceSync (node:diagnostics_channel:315:14)
    at wrapModuleLoad (node:internal/modules/cjs/loader:217:24)
    at Module.require (node:internal/modules/cjs/loader:1339:12)
    at require (node:internal/modules/helpers:135:16)
    at Object. (/packages/vue-generator/.eslintrc.cjs:4:1)
    at Module._compile (node:internal/modules/cjs/loader:1546:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1691:10)
    at Module.load (node:internal/modules/cjs/loader:1317:32)
packages/vue-generator/src/utils/generateImportStatement.js

Oops! Something went wrong! :(

ESLint: 8.57.1

Error: Cannot read config file: /packages/vue-generator/.eslintrc.cjs
Error: Cannot find module '@rushstack/eslint-patch/modern-module-resolution'
Require stack:

  • /packages/vue-generator/.eslintrc.cjs
  • /node_modules/.pnpm/@eslint+eslintrc@2.1.4/node_modules/@eslint/eslintrc/dist/eslintrc.cjs
  • /node_modules/.pnpm/eslint@8.57.1/node_modules/eslint/lib/cli-engine/cli-engine.js
  • /node_modules/.pnpm/eslint@8.57.1/node_modules/eslint/lib/eslint/eslint.js
  • /node_modules/.pnpm/eslint@8.57.1/node_modules/eslint/lib/eslint/index.js
  • /node_modules/.pnpm/eslint@8.57.1/node_modules/eslint/lib/cli.js
  • /node_modules/.pnpm/eslint@8.57.1/node_modules/eslint/bin/eslint.js
    at Module._resolveFilename (node:internal/modules/cjs/loader:1248:15)
    at Module._load (node:internal/modules/cjs/loader:1074:27)
    at TracingChannel.traceSync (node:diagnostics_channel:315:14)
    at wrapModuleLoad (node:internal/modules/cjs/loader:217:24)
    at Module.require (node:internal/modules/cjs/loader:1339:12)
    at require (node:internal/modules/helpers:135:16)
    at Object. (/packages/vue-generator/.eslintrc.cjs:4:1)
    at Module._compile (node:internal/modules/cjs/loader:1546:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1691:10)
    at Module.load (node:internal/modules/cjs/loader:1317:32)
packages/vue-generator/test/testcases/generator/mockData.js

Oops! Something went wrong! :(

ESLint: 8.57.1

Error: Cannot read config file: /packages/vue-generator/.eslintrc.cjs
Error: Cannot find module '@rushstack/eslint-patch/modern-module-resolution'
Require stack:

  • /packages/vue-generator/.eslintrc.cjs
  • /node_modules/.pnpm/@eslint+eslintrc@2.1.4/node_modules/@eslint/eslintrc/dist/eslintrc.cjs
  • /node_modules/.pnpm/eslint@8.57.1/node_modules/eslint/lib/cli-engine/cli-engine.js
  • /node_modules/.pnpm/eslint@8.57.1/node_modules/eslint/lib/eslint/eslint.js
  • /node_modules/.pnpm/eslint@8.57.1/node_modules/eslint/lib/eslint/index.js
  • /node_modules/.pnpm/eslint@8.57.1/node_modules/eslint/lib/cli.js
  • /node_modules/.pnpm/eslint@8.57.1/node_modules/eslint/bin/eslint.js
    at Module._resolveFilename (node:internal/modules/cjs/loader:1248:15)
    at Module._load (node:internal/modules/cjs/loader:1074:27)
    at TracingChannel.traceSync (node:diagnostics_channel:315:14)
    at wrapModuleLoad (node:internal/modules/cjs/loader:217:24)
    at Module.require (node:internal/modules/cjs/loader:1339:12)
    at require (node:internal/modules/helpers:135:16)
    at Object. (/packages/vue-generator/.eslintrc.cjs:4:1)
    at Module._compile (node:internal/modules/cjs/loader:1546:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1691:10)
    at Module.load (node:internal/modules/cjs/loader:1317:32)

Walkthrough

The pull request introduces several improvements across the Vue generator. The parseSchema function now prevents duplicating built-in components by checking for existing entries before adding them. Additionally, dependency versions in a test package have been updated, and a new dependency added. The router configuration has been restructured with nested routes, and a new Vue component with a canvas grid layout is introduced alongside its corresponding schema. Furthermore, the import statement generator now uses a seen set to avoid duplicate entries.

Changes

File(s) Change Summary
packages/vue-generator/src/plugins/parseSchemaPlugin.js Updated parseSchema logic to iterate over BUILTIN_COMPONENTS_MAP and add components only if they don't already exist (by matching componentName and package).
packages/vue-generator/test/testcases/generator/expected/appdemo01/package.json Updated dependency versions for @opentiny/vue and @opentiny/vue-icon from "latest" to "0.1.16", and added a new dependency @opentiny/tiny-engine-builtin-component with version "^2.0.0".
packages/vue-generator/test/testcases/generator/expected/appdemo01/src/router/index.js Restructured Vue Router configuration by removing old standalone routes and nesting new named routes (demopage, createVm, testCanvasRowCol) under a root route (/).
packages/vue-generator/test/testcases/generator/expected/appdemo01/src/views/testCanvasRowCol.vue
packages/vue-generator/test/testcases/generator/mockData.js
Introduced a new Vue component (testCanvasRowCol.vue) with a canvas grid layout, and added a corresponding page schema featuring nested canvas components and a reactive state.
packages/vue-generator/src/utils/generateImportStatement.js Modified import statement generation by introducing a seen set in generateImportByPkgName to track and filter duplicate component names/aliases.

Sequence Diagram(s)

sequenceDiagram
    participant PS as parseSchema()
    participant CM as schema.componentsMap
    participant BCM as BUILTIN_COMPONENTS_MAP

    PS->>BCM: Iterate over each built-in component
    loop For each component in BCM
        PS->>CM: Check if component exists (match by name and package)
        alt Component not present
            PS->>CM: Add component to componentsMap
        else
            Note over PS,CM: Skip duplicate component
        end
    end
Loading
sequenceDiagram
    participant G as generateImportByPkgName()
    participant Seen as seen Set
    participant Imp as Import Statement Generator

    G->>Seen: Check if component/alias already processed
    alt Not in seen
        Seen->>Seen: Add component/alias
        G->>Imp: Generate and return import statement
    else Component already seen
        G->>Imp: Skip and return empty string
    end
Loading

Possibly related PRs

Suggested labels

ready_for_review

Suggested reviewers

  • hexqi
  • rhlin

Poem

Hop, hop! I'm a rabbit coding with glee,
Skipping duplicate steps as neat as can be.
My schema now shines with components so clear,
Routes and imports organized without fear.
In this code garden, my hops celebrate change,
With a twitch of my nose—this update is so strange!
🐇✨ Happy coding and carrot dreams!

Tip

🌐 Web search-backed reviews and chat
  • We have enabled web search-based reviews and chat for all users. This feature allows CodeRabbit to access the latest documentation and information on the web.
  • You can disable this feature by setting web_search: false in the knowledge_base settings.
  • Please share any feedback in the Discord discussion.
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions github-actions bot added bug Something isn't working refactor-main refactor/develop branch feature labels Jan 25, 2025
@chilingling chilingling marked this pull request as ready for review January 25, 2025 09:45
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
packages/vue-generator/src/plugins/parseSchemaPlugin.js (2)

18-27: Consider optimizing the deduplication logic.

While the deduplication logic correctly prevents duplicate components by checking both componentName and package, the current implementation using find() in a loop could be inefficient for large component maps.

Consider using a Map for better performance:

-      for (const builtInComp of BUILTIN_COMPONENTS_MAP) {
-        if (
-          !schema.componentsMap.find(
-            ({ componentName, package: packageName }) =>
-              componentName === builtInComp.componentName && packageName === builtInComp.package
-          )
-        ) {
-          schema.componentsMap.push(builtInComp)
-        }
-      }
+      const existingComps = new Map(
+        schema.componentsMap.map(comp => [
+          `${comp.componentName}:${comp.package}`,
+          true
+        ])
+      );
+      
+      for (const builtInComp of BUILTIN_COMPONENTS_MAP) {
+        const key = `${builtInComp.componentName}:${builtInComp.package}`;
+        if (!existingComps.has(key)) {
+          schema.componentsMap.push(builtInComp);
+          existingComps.set(key, true);
+        }
+      }

Line range hint 42-42: Consider documenting or adjusting the arbitrary depth limit.

The depth < 1000 check seems arbitrary. Consider either:

  1. Documenting why this specific limit was chosen, or
  2. Making it a named constant with documentation, or
  3. Implementing a more meaningful limit based on actual requirements
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5b9d61a and d685aef.

📒 Files selected for processing (6)
  • packages/vue-generator/src/generator/vue/sfc/genSetupSFC.js (1 hunks)
  • packages/vue-generator/src/plugins/parseSchemaPlugin.js (1 hunks)
  • packages/vue-generator/test/testcases/generator/expected/appdemo01/package.json (1 hunks)
  • packages/vue-generator/test/testcases/generator/expected/appdemo01/src/router/index.js (1 hunks)
  • packages/vue-generator/test/testcases/generator/expected/appdemo01/src/views/testCanvasRowCol.vue (1 hunks)
  • packages/vue-generator/test/testcases/generator/mockData.js (1 hunks)
👮 Files not reviewed due to content moderation or server errors (4)
  • packages/vue-generator/test/testcases/generator/expected/appdemo01/src/router/index.js
  • packages/vue-generator/test/testcases/generator/expected/appdemo01/src/views/testCanvasRowCol.vue
  • packages/vue-generator/src/generator/vue/sfc/genSetupSFC.js
  • packages/vue-generator/test/testcases/generator/mockData.js
🧰 Additional context used
🪛 Gitleaks (8.21.2)
packages/vue-generator/test/testcases/generator/mockData.js

2049-2049: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: push-check
🔇 Additional comments (2)
packages/vue-generator/test/testcases/generator/expected/appdemo01/package.json (2)

14-15: Good improvement: Fixed versions instead of "latest".

Replacing "latest" with fixed versions (0.1.16) for @opentiny/vue and @opentiny/vue-icon improves build reproducibility and prevents unexpected breaking changes.


22-22: Verify the new dependency's compatibility.

The addition of @opentiny/tiny-engine-builtin-component aligns with the PR's objective of managing built-in components.

Let's verify the compatibility of this new dependency:

✅ Verification successful

Dependency @opentiny/tiny-engine-builtin-component@2.0.0 is compatible

The dependency is stable with minimal requirements and aligns with the project's Vue ecosystem. Both 2.0.0 and 2.1.0 versions have identical dependencies, indicating no breaking changes.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if the specified version exists and get its publish date
curl -s https://registry.npmjs.org/@opentiny/tiny-engine-builtin-component | jq '."dist-tags", ."time"."2.0.0"'

Length of output: 240


Script:

#!/bin/bash
# Get detailed package info for versions 2.0.0 and 2.1.0
curl -s https://registry.npmjs.org/@opentiny/tiny-engine-builtin-component | jq '[.versions["2.0.0"], .versions["2.1.0"]] | map({version: .version, peerDependencies, dependencies})'

Length of output: 518


Script:

#!/bin/bash
# Find and check Vue version in package.json files
fd package.json | xargs cat | jq -r 'select(.dependencies.vue or .devDependencies.vue or .peerDependencies.vue) | {name: .name, vue: (.dependencies.vue // .devDependencies.vue // .peerDependencies.vue)}'

Length of output: 3920

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
packages/vue-generator/src/utils/generateImportStatement.js (1)

20-44: Good use of Set for deduplication.

The implementation effectively prevents duplicate imports by tracking both component names and aliases. This aligns well with the PR's objective of deduplicating the BuiltinComponentsMap.

However, consider adding a comment explaining the deduplication logic:

+ // Track seen components and aliases to prevent duplicates in import statements
const seen = new Set()
packages/vue-generator/test/testcases/generator/mockData.js (1)

1879-2050: Well-structured grid layout schema.

The new testCanvasRowCol schema demonstrates good use of nested grid components with proper gap spacing and responsive behavior. The structure follows a logical hierarchy of container > row > column.

However, consider adding comments to document the purpose of this test case:

{
+ // Test case for grid layout using CanvasRowColContainer
+ // Demonstrates nested rows and columns with responsive behavior
  state: {
    dataDisk: [1, 2, 3]
  },
  ...
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d685aef and a1e8832.

📒 Files selected for processing (3)
  • packages/vue-generator/src/plugins/parseSchemaPlugin.js (1 hunks)
  • packages/vue-generator/src/utils/generateImportStatement.js (1 hunks)
  • packages/vue-generator/test/testcases/generator/mockData.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/vue-generator/src/plugins/parseSchemaPlugin.js
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: push-check
🔇 Additional comments (2)
packages/vue-generator/src/utils/generateImportStatement.js (1)

1-16: LGTM! The base import statement generation looks good.

The function correctly handles different import scenarios including aliasing and destructuring.

packages/vue-generator/test/testcases/generator/mockData.js (1)

1880-1882: Verify the purpose of dataDisk state.

The state contains a dataDisk array [1, 2, 3] but its purpose is not clear from the schema. Consider documenting its usage or remove if unused.

@hexqi hexqi merged commit 15b6a9c into opentiny:refactor/develop Feb 6, 2025
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working refactor-main refactor/develop branch feature
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants