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

Ospp 2024/003 react dsl #743

Merged
merged 9 commits into from
Oct 31, 2024

Conversation

wjywy
Copy link

@wjywy wjywy commented Aug 17, 2024

English | 简体中文

PR

PR Type

What kind of change does this PR introduce?

  • Feature

Background and solution

实现了React的出码与预览功能

What is the current behavior?

What is the new behavior?

本次新增的功能为 React Dsl 的出码与预览,无 break change
首先,可以通过 packages\design-core\config\lowcode.config.js 路径下修改全局配置,若想要查看 React 出码与预览,则需要将此 dslmode 改为 React

然后便可以开始 React 的出码操作了,如视频所示:(视频见comment)

接下来也可以看一下预览操作,如视频所示:(视频见comment)

Does this PR introduce a breaking change?

  • No

Other information

Summary by CodeRabbit

  • New Features

    • Introduced a new CodeGenerator class for enhanced code generation capabilities.
    • Added multiple plugins for generating various application components, including data sources, pages, and internationalization support.
    • Implemented a new generateApp function for streamlined application generation.
    • Added support for Ant Design components in the DEFAULT_COMPONENTS_MAP.
    • Introduced new components such as FileSelector, ErrorBoundary, and ReactMonacoEditor.
    • Added a new useLazy hook for lazy-loading components.
  • Bug Fixes

    • Improved error handling in the code generation process.
  • Documentation

    • Updated README files to provide clearer instructions and project descriptions.
  • Style

    • Enhanced code formatting and readability across various files.

Copy link
Contributor

coderabbitai bot commented Aug 17, 2024

Important

Review skipped

More than 25% of the files skipped due to max files limit. The review is being skipped to prevent a low-quality review.

43 files out of 130 files are above the max files limit of 75. Please upgrade to Pro plan to get higher limits.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The pull request introduces significant updates to the @opentiny/tiny-engine-dsl-react package, enhancing its structure and functionality. Key changes include the addition of a module field in package.json, new dependencies for React and TypeScript, and a complete overhaul of the DEFAULT_COMPONENTS_MAP to align with Ant Design components. Furthermore, a new CodeGenerator class is implemented for schema-based code generation, and multiple utility and plugin files are added to facilitate various functionalities, including internationalization, data source management, and code formatting.

Changes

File Path Change Summary
packages/react-generator/package.json Added "module": "dist/tiny-engine-dsl-react.es.js", added react-router-dom and @types/node dependencies, and reformatted eslint-plugin-vue.
packages/react-generator/src/constant/index.js Updated DEFAULT_COMPONENTS_MAP to replace Vue components with Ant Design components, added new component mappings, and updated comments.
packages/react-generator/src/generator/codeGenerator.js Implemented CodeGenerator class with methods for schema processing, error handling, and file operations.
packages/react-generator/src/generator/generateApp.js Introduced generateApp function for application generation with plugins.
packages/react-generator/src/generator/index.js Added exports for generateApp and CodeGenerator.
packages/react-generator/src/generator/parseImport.js Added functions for parsing imports and generating import statements.
packages/react-generator/src/index.js Updated exports to include generateApp and CodeGenerator.
packages/react-generator/src/parser/state.js Added translateHookState function for state management.
packages/react-generator/src/plugins/formatCodePlugin.js Introduced formatCode function for code formatting using Prettier.
packages/react-generator/src/plugins/genBlockPlugin.js Added genBlockPlugin function for block schema transformation.
packages/react-generator/src/plugins/genDataSourcePlugin.js Added genDataSourcePlugin function for transforming schema into data source format.
packages/react-generator/src/plugins/genDependenciesPlugin.js Added genDependenciesPlugin function for managing dependencies in package.json.
packages/react-generator/src/plugins/genGlobalState.js Added genGlobalState function for generating global state management code.
packages/react-generator/src/plugins/genI18nPlugin.js Added genI18nPlugin function for internationalization code generation.
packages/react-generator/src/plugins/genPagePlugin.js Added genPagePlugin function for generating page code from schema.
packages/react-generator/src/plugins/genRouterPlugin.js Added genRouterPlugin function for router configuration generation.
packages/react-generator/src/plugins/genTemplatePlugin.js Added genTemplatePlugin function for template generation.
packages/react-generator/src/plugins/genUtilsPlugin.js Added genUtilsPlugin function for utility schema transformation.
packages/react-generator/src/plugins/index.js Re-exported all plugin functions for easier access.
packages/react-generator/src/templates/react-templates/index.js Introduced template generation functionality based on schema.
packages/react-generator/src/templates/react-templates/template-files/* Added various template files for project setup, including index.html, packageJson.js, and App.jsx.
packages/react-generator/src/utils/* Added utility functions for import statement generation and JSX detection.
packages/react-generator/vite.config.js Updated Vite configuration to include new plugins and settings.
packages/toolbars/generate-react/src/Main.vue Transitioned from Vue to React code generation logic.
packages/toolbars/generate-vue/src/Main.vue Updated imports and state management for Vue code generation.
packages/vue-generator/src/generator/vue/sfc/* Updated import paths and structures for Vue component generation.
packages/vue-generator/src/plugins/* Adjusted import paths for various Vue plugins.
mockServer/src/mock/get/app-center/v1/apps/schema/918.json Updated JSON schema formatting for readability.
mockServer/src/services/appinfo.json Restructured JSON formatting for clarity and added a new state entry.

Possibly related PRs

Suggested labels

ready_for_review

Suggested reviewers

  • hexqi
  • yy-wow
  • lizhijie429

Poem

🐇 In the garden where changes bloom,
React takes flight, dispelling gloom.
Code flows like rivers, swift and bright,
With plugins and templates, all feels right.
So hop along, let’s celebrate,
The magic of code, it’s never too late! 🌼


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 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.

@hexqi hexqi added the ospp-2024 ospp-2024 label Aug 17, 2024
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: 30

Outside diff range, codebase verification and nitpick comments (34)
packages/react-generator/src/templates/index.js (1)

1-5: Consider adding comments or documentation.

The file is straightforward, but adding comments or documentation would enhance clarity and maintainability, especially for future developers who might work on this code.

+// Import the default static template generator
import { generateTemplate as genDefaultStaticTemplate } from './react-templates'

+// Map of template types to their respective generator functions
export const templateMap = {
  default: genDefaultStaticTemplate
}
packages/react-generator/test/testcases/full/case1_normal/input/components-map.json (1)

10-14: Ensure completeness of component entries.

The entry for "Img" lacks an export name and package, which might affect the test's effectiveness. Consider providing complete information for consistency and clarity.

{
  "componentName": "Img",
  "exportName": "ImgComponent", // Example export name
  "package": "@opentiny/img-package", // Example package name
  "version": "1.0.0",
  "destructuring": true
}
packages/react-generator/src/index.js (1)

1-11: Consider uncommenting the license header.

The license header is currently commented out. If it's necessary for compliance, consider uncommenting it.

-// /**
-// * Copyright (c) 2023 - present TinyEngine Authors.
-// * Copyright (c) 2023 - present Huawei Cloud Computing Technologies Co., Ltd.
-// *
-// * Use of this source code is governed by an MIT-style license.
-// *
-// * THE OPEN SOURCE SOFTWARE IN THIS PRODUCT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL,
-// * BUT WITHOUT ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR
-// * A PARTICULAR PURPOSE. SEE THE APPLICABLE LICENSES FOR MORE DETAILS.
-// *
-// */
packages/toolbars/generate-react/index.js (1)

17-22: Inconsistent Metadata in React File

The metadata in packages/toolbars/generate-react/index.js uses 'genarate-vue', which suggests a Vue context. This is inconsistent with the file's intended React purpose. Consider updating the metadata to reflect a React context.

  • packages/toolbars/generate-react/index.js: Update id and title to align with React.
Analysis chain

Check metadata alignment with file purpose.

The metadata suggests a Vue context (genarate-vue). Ensure this aligns with the intended React context.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify if the metadata aligns with the intended React context.

# Test: Search for metadata usage. Expect: Consistent usage in a React context.
rg --type javascript -A 5 $'id: \'genarate-vue\''

Length of output: 89


Script:

#!/bin/bash
# Corrected script: Verify if the metadata aligns with the intended React context.

# Test: Search for metadata usage with corrected file type. Expect: Consistent usage in a React context.
rg --type js -A 5 $'id: \'genarate-vue\''

Length of output: 723

packages/react-generator/src/templates/react-templates/template-files/genViteConfig.js (1)

2-3: Document the process.env workaround.

The workaround for process.env replacement is a common practice. Consider adding a comment to explain its purpose.

+    // This workaround prevents `process.env` from being replaced during build.
    const processStr = ['process', 'env']
packages/react-generator/test/testcases/full/index.config.js (1)

13-31: Enhance Test Case Coverage and Clarity

The current configuration files in both react-generator and vue-generator contain only a single test case. To ensure comprehensive testing, consider adding more test cases that cover a wider range of scenarios. Additionally, provide more detailed descriptions for each test case to improve clarity.

  • File: packages/react-generator/test/testcases/full/index.config.js
  • File: packages/vue-generator/test/testcases/full/index.config.js
Analysis chain

Ensure test case completeness and clarity.

The configuration file sets up test cases for code generation. Ensure that the test cases cover a wide range of scenarios and that the descriptions are clear and informative.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the completeness and clarity of test cases in the configuration.

# Test: Search for all test case configurations. Expect: Comprehensive test coverage and clear descriptions.
rg --type javascript -A 5 $'cases:'

Length of output: 69


Script:

#!/bin/bash
# Description: Verify the completeness and clarity of test cases in the configuration.

# Test: Search for all test case configurations. Expect: Comprehensive test coverage and clear descriptions.
rg --type js -A 5 $'cases:'

Length of output: 2314

packages/react-generator/src/plugins/getTemplatePlugin.js (1)

32-34: Remove or replace console.log for production code.

The use of console.log('cuurent', templateMap) is not ideal for production code. Consider using a logging library or removing this statement if it's not necessary.

- console.log('cuurent', templateMap)
+ // Consider using a logging library or removing this line
packages/react-generator/src/utils/generateImportStatement.js (1)

1-1: Clarify the TODO comment.

The comment "动态导入,暂时不考虑" suggests that dynamic imports are not considered. Provide more context or remove if not needed.

- // TODO: 动态导入,暂时不考虑
+ // TODO: Consider dynamic imports in the future if needed.
packages/design-core/config/lowcode.config.js (1)

108-109: Review and Enhance React Lifecycle Tips

The current React lifecycle tip in the codebase is vague and lacks specific guidance. Consider providing more detailed instructions or examples to align with user expectations and improve clarity.

  • Current message: "React生命周期可在这正常配置" (React lifecycle can be configured here normally)
Analysis chain

Ensure lifecycle tips for React are accurate and helpful.

The lifecycle tips for React should provide clear guidance. Verify that this message is consistent with the documentation and user expectations.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the documentation and usage of React lifecycle tips.

# Test: Search for lifecycle tips usage. Expect: Consistency with documentation.
rg --type js -A 5 $'lifeCycleTips'

Length of output: 1900


Script:

#!/bin/bash
# Search for documentation or additional references to React lifecycle tips or configurations.
rg --type md 'React lifecycle' -A 5
rg --type js 'React lifecycle' -A 5

Length of output: 75

packages/react-generator/src/generator/generateApp.js (1)

1-13: Review unused imports.

Several imports are commented out, which might indicate incomplete or unused functionality. Consider removing them if they are not needed.

-    // genBlockPlugin,
-    // genDataSourcePlugin,
-    // genDependenciesPlugin,
-    // genRouterPlugin,
-    // genUtilsPlugin,
-    // formatCodePlugin,
-    // parseSchemaPlugin,
-    // genGlobalState
packages/react-generator/src/plugins/genPagePlugin.js (1)

23-23: Remove console logs for cleaner output.

The console logs are useful for debugging but should be removed or replaced with proper logging before production.

-    console.log('你进来没有啊我草')
+    // console.log('Debug: Entering prettierCode function')
-    console.log(pageFiles, 'pageFiles>>>')
+    // console.log('Debug: Generated page files', pageFiles)

Also applies to: 63-63

packages/react-generator/src/utils/index.js (3)

19-34: Consider input validation or error handling.

The getFunctionInfo function efficiently extracts function details using regex. However, consider adding input validation or error handling for malformed input.

+  if (!fnStr || typeof fnStr !== 'string') {
+    return null;
+  }

36-40: Consider renaming or providing context.

The safeRandom function is a simple wrapper around Math.random. Consider renaming for clarity or providing additional context on its purpose.

- const safeRandom = () => {
+ const getRandomFunction = () => {

50-60: Consider adding validation for existings.

The avoidDuplicateString function effectively avoids duplicates. Consider adding validation to ensure existings is an array.

+  if (!Array.isArray(existings)) {
+    throw new Error('existings must be an array');
+  }
packages/toolbars/generate-react/src/Main.vue (1)

23-31: Consider Import Optimization.

The imports include several utilities from @opentiny. Ensure that only necessary imports are included to optimize performance and reduce bundle size.

packages/react-generator/test/testcases/full/case1_normal/input/blocks.schema.json (1)

1-212: Consider adding descriptions and examples for clarity.

The JSON schema is well-structured, but adding descriptions and examples for each property and method could improve readability and usability for developers who will use this schema.

{
  "property": "src",
  "type": "string",
  "defaultValue": "https://example.com/image.svg",
  "label": {
    "text": {
      "zh_CN": "图片地址"
    }
  },
  "description": "URL of the image to be displayed.",
  "example": "https://example.com/image.svg"
}
packages/react-generator/src/constant/index.js (2)

27-50: Maintain consistency in component mapping definitions.

Ensure that BUILTIN_COMPONENTS_MAP is consistent with other mappings in terms of structure and naming conventions.

-  {
+  /* Ensure consistent naming and structure */

17-25: Update DEFAULT_COMPONENTS_MAP to reflect the latest package version

The DEFAULT_COMPONENTS_MAP currently specifies version ^3.10.0 for @opentiny/vue, but the latest version found in the repository is ~3.14.0. Consider updating the version in the map to ensure consistency and access to the latest features and fixes.

  • Current version in map: ^3.10.0
  • Latest version found: ~3.14.0
Analysis chain

Ensure component mappings are up-to-date.

Verify that the DEFAULT_COMPONENTS_MAP entries are accurate and reflect the latest package versions and component names.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the accuracy of the `DEFAULT_COMPONENTS_MAP`.

# Test: Check the package.json files for the listed packages and versions.
rg --files-with-matches '@opentiny/vue' | xargs -I {} jq '.dependencies["@opentiny/vue"]' {}

Length of output: 14327


Script:

#!/bin/bash
# Description: Verify the accuracy of the `DEFAULT_COMPONENTS_MAP` by checking the package version in package.json files.

# Find all package.json files and check for the version of @opentiny/vue
fd package.json | xargs -I {} jq -r '.dependencies["@opentiny/vue"]' {} 2>/dev/null | sort | uniq

Length of output: 119

packages/toolbars/generate-vue/src/Main.vue (1)

Line range hint 164-233:
Console Logging: Ensure Removal in Production

Numerous console.log statements are added for debugging. Ensure these are removed or replaced with a proper logging mechanism before deploying to production to avoid exposing sensitive information.

- console.log(params, 'params')
- console.log(promises, 'promises')
- console.log(appData, 'appData', metaData, 'metaData', pageList, 'pageList', dirHandle, 'dirHandle')
- console.log(appSchema, 'appSchema')
- console.log(res, 'res')
packages/toolbars/generate-vue/src/generateCode.js (2)

133-133: Debugging Output: Ensure Removal in Production

A console.log statement is added for debugging codeList. Ensure this is removed or replaced with a proper logging mechanism before deploying to production.

- console.log(codeList, 'codeList')

278-278: Export Logic Issue: Handle Empty Export Names

The generateExport function does not currently handle cases where exportNames is empty, leading to potentially unnecessary empty export statements like export { }. Consider adding a check to ensure that the export statement is only pushed if exportNames is non-empty.

  • Location: packages/toolbars/generate-vue/src/generateCode.js, line 278
  • Location: packages/toolbars/generate-react/src/generateCode.js, line 283
Analysis chain

Export Logic: Ensure Correctness

The export statement is always pushed for exportNames. Ensure that this logic is correct and that it doesn't result in empty export statements if exportNames is empty.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of `generateExport` to ensure it handles empty `exportNames`.

# Test: Search for the usage of `generateExport` to ensure it is used correctly.
rg --type js 'generateExport'

Length of output: 393


Script:

#!/bin/bash
# Extract the implementation of the `generateExport` function from both files to check how it handles empty lists.
ast-grep --lang javascript --pattern 'function generateExport($_) { $$$ }'

Length of output: 3305

packages/toolbars/generate-react/src/generateCode.js (2)

19-28: Consider externalizing configuration.

The basePaths object is hardcoded. Consider loading these paths from a configuration file or environment variables to enhance flexibility and maintainability.

-// LOWCODE_TODO: 从本地配置文件获取
const basePaths = {
  i18n: 'src/i18n/',
  pages: 'src/views/',
  blocks: 'src/components/',
  utils: 'src/lowcode/utils.js',
  dataSource: 'src/lowcode/dataSource.json',
  router: 'src/router/index.js',
  store: 'src/stores/'
}
+// Consider loading from a configuration file or environment variables

196-214: Ensure proper validation and error handling in generateDataSource.

The generateDataSource function lacks explicit validation and error handling for the dataSource parameter. Consider adding checks and logging for malformed or missing data to enhance robustness.

  • Location: packages/toolbars/generate-react/src/generateCode.js and packages/toolbars/generate-vue/src/generateCode.js
Analysis chain

Ensure dataSource is properly validated.

In generateDataSource, ensure that dataSource is validated and any potential errors are handled. Consider adding logging for missing or malformed data.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that `dataSource` is properly validated and errors are handled in `generateDataSource`.

# Test: Check for error handling or validation logic in `generateDataSource`.
rg --type javascript 'generateDataSource'

Length of output: 76


Script:

#!/bin/bash
# Search for the `generateDataSource` function to check for validation and error handling.
ast-grep --lang javascript --pattern $'function generateDataSource($_) {
  $$$
}'

Length of output: 3191

packages/plugins/page/src/PageSetting.vue (1)

58-65: Ensure getGlobalConfig handles errors and provides defaults.

The getGlobalConfig function in packages/controller/src/globalConfig.js is a simple getter for globalConfig without built-in error handling or default value provisions. Consider implementing these features where globalConfig is set or used to ensure robustness.

  • Location of getGlobalConfig: packages/controller/src/globalConfig.js
Analysis chain

Ensure getGlobalConfig handles errors.

The getGlobalConfig function is used to retrieve global configuration settings. Ensure it handles errors gracefully and provides defaults if necessary.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that `getGlobalConfig` handles errors and provides defaults.

# Test: Check the implementation of `getGlobalConfig` for error handling and default values.
rg --type javascript 'function getGlobalConfig'

Length of output: 84


Script:

#!/bin/bash
# Description: Verify that `getGlobalConfig` handles errors and provides defaults.

# Test: Check the implementation of `getGlobalConfig` for error handling and default values.
rg 'function getGlobalConfig' -A 10

Length of output: 37


Script:

#!/bin/bash
# Description: Search for any references to `getGlobalConfig` in the codebase.

# Find any imports or exports of `getGlobalConfig`.
rg 'getGlobalConfig' -A 2 -B 2

# Search for potential arrow function or method definitions.
rg 'getGlobalConfig\s*[:=]\s*\(?\s*' -A 5

Length of output: 21131

packages/plugins/data/src/Main.vue (1)

84-85: Ensure getGlobalConfig Handles Errors and Provides Defaults

The getGlobalConfig function currently returns the globalConfig variable, which is initialized to null and later assigned a value. There is no error handling or default value logic implemented. Consider adding error handling to manage cases where globalConfig might be null or improperly initialized, and provide sensible default values if necessary.

  • packages/controller/src/globalConfig.js: Review the initialization and usage of globalConfig to implement error handling and defaults.
Analysis chain

Ensure getGlobalConfig handles errors.

The getGlobalConfig function is used to retrieve global configuration settings. Ensure it handles errors gracefully and provides defaults if necessary.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that `getGlobalConfig` handles errors and provides defaults.

# Test: Check the implementation of `getGlobalConfig` for error handling and default values.
rg --type javascript 'function getGlobalConfig'

Length of output: 84


Script:

#!/bin/bash
# Description: Search for the implementation of `getGlobalConfig` in the codebase.

# Test: Locate the `getGlobalConfig` function definition.
rg 'function getGlobalConfig'

Length of output: 31


Script:

#!/bin/bash
# Description: Search for any occurrences of `getGlobalConfig` in the codebase.

# Test: Locate references to `getGlobalConfig`, including import statements or usage.
rg 'getGlobalConfig'

Length of output: 6107


Script:

#!/bin/bash
# Description: Search for the definition and initialization of `globalConfig`.

# Test: Locate the definition and initialization of `globalConfig` in the relevant files.
rg 'globalConfig' packages/controller/src/globalConfig.js

Length of output: 155

mockServer/src/mock/get/app-center/v1/apps/schema/918.json (1)

Potential Impact from Removing "element-plus" Components

The removal of "element-plus" components from mockServer/src/mock/get/app-center/v1/apps/schema/918.json might affect other parts of the application. These components are still referenced in other JSON files, such as mockServer/src/services/appinfo.json and packages/design-core/public/mock/bundle.json. Ensure that these references are updated or verified to be unnecessary to avoid inconsistencies.

  • Files with References:
    • mockServer/src/services/appinfo.json
    • packages/design-core/public/mock/bundle.json
Analysis chain

Line range hint 1-1: Assess Impact of Removed Component Definitions.

The removal of multiple "element-plus" components from the JSON schema suggests a strategic change. Ensure that these components are no longer needed and that their removal does not affect application functionality.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the impact of removing "element-plus" components from the JSON schema.

# Test: Search for usage of removed components to ensure they are not referenced elsewhere.
rg --type json 'ElInput|ElButton|ElForm|ElFormItem|ElTable|ElTableColumn'

Length of output: 3287

packages/design-core/public/mock/bundle.json (5)

6-454: Ensure Consistency in Property Naming.

The property label-position uses a hyphen, while others like labelCol do not. Consider maintaining consistency in naming conventions for better readability and maintainability.

- "property": "label-position"
+ "property": "labelPosition"

14-15: Add Documentation URL.

The doc_url field is currently empty. Providing documentation links can help developers understand the component usage better.

- "doc_url": ""
+ "doc_url": "https://link-to-docs"

455-795: Consider Adding More Descriptive Labels.

The label property is simply named "label". Consider using more descriptive labels to improve clarity, especially for internationalization.

- "label": "label"
+ "label": "Form Item Label"

14568-14601: Consider Adding Descriptions for Steps.

The items array in the AntdSteps snippet has empty descriptions. Adding descriptions can provide more context for each step.

- "description": ""
+ "description": "Description for this step."

14602-14672: Ensure Button Labels are Descriptive.

The button labels "提交" and "重置" are clear in Chinese, but consider providing translations or comments for internationalization support.

{
  "children": "Submit" // 提交
}
packages/react-generator/src/generator/codeGenerator.js (2)

38-69: Remove or replace console logs for production code.

The generate method contains a console log statement. In production code, consider using a logging library that can be configured to handle different log levels.

- console.log(schema, 'ReactSchema>>>>>>>>')
+ // Consider using a logging library for production

141-154: Improve error messages for schema parsing.

The error messages in parseSchema could be more descriptive. Consider including the invalid schema in the error message to aid debugging.

- '[codeGenerator][generate] parseSchema error, schema is not valid, please check the input params.'
+ `[codeGenerator][generate] parseSchema error, schema is not valid: ${schema}`
packages/toolbars/generate-react/src/FileSelector.vue (1)

36-38: Organize imports for clarity.

Group related imports together and consider sorting them for better readability.

import { reactive, computed, ref, nextTick } from 'vue'
// Separate third-party and local imports
import { DialogBox, Button, Grid, GridColumn } from '@opentiny/vue'
import { useNotify } from '@opentiny/tiny-engine-controller'
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 7a1f2e6 and 2f80271.

Files ignored due to path filters (1)
  • mockServer/src/database/pages.db is excluded by !**/*.db
Files selected for processing (71)
  • mockServer/package.json (1 hunks)
  • mockServer/src/mock/get/app-center/v1/apps/schema/918.json (1 hunks)
  • mockServer/src/services/schema2code.js (1 hunks)
  • package.json (1 hunks)
  • packages/canvas/package.json (1 hunks)
  • packages/canvas/src/Design.vue (1 hunks)
  • packages/canvas/src/components/container/CanvasContainer.vue (1 hunks)
  • packages/canvas/src/components/container/container.js (1 hunks)
  • packages/canvas/src/components/render/render.js (5 hunks)
  • packages/common/component/MetaArrayItem.vue (3 hunks)
  • packages/design-core/config/addons.js (3 hunks)
  • packages/design-core/config/lowcode.config.js (3 hunks)
  • packages/design-core/package.json (2 hunks)
  • packages/design-core/public/mock/bundle.json (2 hunks)
  • packages/design-core/src/preview/src/preview/importMap.json (1 hunks)
  • packages/design-core/vite.config.js (2 hunks)
  • packages/plugins/block/src/BlockSetting.vue (4 hunks)
  • packages/plugins/data/src/CreateVariable.vue (6 hunks)
  • packages/plugins/data/src/Main.vue (4 hunks)
  • packages/plugins/page/src/PageSetting.vue (4 hunks)
  • packages/react-generator/.eslintrc.cjs (1 hunks)
  • packages/react-generator/.gitignore (1 hunks)
  • packages/react-generator/jsconfig.json (1 hunks)
  • packages/react-generator/package.json (1 hunks)
  • packages/react-generator/src/constant/index.js (1 hunks)
  • packages/react-generator/src/generator/codeGenerator.js (1 hunks)
  • packages/react-generator/src/generator/generateApp.js (1 hunks)
  • packages/react-generator/src/generator/index.js (1 hunks)
  • packages/react-generator/src/generator/page.js (1 hunks)
  • packages/react-generator/src/index.d.ts (1 hunks)
  • packages/react-generator/src/index.js (1 hunks)
  • packages/react-generator/src/parser/jsx-slot.js (1 hunks)
  • packages/react-generator/src/parser/state-type.js (1 hunks)
  • packages/react-generator/src/parser/state.js (1 hunks)
  • packages/react-generator/src/plugins/genPagePlugin.js (1 hunks)
  • packages/react-generator/src/plugins/getI18nPlugin.js (1 hunks)
  • packages/react-generator/src/plugins/getTemplatePlugin.js (1 hunks)
  • packages/react-generator/src/plugins/index.js (1 hunks)
  • packages/react-generator/src/pre-processor/index.js (1 hunks)
  • packages/react-generator/src/templates/index.js (1 hunks)
  • packages/react-generator/src/templates/react-templates/index.js (1 hunks)
  • packages/react-generator/src/templates/react-templates/template-files/.gitignore (1 hunks)
  • packages/react-generator/src/templates/react-templates/template-files/README.md (1 hunks)
  • packages/react-generator/src/templates/react-templates/template-files/genViteConfig.js (1 hunks)
  • packages/react-generator/src/templates/react-templates/template-files/index.html (1 hunks)
  • packages/react-generator/src/templates/react-templates/template-files/packageJson.js (1 hunks)
  • packages/react-generator/src/utils/generateImportStatement.js (1 hunks)
  • packages/react-generator/src/utils/index.js (1 hunks)
  • packages/react-generator/src/utils/mergeOptions.js (1 hunks)
  • packages/react-generator/src/utils/vue-sfc-validator.js (1 hunks)
  • packages/react-generator/test/testcases/full/case1_normal/input/blocks.schema.json (1 hunks)
  • packages/react-generator/test/testcases/full/case1_normal/input/components-map.json (1 hunks)
  • packages/react-generator/test/testcases/full/case1_normal/input/page.schema.json (1 hunks)
  • packages/react-generator/test/testcases/full/index.config.js (1 hunks)
  • packages/react-generator/test/testcases/full/index.js (1 hunks)
  • packages/react-generator/test/utils/logger/index.js (1 hunks)
  • packages/react-generator/vite.config.js (1 hunks)
  • packages/toolbars/generate-react/index.js (1 hunks)
  • packages/toolbars/generate-react/package.json (1 hunks)
  • packages/toolbars/generate-react/src/FileSelector.vue (1 hunks)
  • packages/toolbars/generate-react/src/Main.vue (1 hunks)
  • packages/toolbars/generate-react/src/generateCode.js (1 hunks)
  • packages/toolbars/generate-react/src/http.js (1 hunks)
  • packages/toolbars/generate-react/vite.config.js (1 hunks)
  • packages/toolbars/generate-vue/package.json (1 hunks)
  • packages/toolbars/generate-vue/src/FileSelector.vue (1 hunks)
  • packages/toolbars/generate-vue/src/Main.vue (9 hunks)
  • packages/toolbars/generate-vue/src/generateCode.js (5 hunks)
  • packages/toolbars/generate-vue/src/http.js (1 hunks)
  • patches/[email protected] (1 hunks)
  • scripts/setup.js (1 hunks)
Files skipped from review due to trivial changes (12)
  • packages/design-core/src/preview/src/preview/importMap.json
  • packages/react-generator/.eslintrc.cjs
  • packages/react-generator/.gitignore
  • packages/react-generator/jsconfig.json
  • packages/react-generator/src/generator/index.js
  • packages/react-generator/src/plugins/index.js
  • packages/react-generator/src/templates/react-templates/template-files/.gitignore
  • packages/react-generator/src/templates/react-templates/template-files/README.md
  • packages/react-generator/src/templates/react-templates/template-files/index.html
  • packages/react-generator/test/utils/logger/index.js
  • packages/toolbars/generate-react/package.json
  • packages/toolbars/generate-vue/src/FileSelector.vue
Additional context used
Biome
packages/react-generator/src/pre-processor/index.js

[error] 23-23: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 43-43: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 53-53: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

packages/toolbars/generate-react/src/generateCode.js

[error] 74-74: Avoid the use of spread (...) syntax on accumulators.

Spread syntax should be avoided on accumulators (like those in .reduce) because it causes a time complexity of O(n^2).
Consider methods such as .splice or .push instead.

(lint/performance/noAccumulatingSpread)


[error] 305-305: Avoid the use of spread (...) syntax on accumulators.

Spread syntax should be avoided on accumulators (like those in .reduce) because it causes a time complexity of O(n^2).
Consider methods such as .splice or .push instead.

(lint/performance/noAccumulatingSpread)

packages/react-generator/src/generator/page.js

[error] 305-306: Avoid the use of spread (...) syntax on accumulators.

Spread syntax should be avoided on accumulators (like those in .reduce) because it causes a time complexity of O(n^2).
Consider methods such as .splice or .push instead.

(lint/performance/noAccumulatingSpread)


[error] 444-444: Avoid the use of spread (...) syntax on accumulators.

Spread syntax should be avoided on accumulators (like those in .reduce) because it causes a time complexity of O(n^2).
Consider methods such as .splice or .push instead.

(lint/performance/noAccumulatingSpread)

Additional comments not posted (119)
packages/react-generator/src/index.js (1)

13-15: LGTM!

The exports are correctly set up and follow standard JavaScript practices.

packages/toolbars/generate-react/index.js (1)

13-14: Verify the component import.

The current import is from a Vue file, which may not align with a React context. Ensure this is intentional.

packages/react-generator/src/templates/react-templates/template-files/genViteConfig.js (1)

8-9: Verify the use of Vue plugins.

The configuration imports Vue plugins, which may not align with a React context. Ensure this is intentional.

packages/react-generator/src/utils/mergeOptions.js (2)

1-3: Ensure isObject handles edge cases.

The isObject function correctly identifies plain objects. However, consider edge cases such as null values, arrays, and other non-object types that might be passed inadvertently.


6-30: Consider edge cases for mergeOptions.

The mergeOptions function effectively merges objects, but ensure it handles edge cases like circular references, non-object inputs, and prototype pollution.

packages/react-generator/src/templates/react-templates/template-files/packageJson.js (1)

1-34: Review the generated package.json for accuracy.

The package.json template correctly sets up a project with necessary scripts and dependencies. Ensure that the version numbers are up-to-date and that all required dependencies are included.

packages/react-generator/src/plugins/getTemplatePlugin.js (1)

7-19: Consider handling undefined return values.

The function genTemplatePlugin does not explicitly handle cases where res is undefined or null. Ensure that downstream code can handle such cases or provide a default return value.

packages/toolbars/generate-vue/package.json (1)

30-30: Dependency addition looks good.

The addition of @opentiny/tiny-engine-dsl-react as a dependency is appropriate for expanding the package's capabilities to support React.

packages/toolbars/generate-react/vite.config.js (1)

15-16: Verify the necessity of Vue plugins in a React package.

The inclusion of Vue and Vue JSX plugins in a React package configuration is unusual. Verify if these are required or if they can be removed.

Verification successful

Let's adjust the script to search for Vue-related terms using file extensions instead of file types. This should help us verify if the Vue plugins are used in the React package.


Vue plugins are used in the React package configuration.

The search results indicate that Vue-related plugins and components are indeed present in the generate-react package. This includes imports and configurations that utilize Vue plugins and components.

  • Files and Lines:
    • packages/toolbars/generate-react/vite.config.js: Vue plugins are imported and used in the Vite configuration.
    • packages/toolbars/generate-react/index.js: Contains imports and references to Vue components.
    • packages/toolbars/generate-react/src/generateCode.js: Contains references to Vue-related code generation.

These findings suggest that the Vue plugins are actively used in the package, contrary to the initial assumption that they might not be necessary. Further investigation into the package's purpose and dependencies is recommended to determine if this setup is intentional or if refactoring is needed.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify if Vue plugins are used in the React package.

# Test: Search for Vue plugin usage in the React package. Expect: No usage found.
rg --type js --type jsx --type ts --type tsx "vue" packages/toolbars/generate-react

Length of output: 111


Script:

#!/bin/bash
# Description: Verify if Vue plugins are used in the React package.

# Test: Search for Vue plugin usage in the React package. Expect: No usage found.
rg "vue" --glob "*.js" --glob "*.jsx" --glob "*.ts" --glob "*.tsx" packages/toolbars/generate-react

Length of output: 1137

packages/canvas/src/Design.vue (1)

34-40: LGTM! Verify the integration of AntdForm.

The addition of the AntdForm property with its nestingRule is consistent with the existing structure for other components.

Ensure that the integration of AntdForm with these rules aligns with the expected behavior in the application.

packages/toolbars/generate-react/src/http.js (4)

1-11: File Header: Ensure compliance with licensing terms.

The file includes a standard header for licensing. Ensure that the use and distribution of this file comply with the stated terms.


39-39: LGTM! Verify the usage of fetchPageList.

The fetchPageList function is well-defined for making GET requests.

Ensure that the function is used correctly across the codebase with appropriate parameters.

Verification successful

Verification Complete: fetchPageList Usage is Consistent

The fetchPageList function is used consistently across the codebase with appropriate parameters (appId or params.app). No issues found in its usage.

  • PageTree.vue: Uses appId.
  • Main.vue in generate-react: Uses params.app.
  • Main.vue in generate-vue: Uses params.app.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of `fetchPageList` within the codebase.

# Test: Search for `fetchPageList` usage. Expect: Consistent usage with correct parameters.
rg --type js 'fetchPageList'

Length of output: 1117


Script:

#!/bin/bash
# Check the context of `fetchPageList` usage in `PageTree.vue` and `Main.vue` files.
rg -A 5 'fetchPageList' packages/plugins/page/src/PageTree.vue packages/toolbars/generate-react/src/Main.vue packages/toolbars/generate-vue/src/Main.vue

Length of output: 2894


20-27: LGTM! Verify the usage of fetchCode.

The fetchCode function is well-structured for making POST requests.

Ensure that the function is used correctly across the codebase with appropriate parameters.

Verification successful

Usage of fetchCode is consistent and correct. The params object used in Main.vue correctly includes the expected properties for the fetchCode function, ensuring proper usage across the codebase.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of `fetchCode` within the codebase.

# Test: Search for `fetchCode` usage. Expect: Consistent usage with correct parameters.
rg --type js 'fetchCode'

Length of output: 919


Script:

#!/bin/bash
# Search for the definition or initialization of `params` in Main.vue
rg 'params' packages/toolbars/generate-react/src/Main.vue -A 5 -B 5

Length of output: 2171


30-36: LGTM! Verify the usage of fetchMetaData.

The fetchMetaData function correctly handles GET requests and parameters.

Ensure that the function is used correctly across the codebase with appropriate parameters.

Verification successful

Usage of fetchMetaData is consistent across the codebase. The function is used with parameter objects (params or queryParams) in all identified instances, which aligns with its expected input structure. No issues found with its usage.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of `fetchMetaData` within the codebase.

# Test: Search for `fetchMetaData` usage. Expect: Consistent usage with correct parameters.
rg --type js 'fetchMetaData'

Length of output: 1147


Script:

#!/bin/bash
# Extract lines around `fetchMetaData` usage in the identified Vue files to examine parameter usage.

# Extract usage context in Main.vue of generate-react package
rg -A 5 -B 5 'fetchMetaData' packages/toolbars/generate-react/src/Main.vue

# Extract usage context in Main.vue of generate-vue package
rg -A 5 -B 5 'fetchMetaData' packages/toolbars/generate-vue/src/Main.vue

# Extract usage context in Preview.vue of design-core package
rg -A 5 -B 5 'fetchMetaData' packages/design-core/src/preview/src/preview/Preview.vue

Length of output: 2869

packages/react-generator/vite.config.js (2)

1-11: File Header: Ensure compliance with licensing terms.

The file includes a standard header for licensing. Ensure that the use and distribution of this file comply with the stated terms.


19-50: LGTM! Verify the Vite configuration.

The Vite configuration is well-structured, with appropriate settings for building the library, handling plugins, and resolving aliases.

Ensure that the configuration aligns with the project's build and development requirements.

Verification successful

Vite Configuration Verified

The Vite configuration in packages/react-generator/vite.config.js is well-structured and aligns with the project's build and development requirements. No conflicting or overriding configurations were found in the codebase.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the Vite configuration within the codebase.

# Test: Check for any Vite configuration overrides or related settings.
rg --type js --type json 'vite' --glob '!packages/react-generator/vite.config.js'

Length of output: 35024

packages/react-generator/package.json (4)

2-3: Verify package name and version.

Ensure that the package name @opentiny/tiny-engine-dsl-react and version 0.1.0 are correct and follow the project's naming conventions and versioning strategy.


12-16: Review build and test scripts.

The build script uses Vite, which is suitable for modern front-end projects. The test script uses nyc for coverage, which is a good practice. Ensure these scripts are aligned with the project's build and test processes.


29-34: Confirm dependency versions.

Ensure that the versions specified for dependencies like @vue/compiler-sfc, vue, and vue-eslint-parser are compatible with the React DSL and do not introduce conflicts.


36-45: Review devDependencies for consistency.

The devDependencies include tools for linting and building. Verify that these versions are consistent with other packages in the project to avoid conflicts.

packages/canvas/package.json (3)

42-42: Verify the addition of @vitejs/plugin-react.

Ensure that the addition of @vitejs/plugin-react is necessary for the project and that its version ^4.2.1 is compatible with other dependencies.


45-45: Confirm the necessity of antd.

The addition of antd version 5.16.2 suggests a need for Ant Design components. Verify its necessity and compatibility with the project's UI framework.


46-46: Review the inclusion of veaury.

veaury version 2.3.16 is included, which supports Vue and React interoperability. Confirm its necessity and ensure it aligns with the project's goals.

packages/react-generator/src/parser/state.js (2)

16-30: Ensure traverse function handles all edge cases.

The traverse function recursively processes objects and arrays. Verify that it correctly handles all edge cases, such as circular references or unexpected data types.


34-37: Optimize unwrapExpression function.

The unwrapExpression function uses regex to replace patterns. Ensure that the regex is efficient and correctly handles all expected input formats.

packages/toolbars/generate-vue/src/http.js (1)

14-31: Verify the functionality of generateCode.

The fetchCode function now uses generateCode instead of http.post. Ensure that generateCode provides the expected functionality previously handled by the HTTP request.

Verification successful

Functionality of generateCode Verified

The generateCode function, imported from @opentiny/tiny-engine-dsl-react, is implemented to handle schema-to-code transformations, aligning with the functionality previously managed by the HTTP request in fetchCode. This change appears consistent with the intended functionality.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the implementation of `generateCode` to ensure it matches the expected functionality.

# Test: Search for the `generateCode` function definition. Expect: Implementation details of `generateCode`.
ast-grep --lang javascript --pattern $'function generateCode($_) { $$$ }'

Length of output: 163


Script:

#!/bin/bash
# Description: Search for the `generateCode` function definition in various possible forms.

# Search for `generateCode` as a named function
ast-grep --lang javascript --pattern $'function generateCode($_) { $$$ }'

# Search for `generateCode` as an arrow function
ast-grep --lang javascript --pattern $'const generateCode = ($_ => { $$$ })'

# Search for `generateCode` as a method in an object
ast-grep --lang javascript --pattern $'generateCode($_) { $$$ }'

Length of output: 843


Script:

#!/bin/bash
# Description: Search for the `generateCode` function definition or import.

# Search for `generateCode` as an imported function
rg 'import { generateCode }' -A 2

# Search for `generateCode` as a named export
rg 'export function generateCode' -A 5

# Search for `generateCode` as a default export
rg 'export default function generateCode' -A 5

# Corrected search for `generateCode` as a method in an object
ast-grep --lang javascript --pattern $'{ generateCode($_) { $$$ } }'

Length of output: 399


Script:

#!/bin/bash
# Description: Search for any references to `generateCode` across the codebase.

# General search for `generateCode` references
rg 'generateCode' -A 5 -B 5

# Search for `generateCode` in object destructuring or module exports
ast-grep --lang javascript --pattern $'{ generateCode: $_ }'

# Search for `generateCode` in potential dynamic import or require statements
rg 'require.*generateCode' -A 2

Length of output: 32782

mockServer/package.json (1)

28-28: Verify the necessity and integration of @opentiny/tiny-engine-dsl-react.

The addition of this dependency indicates a shift towards React-based features. Ensure that this dependency is necessary and correctly integrated within the project.

Verification successful

The @opentiny/tiny-engine-dsl-react package is integrated and used across multiple files, indicating its necessity.

  • Usage Locations:
    • scripts/setup.js: Used in a build command.
    • mockServer/src/services/schema2code.js: Used with require.
    • packages/toolbars/generate-react/src/Main.vue: Used with import.
    • packages/toolbars/generate-vue/src/Main.vue: Commented-out import suggests possible future or conditional usage.

The integration appears correct, but consider reviewing the commented-out import in generate-vue/src/Main.vue for clarity on its intended use.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of `@opentiny/tiny-engine-dsl-react` to ensure its necessity.

# Test: Search for the usage of the new dependency in the codebase. Expect: References to `@opentiny/tiny-engine-dsl-react`.
rg --type js "@opentiny/tiny-engine-dsl-react"

Length of output: 465

packages/react-generator/src/utils/generateImportStatement.js (2)

2-20: Ensure comprehensive handling of import scenarios in generateImportStatement.

The function generates import statements based on the provided configuration. Ensure it handles all edge cases, such as missing module names or export names.


24-58: Ensure comprehensive handling of import scenarios in generateImportByPkgName.

This function handles multiple import configurations. Ensure it correctly processes all scenarios, especially with default and named imports.

packages/react-generator/src/plugins/getI18nPlugin.js (5)

28-35: Verify correctness of generated JSON files.

Ensure that the JSON files generated for i18n entries are correctly formatted and contain the expected content.


15-17: Ensure consistency in plugin naming and description.

The plugin name tinyEngine-generateCode-plugin-i18n and its description should align with the project's naming conventions for plugins.

Verification successful

Plugin Naming Consistency Verified

The plugin name tinyEngine-generateCode-plugin-i18n follows the observed naming pattern used in the codebase, such as in tinyEngine-generateCode-plugin-template and others. This indicates consistency with the project's naming conventions for plugins.

  • packages/react-generator/src/plugins/getI18nPlugin.js: name: 'tinyEngine-generateCode-plugin-i18n'
  • Other plugins in the same directory follow a similar naming pattern.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify the naming conventions of plugins in the codebase.
rg --type js --pattern 'name:'

Length of output: 442


Script:

#!/bin/bash
# Correct the command to search for plugin names in JavaScript files.
rg 'name:' --type js

Length of output: 33794


4-8: Verify default options for file paths and names.

Ensure that the default paths and file names (localeFileName, entryFileName, and path) are consistent with the project's directory structure and naming conventions.

Verification successful

Default options for file paths and names are consistent.

The default paths and file names (localeFileName, entryFileName, and path) specified in the code snippet align with the project's conventions and usage patterns, as evidenced by their references in the codebase. The src/i18n directory and related files appear to be generated as part of the i18n setup.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify the existence of default paths and files in the project structure.
fd --type d 'src/i18n'

Length of output: 22


Script:

#!/bin/bash
# Search for references to the default path and file names in the codebase.
rg 'src/i18n' -A 2
rg 'locale.js' -A 2
rg 'index.js' -A 2

Length of output: 41881


55-67: Verify correctness of index.js generation.

Ensure that the index.js file is generated with the correct imports and locale message merging logic.

Verification successful

The index.js file generation is correct.

The generated index.js file includes the necessary imports and locale message merging logic as specified in the review comment. The imports and logic for merging locale messages are correctly implemented.

  • Import of i18n from @opentiny/tiny-engine-i18n-host.
  • Import of lowcode from ../lowcodeConfig/lowcode.
  • Import of locale from ./locale.js.
  • Setting i18n.lowcode to lowcode.
  • Merging locale messages using i18n.global.mergeLocaleMessage.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify the structure and content of the generated `index.js` file.
cat <path_to_generated_index_js>

Length of output: 175


Script:

#!/bin/bash
# Locate the generated `index.js` file and display its contents.
fd 'index.js' --type f --exec cat

Length of output: 165815


44-52: Verify correctness of locale.js generation.

Ensure that the locale.js file is generated correctly with the appropriate import statements and export structure.

Verification successful

Verification of locale.js Generation Logic

The locale.js file is generated correctly in the genI18nPlugin function. The code constructs import statements for each language file and exports them in an object. The logic ensures that all language entries from the schema are included, and the import statements are properly formatted.

  • The langs array is populated with keys from the i18n object, representing different languages.
  • The importStatements array is constructed using these keys to generate import statements for each language JSON file.
  • The fileContent for locale.js includes these import statements and exports an object containing all languages.

This process ensures the locale.js file is generated with the appropriate structure and content.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify the structure and content of the generated `locale.js` file.
cat <path_to_generated_locale_js>

Length of output: 176


Script:

#!/bin/bash
# Search for references to `locale.js` in the codebase to determine where it is generated or stored.
rg 'locale\.js' --context 5

Length of output: 4971


Script:

#!/bin/bash
# Extract the relevant code section from `getI18nPlugin.js` to verify the logic for generating `locale.js`.
ast-grep --lang javascript --pattern $'function genI18nPlugin(options = {}) {
  $$$
  const langs = Object.keys(i18n)
  const importStatements = langs.map((lang) =>
    generateImportStatement({ moduleName: `./${lang}.json`, exportName: lang })
  )
  $$$
}' packages/react-generator/src/plugins/getI18nPlugin.js

Length of output: 312


Script:

#!/bin/bash
# Use ripgrep to extract the relevant code section around `genI18nPlugin` in `getI18nPlugin.js`.
rg 'function genI18nPlugin' -A 20 packages/react-generator/src/plugins/getI18nPlugin.js

Length of output: 663


Script:

#!/bin/bash
# Extend the search to capture more lines of the `genI18nPlugin` function to verify the generation logic.
rg 'function genI18nPlugin' -A 50 packages/react-generator/src/plugins/getI18nPlugin.js

Length of output: 1426

packages/react-generator/src/pre-processor/index.js (1)

78-91: Verify schema transformations for correctness.

Ensure that the schema transformations (text2Span, tinyIcon, tinyGrid, collection2Div, component2Block) are correctly applied and produce the intended results.

Verification successful

Schema Transformations Verified

The implementations of the transformation functions (text2Span, tinyIcon, tinyGrid, collection2Div, component2Block) have been successfully extracted and reviewed. Each function checks specific conditions on the schema object and modifies it accordingly. These transformations appear to be consistent with their intended purposes, such as renaming components or adjusting properties.

  • text2Span: Converts TEXT components to span and moves props.text to children.
  • tinyIcon: Renames icon components to ensure they have a Tiny prefix.
  • tinyGrid: Removes data property if fetchData is present for TinyGrid.
  • collection2Div: Converts COLLECTION components to div.
  • component2Block: Adjusts componentName and fileName for BLOCK components.

These transformations seem to be correctly implemented based on the logic provided. Further testing or documentation review might be needed to ensure they align with all intended use cases.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify the correctness of schema transformations.
# This requires inspecting the transformed schema objects.

Length of output: 0


Script:

#!/bin/bash
# Find the implementation of the transformation functions in the repository.
ast-grep --lang javascript --pattern 'function text2Span($_) { $$$ }'
ast-grep --lang javascript --pattern 'function tinyIcon($_) { $$$ }'
ast-grep --lang javascript --pattern 'function tinyGrid($_) { $$$ }'
ast-grep --lang javascript --pattern 'function collection2Div($_) { $$$ }'
ast-grep --lang javascript --pattern 'function component2Block($_) { $$$ }'

Length of output: 813


Script:

#!/bin/bash
# Search for test cases related to the transformation functions in the repository.
rg 'text2Span' --glob '*test*'
rg 'tinyIcon' --glob '*test*'
rg 'tinyGrid' --glob '*test*'
rg 'collection2Div' --glob '*test*'
rg 'component2Block' --glob '*test*'

Length of output: 163


Script:

#!/bin/bash
# Search for the transformation functions in the entire codebase to find their definitions or usages.
rg 'text2Span'
rg 'tinyIcon'
rg 'tinyGrid'
rg 'collection2Div'
rg 'component2Block'

Length of output: 2356


Script:

#!/bin/bash
# Extract the implementations of the transformation functions from the react-generator pre-processor file.
ast-grep --lang javascript --pattern 'const text2Span = (schema) => { $$$ }' packages/react-generator/src/pre-processor/index.js
ast-grep --lang javascript --pattern 'const tinyIcon = (schema) => { $$$ }' packages/react-generator/src/pre-processor/index.js
ast-grep --lang javascript --pattern 'const tinyGrid = (schema) => { $$$ }' packages/react-generator/src/pre-processor/index.js
ast-grep --lang javascript --pattern 'const collection2Div = (schema) => { $$$ }' packages/react-generator/src/pre-processor/index.js
ast-grep --lang javascript --pattern 'const component2Block = (schema) => { $$$ }' packages/react-generator/src/pre-processor/index.js

Length of output: 5272

packages/react-generator/src/parser/state-type.js (1)

64-77: Verify type transformations for correctness.

Ensure that the type transformations handled by the strategy object are correctly applied and produce the intended results.

packages/design-core/config/lowcode.config.js (4)

18-18: Verify the impact of changing dslMode to 'React'.

Changing the dslMode to 'React' may have significant implications on how the application behaves. Ensure that all dependent components and configurations are compatible with React.


36-40: Ensure React material and styles are correctly configured.

The material and styles for React are specified. Verify that these paths are correct and the resources are available.

Verification successful

React material and styles are correctly configured.

The specified files react-bundle.json and tiny-vue.css are present in the repository, confirming that the paths in the configuration are correct. No further action is needed.

  • packages/design-core/public/mock/react-bundle.json
  • packages/design-core/public/tiny-vue.css
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the existence of React material and styles files.

# Test: Check for the presence of the specified files. Expect: Files exist.
fd 'react-bundle.json' -p 'mock'
fd 'tiny-vue.css' -p 'mock'

Length of output: 240


Script:

#!/bin/bash
# Description: Search for the existence of React material and styles files across the entire repository.

# Test: Check for the presence of the specified files. Expect: Files exist.
fd 'react-bundle.json'
fd 'tiny-vue.css'

Length of output: 132


101-102: Add getDerivedStateFromProps to React lifecycle options.

The addition of getDerivedStateFromProps enhances React lifecycle management. Ensure that this method is used correctly in the codebase.


45-66: Review moduleDisplayStatus settings for React.

The moduleDisplayStatus for React is set to false for all options. Ensure this aligns with the intended functionality and does not inadvertently disable necessary features.

packages/react-generator/src/generator/generateApp.js (1)

22-75: Ensure all necessary plugins are included.

The function generateApp initializes a code generator with a set of plugins. Verify that all necessary plugins are included and configured correctly.

Verification successful

Current plugin configuration in generateApp is appropriate.

The generateApp function is designed to be flexible, allowing users to customize which plugins are active. The current implementation includes a minimal set of essential plugins (genTemplatePlugin, genPagePlugin, genI18nPlugin) and allows for additional plugins to be added as needed. This aligns with the documentation, which shows examples of customizing and replacing plugins. No further changes are necessary unless specific requirements dictate otherwise.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the completeness and correctness of plugin usage in `generateApp`.

# Test: Search for all plugin usage in the codebase. Expect: Correct and complete usage.
rg --type js -A 5 $'gen(\\w+)Plugin'

Length of output: 27149


Script:

#!/bin/bash
# Search for documentation or comments related to `generateApp` to determine necessary plugins.
rg --type md --type js 'generateApp' -A 10

Length of output: 14316

packages/design-core/config/addons.js (2)

24-24: Verify the import of GenerateReact.

Ensure that GenerateReact is correctly imported and used within the configuration.

Verification successful

Import and usage of GenerateReact are correct.

The GenerateReact module is correctly imported and utilized in the configuration file packages/design-core/config/addons.js. It is used in a conditional expression to determine the techStackToolbars based on the dslMode. No issues found with its import or usage.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of `GenerateReact` in the codebase.

# Test: Search for `GenerateReact` usage. Expect: Correct and complete usage.
rg --type js -A 5 $'GenerateReact'

Length of output: 1059


49-50: Ensure otherPlugins and techStackToolbars are correctly configured.

The configuration dynamically changes based on dslMode. Verify that these arrays are set up correctly for both React and other modes.

mockServer/src/services/schema2code.js (1)

53-53: Verify compatibility with the new React module.

The import statement has been updated to use @opentiny/tiny-engine-dsl-react. Ensure that this module is compatible with the existing code and that all necessary adjustments have been made for this transition.

packages/react-generator/src/plugins/genPagePlugin.js (1)

37-51: Verify logic for handling block replacements.

Ensure that the logic for replacing block paths in prettierCode is correct and that basePaths.blocks is defined and used appropriately.

Verification successful

Verified: Logic for handling block replacements is correct.

The basePaths.blocks is defined as 'src/components/', and the transformation logic in the code snippet correctly replaces 'src/' with '@/'. This ensures that block paths are handled appropriately in the code.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the logic for block path replacements in `prettierCode`.

# Test: Search for the definition and usage of `basePaths.blocks`. Expect: Correct path transformation logic.
rg --type js $'basePaths.blocks'

Length of output: 842


Script:

#!/bin/bash
# Description: Search for the definition of `basePaths` to verify how `basePaths.blocks` is set up.

# Test: Find the definition of `basePaths` in JavaScript files.
rg --type js 'const basePaths' -A 5

Length of output: 1006

package.json (1)

71-72: Verify the application of the veaury patch.

A new patched dependency for [email protected] has been added. Ensure that the patch is correctly applied and does not introduce any issues.

packages/react-generator/test/testcases/full/case1_normal/input/page.schema.json (3)

2-20: State section is well-structured.

The use of JSExpression and JSFunction for dynamic state management is appropriate and correctly implemented.


41-107: Components section is well-integrated.

The use of Ant Design components with appropriate props and event handlers is consistent and follows best practices.


36-116: Other attributes are well-defined.

Attributes like componentName, fileName, css, props, lifeCycles, dataSource, bridge, inputs, and outputs are correctly defined and complete the schema structure.

packages/react-generator/test/testcases/full/index.js (1)

20-38: getPageData function is well-implemented.

The use of fs.existsSync before requiring files is a good practice to avoid runtime errors.

packages/react-generator/src/templates/react-templates/index.js (1)

22-33: getTemplate function is well-implemented.

The use of regex to replace placeholders with schema values is effective and correctly implemented.

packages/react-generator/src/parser/jsx-slot.js (3)

16-32: LGTM! Handle expression bindings correctly.

The function correctly processes expression bindings and event handlers, ensuring proper conversion to JSX attributes.


34-59: LGTM! Correctly handle property bindings.

The function effectively processes different property types, ensuring proper JSX attribute formatting.


62-115: LGTM! Robust JSX template generation.

The function provides a comprehensive solution for generating JSX templates, handling conditionals and child components effectively.

packages/react-generator/src/index.d.ts (1)

1-151: LGTM! Well-structured namespace for DSL types.

The namespace provides a comprehensive and clear structure for the DSL's types, enhancing type safety and clarity.

packages/common/component/MetaArrayItem.vue (2)

Line range hint 1-29:
LGTM! Improved template robustness with fallback logic.

The template effectively uses Vue's slot system and enhances content rendering with a fallback for item.title.


Line range hint 30-159:
LGTM! Enhanced interactivity and data handling.

The script section improves component interactivity by restructuring event handling logic and integrating updates within specific actions.

packages/react-generator/src/utils/vue-sfc-validator.js (4)

22-46: LGTM!

The validateByParse function is well-implemented, with appropriate error handling and use of vue-eslint-parser for validation.


55-117: Comprehensive validation approach.

The validateByCompile function effectively validates scripts, templates, and styles using @vue/compiler-sfc, with robust error handling.


125-131: Consistent error formatting.

The unify function ensures errors are consistently formatted, which aids in error handling.


139-155: Enhanced error messaging.

The locateErrorMessage function effectively enhances error messages with location context, aiding in debugging.

packages/react-generator/src/utils/index.js (8)

17-17: LGTM!

The getTypeOfSchema function correctly retrieves the component name from the schema.


42-48: LGTM!

The randomString function is well-implemented, efficiently generating random strings.


62-62: LGTM!

The lowerFirst function correctly converts the first character of a string to lowercase.


70-70: LGTM!

The toPascalCase function is well-implemented, effectively converting strings to PascalCase.


78-82: LGTM!

The prettierOpts object provides comprehensive formatting options for different parsers.


87-88: LGTM!

The isOn and isOnUpdate functions correctly detect event-related keys using regex.


90-98: LGTM!

The toEventKey function correctly formats event handler keys, handling different cases appropriately.


100-147: LGTM!

The functions related to accessors and icons are well-implemented, effectively managing component properties.

packages/design-core/package.json (2)

68-68: New dependency added: @opentiny/tiny-engine-toolbar-generate-react.

This addition suggests new functionality related to React component generation.


97-97: Verify the impact of downgrading vue.

The version of vue has been downgraded from 3.4.23 to 3.4.21. Verify that this change does not introduce any compatibility issues.

packages/toolbars/generate-react/src/Main.vue (4)

1-21: Ensure Accessibility and Usability of the UI Components.

The template section uses tiny-popover and generate-file-selector components. Ensure that these components are accessible and provide feedback for users with different needs. Consider adding ARIA attributes if necessary.


55-79: Verify URLSearchParams Usage for Compatibility.

The getParams function uses URLSearchParams to extract query parameters. Ensure compatibility with environments that might not support this API or consider using a polyfill.


88-99: Handle Potential Promise Rejections.

The getPreGenerateInfo function uses Promise.all. Ensure that all promises are properly handled to avoid unhandled promise rejections, especially in environments that enforce strict error handling.


157-172: Ensure Data Integrity in the confirm Method.

The confirm method processes selected files. Ensure that the data passed to saveCodeToLocal is validated to prevent data corruption or unexpected behavior.

packages/canvas/src/components/container/CanvasContainer.vue (1)

131-145: Verify the impact of using the capture phase for mousedown.

The addition of true to addEventListener changes the event handling to the capture phase. Ensure this change aligns with the intended behavior and does not introduce unintended side effects.

packages/react-generator/src/constant/index.js (1)

52-140: Review Antd component versions.

Ensure that the Antd component versions are consistent with the project's dependencies and are up-to-date.

packages/plugins/block/src/BlockSetting.vue (2)

Line range hint 26-43:
Conditional Rendering Logic: Ensure Correctness

The v-if directive for tiny-collapse-item components checks moduleDisplayStatus[dslMode].block. Ensure that moduleDisplayStatus and dslMode are always defined and valid. Consider adding a fallback or error handling to prevent runtime errors if these values are undefined.

Verification successful

Ensure Robustness Against Undefined Values

The dslMode and moduleDisplayStatus variables are initialized using getGlobalConfig() with optional chaining, providing some protection against undefined values. However, consider implementing additional error handling or default values to further prevent potential runtime issues.

  • Location in Codebase:
    • packages/plugins/block/src/BlockSetting.vue: Initialization and usage of dslMode and moduleDisplayStatus.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage and initialization of `dslMode` and `moduleDisplayStatus` in the codebase.

# Test: Search for the initialization and usage of `dslMode` and `moduleDisplayStatus`.
rg --type vue --type js 'dslMode|moduleDisplayStatus'

Length of output: 83


Script:

#!/bin/bash
# Description: Verify the usage and initialization of `dslMode` and `moduleDisplayStatus` in the codebase.

# Test: Search for the initialization and usage of `dslMode` and `moduleDisplayStatus` in .vue and .js files.
rg 'dslMode|moduleDisplayStatus' --glob '**/*.vue' --glob '**/*.js' -A 3

Length of output: 13028


133-134: Initialization of Global Config Variables

The variables dslMode and moduleDisplayStatus are initialized using getGlobalConfig(). Ensure that getGlobalConfig() always returns an object with these properties to avoid potential null or undefined errors.

packages/toolbars/generate-vue/src/Main.vue (4)

13-13: New Selection Feature: Ensure Correct Binding

The <tiny-select> component is added for selecting the output type. Ensure that state.value is correctly initialized and updated, and that the options are accurately defined.


Line range hint 26-49:
Import and Component Registration

The Select component is imported and registered as TinySelect. Ensure that the component is correctly integrated and that there are no conflicts with existing components.


67-78: State Initialization: Verify Default Values

The state object now includes value, instance, and options. Ensure that these are initialized with appropriate default values and that they align with the application's logic.


229-231: Dynamic Instance Assignment: Verify Logic

The state.instance is dynamically assigned based on state.value. Ensure that both generateReactApp and generateVueApp are correctly imported and functional, and that the logic handles all possible values of state.value.

Verification successful

Dynamic Instance Assignment: Verification Successful

The generateReactApp and generateVueApp functions are correctly defined and exported in their respective modules. The dynamic assignment logic in Main.vue is implemented correctly. No issues found.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the imports of `generateReactApp` and `generateVueApp`.

# Test: Search for the imports of `generateReactApp` and `generateVueApp` to ensure they are correctly defined.
rg --type js 'generateReactApp|generateVueApp'

Length of output: 580


Script:

#!/bin/bash
# Description: Verify the definition and export of `generateApp` in the Vue module.
ast-grep --lang javascript --pattern 'export function generateApp($_) { $$$ }' -- 'packages/toolbars/generate-vue/src/Main.vue'

# Description: Verify the definition and export of `generateApp` in the React module.
ast-grep --lang javascript --pattern 'export function generateApp($_) { $$$ }' -- 'react-generator/src/index'

Length of output: 310


Script:

#!/bin/bash
# Locate the correct path for the React generator index file.
fd 'index' --type f --glob --search-path react-generator

# Verify the definition and export of `generateApp` in the Vue module.
ast-grep --lang javascript --pattern 'export function generateApp($_) { $$$ }' -- 'packages/toolbars/generate-vue/src/Main.vue'

Length of output: 287


Script:

#!/bin/bash
# Locate the correct path for any index file that might contain the React generator.
fd 'index' --type f --glob

# Search for the definition of `generateApp` function across the repository.
ast-grep --lang javascript --pattern 'export function generateApp($_) { $$$ }'

Length of output: 10492

packages/toolbars/generate-vue/src/generateCode.js (2)

16-16: TypeScript Support: Verify Integration

The addition of parseTypescript from Prettier allows TypeScript code formatting. Ensure that this integration is correctly implemented and that it doesn't conflict with existing parsers.


287-294: Utility Export Logic: Ensure Consistency

The generateUtils function now calls generateExport with an empty array if utils is not provided. Ensure that this change maintains consistency and doesn't introduce unexpected behavior.

packages/toolbars/generate-react/src/generateCode.js (1)

80-123: Ensure proper error handling and validation.

In generateStores, ensure that globalState is validated and any potential errors are handled gracefully. Consider adding logging or error messages for debugging purposes.

packages/plugins/page/src/PageSetting.vue (2)

120-121: Verify the impact of global configuration changes.

The introduction of dslMode and moduleDisplayStatus from getGlobalConfig can impact the component's behavior. Verify that these changes do not introduce unintended side effects.


27-27: Ensure module display status is correctly initialized.

The condition moduleDisplayStatus[dslMode].page assumes that moduleDisplayStatus and dslMode are initialized and valid. Ensure these values are correctly set and handle potential undefined values to avoid runtime errors.

Verification successful

Initialization of moduleDisplayStatus and dslMode Verified

Both moduleDisplayStatus and dslMode are initialized using getGlobalConfig(). This approach should ensure they are set correctly if getGlobalConfig() is functioning as expected. However, it's crucial to handle cases where these values might be undefined to prevent runtime errors.

  • moduleDisplayStatus is initialized in multiple files, including PageSetting.vue, using getGlobalConfig()?.moduleDisplayStatus.
  • dslMode is initialized in http.js with getGlobalConfig()?.dslMode.

Ensure that getGlobalConfig() is robust and handles cases where the configuration might not be available. Consider adding default values or error handling to manage potential undefined states.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that `moduleDisplayStatus` and `dslMode` are correctly initialized and used.

# Test: Check for initialization and usage of `moduleDisplayStatus` and `dslMode`.
rg --type vue 'moduleDisplayStatus|dslMode'

Length of output: 73


Script:

#!/bin/bash
# Description: Verify initialization and usage of `moduleDisplayStatus` and `dslMode` in JavaScript code.

# Search for `moduleDisplayStatus` initialization and usage
ast-grep --lang javascript --pattern 'const moduleDisplayStatus = $_' .

# Search for `dslMode` initialization and usage
ast-grep --lang javascript --pattern 'const dslMode = $_' .

Length of output: 406


Script:

#!/bin/bash
# Description: Search for `moduleDisplayStatus` in the repository to verify its initialization and usage.

# Use ripgrep to search for `moduleDisplayStatus` across all files
rg 'moduleDisplayStatus'

Length of output: 1467

packages/plugins/data/src/Main.vue (2)

12-12: Ensure module display status is correctly initialized.

The condition moduleDisplayStatus[dslMode].globalState assumes that moduleDisplayStatus and dslMode are initialized and valid. Ensure these values are correctly set and handle potential undefined values to avoid runtime errors.

Verification successful

Initialization of moduleDisplayStatus and dslMode appears handled via getGlobalConfig(). These variables are initialized using getGlobalConfig(), suggesting they are set in a centralized configuration. Ensure getGlobalConfig() is correctly implemented to avoid runtime errors. If issues persist, further investigation into getGlobalConfig() may be needed.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that `moduleDisplayStatus` and `dslMode` are correctly initialized and used.

# Test: Check for initialization and usage of `moduleDisplayStatus` and `dslMode`.
rg --type vue 'moduleDisplayStatus|dslMode'

Length of output: 73


Script:

#!/bin/bash
# Find all .vue files and search for `moduleDisplayStatus` and `dslMode`
fd --extension vue --exec rg 'moduleDisplayStatus|dslMode' {}

Length of output: 2062


120-121: Verify the impact of global configuration changes.

The introduction of dslMode and moduleDisplayStatus from getGlobalConfig can impact the component's behavior. Verify that these changes do not introduce unintended side effects.

packages/design-core/vite.config.js (2)

170-170: Addition of alias for React toolbar generation.

The new alias @opentiny/tiny-engine-toolbar-generate-react facilitates better integration with the React generation toolbar. Ensure that this path is correct and the module exists at the specified location.


134-134: Verify the impact of downgrading Vue version.

Downgrading Vue from 3.4.23 to 3.4.21 might affect features or fixes present in the newer version. Ensure compatibility with other dependencies and test thoroughly.

packages/plugins/data/src/CreateVariable.vue (5)

77-77: Conditional rendering based on dslMode.

The code now conditionally renders getterReactExample or getterExample based on dslMode. Ensure that dslMode is correctly set and managed in the global configuration.


88-88: Refined rendering condition for tiny-form-item.

The condition for displaying the tiny-form-item now includes moduleDisplayStatus[dslMode].globalState. This ensures tighter control over rendering. Verify that moduleDisplayStatus is correctly configured and updated.


117-117: Import of getGlobalConfig for configuration management.

The addition of getGlobalConfig allows dynamic retrieval of global settings. Ensure this function is reliable and handles cases where the configuration might be missing or incomplete.


150-151: Introduction of reactive variables dslMode and moduleDisplayStatus.

These variables enhance the component's adaptability to different DSL modes. Ensure they are correctly initialized and updated in response to changes in the global configuration.


380-380: New constant getterReactExample.

This addition provides a specific example for React, expanding the component's versatility. Ensure consistency with other examples and verify its correctness.

packages/react-generator/src/generator/page.js (10)

40-57: Review recurseJSXChildren function.

The function recursively processes JSX children. Ensure that all possible child types are handled and that the description.jsResource updates are correct.


62-78: Review handleJSXEventBinding function.

This function handles event bindings for JSX. Ensure that the logic correctly translates Vue event bindings to React and that parameter handling is robust.


81-114: Review handleJSXLiteralBinding function.

The function manages literal bindings in JSX. Ensure that all literal types are correctly processed and that the function handles complex types appropriately.


116-137: Review handleJSXBinding function.

This function processes all JSX bindings. Ensure that the logic correctly distinguishes between event, literal, and expression types.


139-230: Review generateJSXNode function.

This function generates JSX nodes from a schema. Ensure that all schema properties are correctly translated to JSX and that the function handles edge cases.


232-324: Review generateReactImports function.

This function generates import statements for React components. Ensure that all necessary components are imported and that the logic handles component dependencies correctly.

Tools
Biome

[error] 305-306: Avoid the use of spread (...) syntax on accumulators.

Spread syntax should be avoided on accumulators (like those in .reduce) because it causes a time complexity of O(n^2).
Consider methods such as .splice or .push instead.

(lint/performance/noAccumulatingSpread)


327-423: Review generateReactCode function.

This function generates React code from a schema. Ensure that the code generation logic correctly translates schema properties, state, and lifecycle methods into React components.


436-485: Review generatePageCode function.

This function generates code for a page, including React and CSS. Ensure that the function correctly handles schema preprocessing and that the generated code is valid.

Tools
Biome

[error] 444-444: Avoid the use of spread (...) syntax on accumulators.

Spread syntax should be avoided on accumulators (like those in .reduce) because it causes a time complexity of O(n^2).
Consider methods such as .splice or .push instead.

(lint/performance/noAccumulatingSpread)


487-497: Review generateBlocksCode function.

This function generates code for individual blocks. Ensure that the function correctly processes block data and generates valid code.


499-518: Review generateCode function.

This function orchestrates the generation of code for pages and blocks. Ensure that the function correctly integrates all components and handles edge cases.

packages/canvas/src/components/render/render.js (4)

594-604: Conditional Logic for Class Name Handling.

The logic for renaming className to class is applied only to non-Ant Design components. Ensure this does not conflict with any component-specific styling or functionality.

Verification successful

Conditional Logic for Class Name Handling Verified

The logic for renaming className to class for non-Ant Design components appears to be correctly implemented. The search results show consistent handling of className across the codebase, and no conflicts with component-specific styling or functionality were identified.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the impact of conditional class name handling on component styling.

# Test: Search for components using `className` to ensure no conflicts arise.
rg --type js 'className' -A 5

Length of output: 60883


32-33: Ensure Proper Usage of Imported Libraries.

The import of applyPureReactInVue from veaury and Antd from antd indicates a shift towards integrating React components within a Vue environment. Ensure that these libraries are correctly configured and compatible with the project's existing setup.

Verification successful

Integration of React Components in Vue Environment Verified

The usage of applyPureReactInVue and Antd components in the render.js file is correctly implemented for integrating React components within a Vue environment. The dynamic handling of Antd components aligns with the intended functionality. No issues were found with the configuration or usage of these libraries.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage and configuration of imported libraries `veaury` and `antd`.

# Test: Check for usage of `applyPureReactInVue` and `Antd` components.
rg --type js 'applyPureReactInVue|Antd' -A 5

Length of output: 10142


525-528: Clarify Event Handling Logic.

The stopNotPreventEvent function stops event propagation but does not prevent default behavior. Ensure this behavior is intentional and does not lead to unexpected issues in the application.

Verification successful

Event Handling Logic Verified.

The use of stopNotPreventEvent in the onMouseDownCapture event for bindProps is intentional to support the functionality of AntdSelect. It stops event propagation without preventing default behavior, which is appropriate for components like dropdowns that rely on default actions. No changes are needed.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of `stopNotPreventEvent` to ensure it aligns with expected event handling behavior.

# Test: Check where `stopNotPreventEvent` is used to confirm its intended use.
rg --type js 'stopNotPreventEvent' -A 5

Length of output: 928


Script:

#!/bin/bash
# Description: Check the context of `bindProps.onMouseDownCapture` and its interaction with `AntdSelect`.

# Test: Search for the definition and usage of `bindProps` to understand its role.
rg --type js 'bindProps' -A 10

# Test: Check for references to `AntdSelect` to understand its interaction with `stopNotPreventEvent`.
rg --type js 'AntdSelect' -A 10

Length of output: 4812


350-361: Verify Ant Design Component Mapping.

The antdComponents object maps Ant Design components to a prefixed format. Ensure that all necessary components and sub-components are correctly included and that this mapping aligns with project requirements.

packages/canvas/src/components/container/container.js (1)

304-304: Improve Function Robustness with Early Return.

The early return in querySelectById for falsy id values enhances function robustness by avoiding unnecessary DOM queries. This change is beneficial for preventing errors and improving performance.

patches/[email protected] (1)

7-7: Ensure import statement consistency.

The import statement on line 7 re-imports React and other modules. Ensure that these imports are consistent with the rest of the codebase and do not cause conflicts or redundancy.

packages/design-core/public/mock/bundle.json (2)

919-1561: Ensure Unique Keys in dataSource.

The dataSource array contains duplicate keys. Ensure that each entry has a unique key to prevent rendering issues.

- "key": "1"
+ "key": "unique-key-1"

Likely invalid or redundant comment.


797-917: Verify Property Type for current.

The current property is defined as a string, but it typically represents a numeric index in step components. Verify if the type should be number.

packages/react-generator/src/generator/codeGenerator.js (2)

17-28: Ensure plugin configuration is validated.

When initializing the CodeGenerator, ensure that the config.plugins is validated to be an array. This prevents runtime errors if the configuration is incorrect.

Consider adding validation logic to check the type of config.plugins.


209-211: Ensure consistent use of background colors.

The CSS class .row__current uses a different background color. Ensure this is intentional and consistent with the design guidelines.

Verify that the color used here aligns with the overall design theme.

packages/toolbars/generate-react/src/FileSelector.vue (2)

74-85: Validate selected data before emitting.

Ensure that the selected data is valid before emitting the confirm event. Consider adding additional checks or constraints.

Ensure that the selected data meets any necessary criteria before proceeding.


106-231: Ensure CSS variables are defined.

The styles use CSS variables. Ensure these variables are defined in the global scope or appropriate context to avoid rendering issues.

Verify that all CSS variables used are defined and accessible in the component's context.

scripts/setup.js Outdated Show resolved Hide resolved
packages/toolbars/generate-react/index.js Outdated Show resolved Hide resolved
packages/react-generator/package.json Outdated Show resolved Hide resolved
packages/toolbars/generate-react/src/Main.vue Outdated Show resolved Hide resolved
packages/react-generator/src/generator/codeGenerator.js Outdated Show resolved Hide resolved
packages/react-generator/src/generator/codeGenerator.js Outdated Show resolved Hide resolved
packages/react-generator/src/generator/codeGenerator.js Outdated Show resolved Hide resolved
packages/toolbars/generate-react/src/FileSelector.vue Outdated Show resolved Hide resolved
packages/toolbars/generate-react/src/FileSelector.vue Outdated Show resolved Hide resolved
@hexqi
Copy link
Collaborator

hexqi commented Aug 18, 2024

代码有冲突,请先拉取远程目标分支代码,解决冲突

@Issues-translate-bot
Copy link

Bot detected the issue body's language is not English, translate it automatically.


There is a conflict in the code. Please pull the remote target branch code first to resolve the conflict.

mockServer/package.json Outdated Show resolved Hide resolved
Copy link
Collaborator

@hexqi hexqi left a comment

Choose a reason for hiding this comment

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

请处理完冲突后先让导师review代码

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: 33

🧹 Outside diff range and nitpick comments (22)
packages/react-generator/src/templates/react-templates/template-files/src/App.jsx (2)

1-1: Consider adding file extension to import statement.

For better clarity and tooling support, consider specifying the file extension in the import path.

-import Routers from './router'
+import Routers from './router.jsx'

3-9: Consider adding component documentation and type definitions.

The component would benefit from:

  1. JSDoc documentation explaining its purpose
  2. PropTypes or TypeScript type definitions
+/**
+ * Root component that handles application routing
+ */
 function App() {
   return (
-    <>
-      <Routers></Routers>
-    </>
+    <Routers />
   )
 }
packages/react-generator/src/templates/react-templates/template-files/src/hooks/useLazy.jsx (1)

1-10: Document the hook's usage and limitations.

The hook lacks documentation explaining its purpose, usage, and limitations.

Add JSDoc comments:

+/**
+ * Creates a lazy-loaded version of a React component with Suspense wrapper.
+ * 
+ * @param {React.ComponentType} Component - The component to be lazy loaded
+ * @returns {React.FC} A wrapped component that lazy loads the original component
+ * 
+ * @example
+ * const LazyComponent = useLazy(MyComponent);
+ * // Later in JSX
+ * <LazyComponent prop1="value" />
+ * 
+ * @note This implementation is best suited for client-side only components.
+ * For SSR compatibility, ensure proper server-side handling is in place.
+ */
packages/toolbars/generate-react/index.js (2)

13-14: Consider decoupling React generator from Vue components.

The React generator is currently importing a Vue component from the Vue generator. This creates an unnecessary dependency between React and Vue tooling.

Consider extracting shared logic into a common utility module and implementing separate Vue/React specific components. This would:

  • Reduce coupling between Vue and React tooling
  • Make the codebase more maintainable
  • Allow independent evolution of Vue and React generators

Line range hint 13-22: Review the overall generator architecture.

The current implementation shares Vue components between Vue and React generators. This approach might lead to:

  1. Unnecessary dependencies in the React tooling bundle
  2. Challenges in maintaining separate Vue/React features
  3. Potential conflicts in component lifecycle management

Consider implementing a more modular architecture:

  1. Create a shared core module for common generator logic
  2. Implement separate Vue and React specific UI components
  3. Use dependency injection or strategy pattern for framework-specific code

Would you like assistance in designing a more modular architecture for the generators?

packages/react-generator/src/parser/state.js (1)

43-50: Consider expanding state handling capabilities.

As this is part of a React DSL implementation, consider enhancing the state translation to support:

  1. Complex state initializers (functions)
  2. Computed initial state
  3. Integration with state update functions
  4. Handling of lazy initialization patterns

This would provide better coverage of React's useState hook patterns.

Would you like me to provide examples of these advanced state handling patterns?

packages/react-generator/src/plugins/genRouterPlugin.js (2)

45-47: Address TODO comment regarding router modes.

The comment indicates missing support for hash and history modes, which are crucial router features.

Would you like me to help implement the router mode support or create an issue to track this enhancement?


73-81: Improve JSX formatting for better readability.

The generated JSX could be formatted better for maintainability.

- const routeSnippets = `<Routes> \n ${routes} \n </Routes>`
+ const routeSnippets = `
+   <Routes>
+     ${routes.join('\n    ')}
+   </Routes>
+ `
packages/toolbars/generate-react/src/Main.vue (2)

19-20: Remove commented-out code.

Since the Vue code generation functionality has been replaced with React, the commented import should be removed rather than left in the codebase.

 import { generateApp, generateBlocksCode, generateCode } from '@opentiny/tiny-engine-dsl-react'
-// import { generateVuePage, generateVueBlock } from './generateCode'

93-97: Remove debug console.log statements.

Production code should not contain debugging console.log statements. These should be removed before merging.

-      console.log(codeList, 'codelist>>>>>')
-      console.log(metaData, 'metaData>>>>>')
-      console.log(pageList, 'pageList>>>>>')
-      console.log(params, 'params>>>>>')
packages/settings/props/src/components/groups/LifeCycle.vue (2)

Line range hint 1-297: Consider internationalizing the component.

The component currently uses hardcoded Chinese text. Consider using a translation system for better internationalization support.

Example strings to internationalize:

  • "生命周期" (Lifecycle)
  • "提示" (Prompt)
  • "取 消" (Cancel)
  • "确 定" (Confirm)

Line range hint 166-182: Add code validation in the confirm handler.

The confirm function directly saves the editor content without validating if it's valid JavaScript/React code. Consider adding validation to prevent runtime errors.

 const confirm = () => {
   const editorValue = instance.refs.editor.getEditor().getValue()
+  try {
+    // Basic syntax validation
+    new Function(editorValue)
+  } catch (e) {
+    Modal.message({
+      message: `Invalid JavaScript: ${e.message}`,
+      status: 'error'
+    })
+    return
+  }
   const value = {
     type: 'js',
     source: editorValue
   }
   // ... rest of the function
 }
packages/toolbars/generate-vue/src/Main.vue (2)

2-3: Consider implementing internationalization for UI text.

The hardcoded Chinese text in the template should be moved to translation files for better maintainability and internationalization support.

-    content="生成当前应用代码到本地文件">
+    :content="t('generateCode.tooltip')">
  •  <tiny-select title="请选择出码产物" :options="state.options" v-model="state.value" size="small"
    
  •  <tiny-select :title="t('generateCode.selectFramework')" :options="state.options" v-model="state.value" size="small"
    


Also applies to: 8-9

---

Line range hint `266-271`: **Enhance error handling with specific error messages.**

The current error handling catches all errors and displays generic messages. Consider adding specific error handling for different types of failures (e.g., file system errors, generation errors).

```diff
       } catch (error) {
-        // eslint-disable-next-line no-console
-        console.error(error)
-        useNotify({ type: 'error', title: '代码生成失败', message: error?.message || error })
+        const errorMessage = this.getErrorMessage(error);
+        console.error('Code generation failed:', error);
+        useNotify({ 
+          type: 'error', 
+          title: t('generateCode.error.generation'),
+          message: errorMessage
+        });
         state.generating = false
       }

Add a helper method to handle specific error types:

const getErrorMessage = (error: unknown) => {
  if (error instanceof FileSystemError) {
    return t('generateCode.error.filesystem');
  }
  if (error instanceof GenerationError) {
    return t('generateCode.error.generation');
  }
  return error?.message || t('generateCode.error.unknown');
};

Also applies to: 290-295

packages/common/component/LifeCycles.vue (2)

Line range hint 247-343: Consider organizing styles using BEM methodology.

While the styles are functionally correct, consider organizing them using BEM (Block Element Modifier) methodology for better maintainability. This would help group related styles and reduce nesting.

Example reorganization for the popover list:

-.popover-list {
-  li {
-    padding: 8px 30px 8px 16px;
-    cursor: pointer;
-
-    &:hover {
-      background: var(--ti-lowcode-life-cycle-item-hover-bg);
-    }
-  }
-
-  .existed {
-    cursor: not-allowed;
-    pointer-events: none;
-    color: var(--ti-lowcode-life-cycle-item-disable-color);
-  }
-}
+.popover-list {}
+.popover-list__item {
+  padding: 8px 30px 8px 16px;
+  cursor: pointer;
+}
+.popover-list__item:hover {
+  background: var(--ti-lowcode-life-cycle-item-hover-bg);
+}
+.popover-list__item--existed {
+  cursor: not-allowed;
+  pointer-events: none;
+  color: var(--ti-lowcode-life-cycle-item-disable-color);
+}

Line range hint 1-359: Consider architectural improvements for better maintainability.

The component handles multiple responsibilities and could benefit from being split into smaller, more focused components:

  1. Extract the Monaco editor setup into a separate component with error boundaries
  2. Move the lifecycle list into its own component
  3. Consider adding TypeScript for better type safety

Would you like help with implementing any of these architectural improvements?

packages/react-generator/src/constant/index.js (3)

24-2172: Consider stricter version constraints

While version patterns are consistent within each package group, using caret (^) for all dependencies may lead to unexpected updates. For a more stable build:

  1. Consider using exact versions or tighter ranges for critical dependencies
  2. Document the tested version combinations
  3. Add a package-lock.json or yarn.lock to lock all dependency versions

Line range hint 1-13: Document component naming conventions

The file uses consistent prefixes for different component types:

  • 'Tiny' for OpenTiny components
  • 'Antd' for Ant Design components
  • 'Canvas' for built-in components

Consider adding JSDoc comments to document these naming conventions and their significance.

 /**
  * Copyright (c) 2023 - present TinyEngine Authors.
  * Copyright (c) 2023 - present Huawei Cloud Computing Technologies Co., Ltd.
  *
  * Use of this source code is governed by an MIT-style license.
  *
  * THE OPEN SOURCE SOFTWARE IN THIS PRODUCT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL,
  * BUT WITHOUT ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR
  * A PARTICULAR PURPOSE. SEE THE APPLICABLE LICENSES FOR MORE DETAILS.
  *
+ * @fileoverview Constants for component mappings and configurations
+ * 
+ * Component Naming Conventions:
+ * - TinyXxx: OpenTiny Vue components
+ * - AntdXxx: Ant Design React components
+ * - CanvasXxx: Built-in layout components
  */

Line range hint 2173-2186: Improve export declarations

Consider using named exports for all constants at their declaration point for better maintainability and to avoid the risk of forgetting to add new constants to the export list.

-const DEFAULT_COMPONENTS_MAP = [...]
+export const DEFAULT_COMPONENTS_MAP = [...]

-const BUILTIN_COMPONENTS_MAP = [...]
+export const BUILTIN_COMPONENTS_MAP = [...]

-const AntdComponents = [...]
+export const AntdComponents = [...]

-const BUILTIN_COMPONENT_NAME = {...}
+export const BUILTIN_COMPONENT_NAME = {...}

-const TINY_ICON = 'TinyIcon'
+export const TINY_ICON = 'TinyIcon'

-const UNWRAP_QUOTES = {...}
+export const UNWRAP_QUOTES = {...}

-const IntrinsicElements = [...]
+export const IntrinsicElements = [...]

-/**
- * 协议中的类型
- */
-export const [JS_EXPRESSION, JS_FUNCTION, JS_I18N, JS_RESOURCE, JS_SLOT] = [
+export const JS_EXPRESSION = 'JSExpression'
+export const JS_FUNCTION = 'JSFunction'
+export const JS_I18N = 'i18n'
+export const JS_RESOURCE = 'JSResource'
+export const JS_SLOT = 'JSSlot'
-  'JSExpression',
-  'JSFunction',
-  'i18n',
-  'JSResource',
-  'JSSlot'
-]

-export {
-  DEFAULT_COMPONENTS_MAP,
-  BUILTIN_COMPONENT_NAME,
-  TINY_ICON,
-  UNWRAP_QUOTES,
-  BUILTIN_COMPONENTS_MAP,
-  IntrinsicElements,
-  AntdComponents
-}
packages/react-generator/src/index.d.ts (3)

18-24: Inconsistent Placeholder Names in Mapped Types

In the IConfig interface, the placeholder names key and k are used inconsistently in the mapped types. For better readability and consistency, consider using a single placeholder name throughout, such as pluginName.

Apply this diff to improve consistency:

interface IConfig {
  customPlugins?: {
-    [key in defaultPlugins]?: IPluginFun
+    [pluginName in defaultPlugins]?: IPluginFun
  } & {
-    [key in 'transformStart' | 'transform' | 'transformEnd']?: Array<IPluginFun>
+    [pluginName in 'transformStart' | 'transform' | 'transformEnd']?: Array<IPluginFun>
  }
  pluginConfig?: {
-    [k in defaultPlugins]: Record<string, any>
+    [pluginName in defaultPlugins]: Record<string, any>
  }
  customContext?: Record<string, any>
}

76-76: Enhance Type Specificity for data Property in IDataSource

In the IDataSource interface, the data property within the list array is typed as object. For stronger type safety, consider specifying a more detailed type or using Record<string, any>.

Apply this diff to enhance type specificity:

 interface IDataSource {
   list: Array<{
     id: number
     name: string
-    data: object
+    data: Record<string, any>
   }>
   dataHandler?: IFuncType
   errorHandler?: IFuncType
   willFetch?: IFuncType
 }

132-137: Consistency in componentName Type Across Interfaces

In ISchemaChildrenItem, componentName is typed as string, whereas in IPageSchema, it's 'Page' | 'Block'. For consistency and type safety, consider defining componentName as a union type or referencing a shared type across interfaces.

Apply this diff to align the types:

 interface ISchemaChildrenItem {
   children: Array<ISchemaChildrenItem>
-  componentName: string
+  componentName: 'Page' | 'Block' | string
   id: string
   props: Record<string, any>
 }

Alternatively, define a shared type:

type ComponentName = 'Page' | 'Block' | string;

And update both interfaces to use ComponentName.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between bf63f8e and ebd1545.

⛔ Files ignored due to path filters (1)
  • mockServer/src/database/pages.db is excluded by !**/*.db
📒 Files selected for processing (17)
  • packages/common/component/LifeCycles.vue (6 hunks)
  • packages/design-core/config/lowcode.config.js (1 hunks)
  • packages/react-generator/src/constant/index.js (2 hunks)
  • packages/react-generator/src/generator/page.js (6 hunks)
  • packages/react-generator/src/index.d.ts (1 hunks)
  • packages/react-generator/src/parser/state.js (2 hunks)
  • packages/react-generator/src/plugins/genGlobalState.js (1 hunks)
  • packages/react-generator/src/plugins/genPagePlugin.js (1 hunks)
  • packages/react-generator/src/plugins/genRouterPlugin.js (1 hunks)
  • packages/react-generator/src/templates/react-templates/index.js (1 hunks)
  • packages/react-generator/src/templates/react-templates/template-files/src/App.jsx (1 hunks)
  • packages/react-generator/src/templates/react-templates/template-files/src/hooks/useLazy.jsx (1 hunks)
  • packages/settings/props/src/components/groups/LifeCycle.vue (6 hunks)
  • packages/toolbars/generate-react/index.js (1 hunks)
  • packages/toolbars/generate-react/src/Main.vue (2 hunks)
  • packages/toolbars/generate-vue/src/Main.vue (7 hunks)
  • packages/toolbars/generate-vue/src/generateCode.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/react-generator/src/plugins/genGlobalState.js
  • packages/react-generator/src/plugins/genPagePlugin.js
🧰 Additional context used
🪛 Biome
packages/react-generator/src/generator/page.js

[error] 425-425: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 428-430: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 431-431: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 433-435: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 437-439: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 444-447: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 451-453: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (19)
packages/react-generator/src/templates/react-templates/template-files/src/App.jsx (1)

11-11: LGTM!

The default export follows React conventions.

packages/react-generator/src/templates/react-templates/template-files/src/hooks/useLazy.jsx (1)

1-10: Verify template usage and SSR compatibility.

Since this is a template file, we should verify its integration with other templates and SSR compatibility.

Let's check how this hook is used across the template files:

✅ Verification successful

Let's gather more information about how useLazy is used in the template and check the Vite configuration for SSR settings.

This will help us understand:

  1. How the useLazy hook is integrated into the template generation process
  2. Whether there are any SSR-specific configurations that might conflict with the lazy loading implementation

Based on the gathered information, I can now provide the final response:

The useLazy hook implementation is safe to proceed

The verification shows that:

  • The hook is only used as a template file (useLazy.jsx) that gets copied to new projects
  • No direct usage of this hook exists in other template components
  • The Vite configuration is basic and doesn't include any SSR-specific settings that would conflict with the lazy loading implementation
  • The template system correctly includes this hook file in the generation process

The implementation is safe because:

  1. It follows React's recommended pattern for lazy loading
  2. The template is set up for client-side rendering (no SSR complications)
  3. The hook is properly isolated and made available for optional use in generated projects
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for potential SSR setup in templates
echo "Checking for SSR setup..."
rg -l "server|ssr|renderToString|hydrate" packages/react-generator/src/templates/

# Check for other uses of lazy loading in templates
echo "Checking for other lazy loading patterns..."
rg -l "React.lazy|lazy\(|Suspense" packages/react-generator/src/templates/

# Check if this hook is imported anywhere
echo "Checking for useLazy hook usage..."
rg -l "useLazy" packages/react-generator/src/templates/

Length of output: 788


Script:

#!/bin/bash
# Check the content of index.js to see how useLazy is used
echo "Content of index.js showing useLazy usage:"
rg -A 5 -B 5 "useLazy" packages/react-generator/src/templates/react-templates/index.js

# Check Vite config for SSR settings
echo -e "\nVite config content:"
cat packages/react-generator/src/templates/react-templates/template-files/genViteConfig.js

Length of output: 1515

packages/react-generator/src/parser/state.js (1)

52-52: LGTM!

The export statement correctly includes all necessary functions.

packages/design-core/config/lowcode.config.js (2)

100-100: ⚠️ Potential issue

Inconsistent handling of deprecated lifecycle methods

While componentWillReceiveProps is correctly commented out as deprecated, other deprecated methods like componentWillMount and componentWillUpdate are still included in the configuration.

Apply this diff to update the lifecycle methods according to React's current recommendations:

-      'componentWillMount',
       'componentDidMount',
-      // 'componentWillReceiveProps', // 被弃用了
       'shouldComponentUpdate',
-      'componentWillUpdate',
       'componentDidUpdate',
       'componentWillUnmount',
-      'getDerivedStateFromProps'
+      'static getDerivedStateFromProps',
+      'getSnapshotBeforeUpdate'

Likely invalid or redundant comment.


Line range hint 95-104: Consider modernizing the React configuration approach

The current configuration appears to be moving towards class components while modern React development emphasizes functional components with hooks. This might impact the developer experience and code maintainability.

Recommendations:

  1. Support both modern and legacy patterns but prioritize hooks-based development
  2. Add configuration options to control which patterns are available
  3. Consider adding documentation about the recommended patterns
  4. Include newer React features like:
    • Concurrent Mode lifecycle methods
    • Suspense boundaries
    • Error boundaries

Let's check if there are any React components already using these lifecycle methods:

packages/react-generator/src/plugins/genRouterPlugin.js (2)

1-6: LGTM! Clean imports and well-structured defaults.

The imports and default options are properly defined with clear, meaningful values.


20-24: Verify root route handling logic.

The current implementation might lead to undefined behavior if:

  1. No home route is defined
  2. The first route in the array is invalid
✅ Verification successful

Let me gather more information about the route handling logic to better understand the implementation.


Let me gather one more piece of information to understand how routes are processed before they reach the genRouterPlugin.


Based on the gathered information, I can now provide a final response:

Root route handling is safely implemented with fallback mechanism

The implementation has a proper fallback mechanism:

  • If no home route exists (isHome), it falls back to the first route's path
  • The root route (/) is only added if it doesn't already exist (!hasRoot)
  • Test cases show expected route generation with proper redirects (e.g., { path: '/', redirect: '/demopage' })
  • Route objects consistently include required path property as seen in the route generation code

The current implementation handles edge cases appropriately:

  1. When no home route is defined, it gracefully falls back to the first route
  2. Routes are generated with proper validation in the toolbars' generate code, ensuring valid route objects
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for route definitions to verify home route patterns
rg -A 5 "isHome.*=.*true" 

Length of output: 486


Script:

#!/bin/bash
# Search for route array construction and path definitions
rg -A 10 "routes\s*=\s*\[" 

# Search for route object definitions to understand their structure
ast-grep --pattern 'path: $_'

# Look for any test files related to router or routes
fd -e test.js -e spec.js router

Length of output: 3955


Script:

#!/bin/bash
# Look for route processing logic and how isHome is set
rg -B 5 -A 5 "routes\.find\(\{\s*isHome\s*\}\)"

# Check the test cases to see route configurations
fd -e js -e json "testcases" -x cat {}

Length of output: 90

packages/toolbars/generate-react/src/Main.vue (2)

2-3: LGTM! Template changes accurately reflect React integration.

The tooltip content has been appropriately updated to indicate React code generation, and the file selector integration remains clean and well-structured.

Also applies to: 10-11


Line range hint 134-141: Enhance error handling with detailed feedback.

While basic error handling exists, it could be improved to provide better user guidance and error tracking.

Consider implementing:

  1. Structured error types for different failure scenarios
  2. More descriptive error messages with recovery steps
  3. Error tracking integration

Example implementation:

try {
  // existing code
} catch (error) {
  const errorDetails = {
    context: 'Code Generation',
    operation: params.type,
    technical: error?.message || String(error)
  };
  
  // Log structured error for tracking
  console.error('Code generation failed:', errorDetails);
  
  // User-friendly notification with guidance
  useNotify({
    type: 'error',
    title: '代码生成失败',
    message: `
      无法生成代码。可能的原因:
      - 文件系统权限问题
      - 无效的页面配置
      请尝试刷新页面或联系支持团队。
    `.trim()
  });
  
  state.generating = false;
}
packages/settings/props/src/components/groups/LifeCycle.vue (3)

32-33: LGTM! Improved template formatting.

The consolidation of attributes improves readability while maintaining the same functionality.

Also applies to: 47-48


207-207: LGTM! Improved CSS readability.

The added spacing between CSS rules improves code readability.

Also applies to: 228-228, 278-278


120-120: Document the lifecycle hook template format.

The new default template ${state.title} (() => {}, []) appears to follow React hooks style, but the empty function and dependencies array might need explanation for other developers.

Let's verify if this format is consistent with other React lifecycle implementations:

✅ Verification successful

Let me try a different search pattern to verify the lifecycle hook implementations.

This should help us understand:

  1. Similar empty function patterns with dependency arrays
  2. React-style lifecycle hook usage
  3. Any documentation files related to lifecycle hooks

Let me check the content of the lifecycle-related files to understand the implementation pattern better.


Let me check the content of the LifeCycle.vue file specifically to understand the lifecycle hook implementation context better.


Let me check the lifecycle configuration in the lowcode config file to understand the supported lifecycle hooks.


Based on the gathered information, I can now provide a final response:

The lifecycle hook template format is correct and consistent with React's architecture.

The empty arrow function with dependencies array (() => {}, []) follows React's hooks pattern, particularly for effects. This is verified by:

  1. The codebase is configured for React DSL mode as shown in lowcode.config.js
  2. The config file lists React lifecycle hooks including component lifecycle methods
  3. The empty function and empty dependencies array is a valid pattern in React, representing an effect that:
    • Has no implementation yet (empty function)
    • Has no dependencies (empty array), meaning it will only run once on mount

The template serves as a good starting point for developers to implement their lifecycle logic, following React's conventions.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for similar lifecycle hook patterns
rg -g '!*.{json,md}' -A 2 '\(\s*\(\s*\)\s*=>\s*{\s*}\s*,\s*\[\s*\]\s*\)'

Length of output: 222


Script:

#!/bin/bash
# Search for lifecycle hook patterns in the codebase
rg -g '!*.{json,md}' "() => {.*}, \[\]"

# Look for any React-style lifecycle hooks or effects
ast-grep --pattern 'useEffect(() => {
  $$$
}, [$$$])'

# Search for files that might contain lifecycle documentation
fd -e md -e vue lifecycle

Length of output: 422


Script:

#!/bin/bash
# Check the content of both lifecycle files
echo "=== Content of LifeCycles.vue ==="
cat packages/common/component/LifeCycles.vue

echo -e "\n=== Content of LifeCycle.vue ==="
cat packages/settings/props/src/components/groups/LifeCycle.vue

# Try a different pattern to search for arrow functions with empty arrays
rg -g '!*.{json,md}' '\(\) => \{'

Length of output: 94580


Script:

#!/bin/bash
# Get the content around the specific line in LifeCycle.vue
rg -A 10 -B 10 "\`\$\{state\.title\} \(\(\) => \{\}, \[\]\)\`" packages/settings/props/src/components/groups/LifeCycle.vue

# Look for any lifecycle hook related configuration
rg -g '*.{js,ts}' "lifeCyclesOptions|lifeCycleTips"

Length of output: 309


Script:

#!/bin/bash
# Check the lifecycle configuration
cat packages/design-core/config/lowcode.config.js

# Also check if there are any lifecycle hook examples in the codebase
rg -g '!*.{json,md}' "onMounted|onBeforeMount|onUnmounted|onBeforeUnmount" -A 2

Length of output: 27818

packages/toolbars/generate-vue/src/Main.vue (1)

131-135: ⚠️ Potential issue

Fix semicolon placement to prevent ASI issues.

The current semicolon placement could lead to issues with JavaScript's Automatic Semicolon Insertion (ASI). The semicolon should be at the end of the previous line.

-        ; (await Promise.allSettled(extraList)).forEach((item) => {
+        (await Promise.allSettled(extraList)).forEach((item) => {

Likely invalid or redundant comment.

packages/common/component/LifeCycles.vue (1)

13-14: LGTM! Improved template formatting.

The reformatting of the v-for list item attributes improves code readability while maintaining the same functionality.

packages/toolbars/generate-vue/src/generateCode.js (1)

Line range hint 1-400: Architectural Concern: Vue Generator in React DSL PR.

This file is part of the Vue code generation system (generate-vue/), but the PR is focused on implementing React DSL. This raises several architectural concerns:

  1. If this is part of the Vue-to-React transition, consider:

    • Creating a separate React generator package instead of modifying Vue files
    • Implementing proper separation of concerns between Vue and React generators
    • Documenting the migration strategy
  2. If this is not part of the transition:

    • The changes to Vue generator files might be unintentional
    • The PR scope might need to be reviewed

Let's verify if this file should be part of the React DSL changes:

packages/react-generator/src/constant/index.js (1)

Line range hint 14-2172: Architectural Concern: Vue components in React DSL

The DEFAULT_COMPONENTS_MAP is importing components from @opentiny/vue and @opentiny/vue-icon, but this appears to be a React DSL project. Vue components cannot be directly used in React without proper adapters or rewrites.

Consider:

  1. Using React-specific versions of these components
  2. Creating React wrapper components
  3. Using the Ant Design components that are already defined in AntdComponents

Let's verify if there are React versions of these components:

packages/react-generator/src/generator/page.js (3)

163-163: Component Registration

Adding the componentName to description.componentSet ensures that all used components are properly registered. This change looks good.


407-414: Confirm Lifecycle Methods Handling

Ensure that all relevant lifecycle methods are correctly extracted and utilized. This includes componentDidMount, componentWillUnmount, componentDidUpdate, componentWillMount, and shouldComponentUpdate.

If everything is correct, the code changes look good.


386-387: ⚠️ Potential issue

Check Function Declaration Syntax

Ensure that the type variable contains the correct function syntax ('function' or an arrow function). The current code assumes type can be used directly, which may lead to incorrect function declarations.

Verify that type is correctly defined and adjust the function declaration accordingly.

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: 30

🧹 Outside diff range and nitpick comments (17)
packages/react-generator/src/templates/react-templates/template-files/genViteConfig.js (1)

1-4: Enhance code clarity and robustness

Consider the following improvements:

  1. Translate the Chinese comment to English for better accessibility
  2. Use a more descriptive variable name than processStr
  3. Consider using Vite's built-in loadEnv utility for environment variables

Apply this diff:

 export default () => {
-  // 避免在构建的时候,被 process. env 替换
-  const processStr = ['process', 'env']
+  // Prevent process.env substitution during build
+  const processEnvPath = ['process', 'env']
packages/toolbars/generate-vue/src/http.js (3)

14-15: Architectural concern: React code in Vue.js directory structure

The file is importing React generator code within a Vue.js directory structure (generate-vue). This mixing of frameworks could lead to confusion and maintenance issues.

Consider:

  1. Moving this file to a framework-agnostic location
  2. Creating separate files for React and Vue implementations
  3. Renaming the directory to reflect its multi-framework nature

22-30: Code organization: Clean up commented code

The file contains two versions of the same implementation (old and new), with extensive commenting. This makes the code harder to maintain and understand.

Consider:

  1. Remove the commented code if it's no longer needed
  2. If both implementations are needed, use a strategy pattern to switch between them instead of commenting/uncommenting code
-// export const fetchCode = async ({ platform, app, pageInfo, tenant } = {}) =>
-//   http.post(
-//     '/app-center/api/schema2code',
-//     { platform, app, pageInfo },
-//     {
-//       headers: { [HEADER_LOWCODE_ORG]: tenant }
-//     }
-//   )

export const fetchCode = async ({ platform, app, pageInfo, tenant } = {}) =>
  generateCode({ platform, app, pageInfo, tenant })
-// http.post(
-//   '/app-center/api/schema2code',
-//   { platform, app, pageInfo },
-//   {
-//     headers: { [HEADER_LOWCODE_ORG]: tenant }
-//   }
-// )

Also applies to: 31-39


14-39: Document framework transition strategy

The commented code and mixed imports suggest an ongoing transition from Vue to React, but the strategy isn't clear from the code alone.

Add a comment block explaining:

  1. The transition strategy
  2. How to switch between Vue and React implementations
  3. Timeline for deprecating the Vue implementation (if planned)
+/**
+ * Framework Transition Note:
+ * This file supports both Vue and React code generation as part of the Vue to React transition.
+ * To switch between implementations:
+ * 1. For React: Use the react-generator import
+ * 2. For Vue: Comment out react-generator and uncomment vue-generator import
+ * 
+ * TODO: Document deprecation timeline for Vue implementation
+ */
import { useHttp } from '@opentiny/tiny-engine-http'
import { generateCode } from '../../../react-generator/src/index'
// import { generateCode } from '../../../vue-generator/src/index'
packages/vue-generator/src/generator/vue/sfc/parseImport.js (1)

Line range hint 4-103: The existing functionality looks good, but clarify the PR scope.

The core functionality remains unchanged and well-structured. However, I have a strategic concern:

Given that this PR is titled "Ospp 2024/003 react dsl" and aims to introduce React DSL changes, could you explain:

  1. Why are we modifying Vue-generator files?
  2. Is this part of a larger refactoring effort that should be in a separate PR?
  3. Are there any plans to share code between Vue and React generators?

Consider:

  • If code sharing between Vue and React generators is intended, we might want to move shared utilities to a common package
  • If not, these Vue-generator changes might be better suited for a separate PR to maintain clear separation of concerns
packages/react-generator/src/plugins/genDependenciesPlugin.js (2)

1-7: Add error handling for utility imports

Consider adding try-catch blocks around the utility imports to gracefully handle cases where the required modules might be missing or corrupted.

+try {
  import { mergeOptions } from '../utils/mergeOptions'
  import { parseImport } from '../generator/parseImport'
+} catch (error) {
+  console.error('Failed to load required utilities:', error)
+  throw new Error('Dependencies plugin initialization failed')
+}

48-48: Translate Chinese comment to English

The Chinese comment should be translated to maintain code consistency.

-// 处理内置 Icon,如果使用了 tinyreact 组件,则默认添加 @opentiny/react-icon 依赖,且依赖与 @opentiny/react 依赖版本一致
+// Handle built-in Icon: If tinyreact components are used, automatically add @opentiny/react-icon dependency with the same version as @opentiny/react
packages/react-generator/src/plugins/genGlobalState.js (2)

8-16: Add JSDoc documentation for the parseSchema function.

The function handles schema parsing well, but adding documentation would improve maintainability.

+/**
+ * Extracts and validates the globalState from the schema
+ * @param {Object} schema - The input schema object
+ * @returns {Array} The globalState array, empty if not found or invalid
+ */
 const parseSchema = (schema) => {

33-79: Consider making the default stores configurable.

Currently, the plugin hardcodes two stores (counter and user) which limits its flexibility. Consider:

  1. Moving default stores to a configuration file
  2. Making them optional
  3. Allowing users to provide their own default store templates

Example configuration approach:

// defaultStores.js
export const defaultStores = {
  counter: {
    state: { count: 0 },
    actions: {
      increment: { type: 'JSFunction', value: 'function increment() { this.state.count++; }' }
      // ...
    }
  }
  // ... other default stores
}

// In genGlobalState.js
const realOptions = mergeOptions(defaultOption, {
  defaultStores: [],  // Allow users to override default stores
  ...options
})
packages/vue-generator/src/generator/vue/sfc/genSetupSFC.js (1)

Line range hint 1-275: Well-structured and extensible architecture.

The code demonstrates good architectural patterns:

  • Clear separation of concerns with template, script, and style generation
  • Flexible hook system for customization
  • Comprehensive configuration options
  • Good state management through the globalHooks system

Consider adding JSDoc documentation for the main functions and hooks to improve maintainability.

packages/toolbars/generate-vue/src/Main.vue (3)

2-3: Internationalize UI text strings.

The UI text strings are hardcoded in Chinese. Consider using i18n translations for better maintainability and global accessibility.

-    content="生成当前应用代码到本地文件">
+    :content="t('generateCode.tooltip')">
...
-      <tiny-select title="请选择出码产物"
+      <tiny-select :title="t('generateCode.selectFramework')"

Also applies to: 8-9


132-136: Remove unnecessary semicolon before array spread.

The semicolon before the array spread operation is unnecessary and affects code readability.

-      ; (await Promise.allSettled(extraList)).forEach((item) => {
+      (await Promise.allSettled(extraList)).forEach((item) => {

158-160: Remove commented-out code.

Remove commented-out HTTP calls as they add noise to the codebase. If these are needed for reference, consider documenting them elsewhere.

-        // useHttp().get(`/app-center/v1/api/apps/schema/${id}`),
         fetchBlockSchema(params),
-        // state.value === 'React' ? fetchBlockSchema(params) : useHttp().get(`/app-center/v1/api/apps/schema/${id}`),
packages/react-generator/src/constant/index.js (3)

14-16: Consider enhancing the documentation.

While the comment indicates this maps to React components, it would be helpful to add:

  • A brief description of how these mappings are used in code generation
  • Any requirements or constraints for adding new mappings
  • Examples of how to use these mappings

Line range hint 2197-2338: Consider standardizing the component mapping schema.

The Ant Design component mappings introduce a subName property not present in other mappings. This inconsistency could cause issues in the code generator.

Consider:

  1. Documenting the subName property's purpose
  2. Adding subName support to other component types if needed
  3. Creating a TypeScript interface to enforce consistent mapping structure

Example TypeScript interface:

interface ComponentMapping {
  componentName: string;
  exportName: string;
  package: string;
  version: string;
  destructuring: boolean;
  subName?: string; // Optional for components like Radio.Group
}

Line range hint 2339-2452: Consider improving constant organization and documentation.

The utility constants section could be improved by:

  1. Grouping related constants into separate files (e.g., move IntrinsicElements to a separate file)
  2. Adding JSDoc comments to explain the purpose and usage of each constant
  3. Using TypeScript enums or const assertions for better type safety

Example improved documentation:

/**
 * Built-in component names used by the code generator.
 * These names are reserved and may require special handling during code generation.
 * @enum {string}
 */
export const BUILTIN_COMPONENT_NAME = {
  /** Root page component */
  PAGE: 'Page',
  /** Reusable block component */
  BLOCK: 'Block',
  // ... other components
} as const;
packages/react-generator/src/generator/generateJsx.js (1)

148-154: Rename hasExists to existingDependency for clarity

The variable hasExists might be misleading. Renaming it to existingDependency would improve readability and better reflect its purpose.

Here's the suggested change:

-        const hasExists = dependenciesMap.find(({ destructuring, exportName, componentName }) => {
+        const existingDependency = dependenciesMap.find(({ destructuring, exportName, componentName }) => {
           return (
             destructuring === config.destructuring &&
             exportName === config.exportName &&
             componentName === config.componentName
           )
         })
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between ebd1545 and 267c62b.

⛔ Files ignored due to path filters (1)
  • mockServer/src/database/pages.db is excluded by !**/*.db
📒 Files selected for processing (31)
  • mockServer/src/mock/get/app-center/v1/apps/schema/918.json (3 hunks)
  • mockServer/src/services/appinfo.json (114 hunks)
  • packages/react-generator/src/constant/index.js (1 hunks)
  • packages/react-generator/src/generator/generateJsx.js (1 hunks)
  • packages/react-generator/src/generator/page.js (6 hunks)
  • packages/react-generator/src/plugins/genDependenciesPlugin.js (1 hunks)
  • packages/react-generator/src/plugins/genGlobalState.js (1 hunks)
  • packages/react-generator/src/plugins/genPagePlugin.js (1 hunks)
  • packages/react-generator/src/templates/react-templates/template-files/README.md (1 hunks)
  • packages/react-generator/src/templates/react-templates/template-files/genViteConfig.js (1 hunks)
  • packages/react-generator/src/templates/react-templates/template-files/packageJson.js (1 hunks)
  • packages/react-generator/test/testcases/full/case1_normal/input/components-map.json (2 hunks)
  • packages/toolbars/generate-vue/src/Main.vue (7 hunks)
  • packages/toolbars/generate-vue/src/http.js (1 hunks)
  • packages/vue-generator/src/generator/vue/sfc/genSetupSFC.js (5 hunks)
  • packages/vue-generator/src/generator/vue/sfc/generateAttribute.js (2 hunks)
  • packages/vue-generator/src/generator/vue/sfc/generateScript.js (1 hunks)
  • packages/vue-generator/src/generator/vue/sfc/generateTemplate.js (3 hunks)
  • packages/vue-generator/src/generator/vue/sfc/parseImport.js (1 hunks)
  • packages/vue-generator/src/plugins/genDependenciesPlugin.js (1 hunks)
  • packages/vue-generator/src/plugins/genGlobalState.js (1 hunks)
  • packages/vue-generator/src/plugins/genPagePlugin.js (1 hunks)
  • packages/vue-generator/src/plugins/parseSchemaPlugin.js (1 hunks)
  • packages/vue-generator/test/testcases/generator/mockData.js (1 hunks)
  • packages/vue-generator/test/testcases/sfc/case01/case01.test.js (1 hunks)
  • packages/vue-generator/test/testcases/sfc/case02/case02.test.js (1 hunks)
  • packages/vue-generator/test/testcases/sfc/case03/case03.test.js (1 hunks)
  • packages/vue-generator/test/testcases/sfc/case04/case04.test.js (1 hunks)
  • packages/vue-generator/test/testcases/sfc/case05/case05.test.js (1 hunks)
  • packages/vue-generator/test/unit/hasJSX.test.js (1 hunks)
  • packages/vue-generator/test/unit/parseRequiredBlocks.test.js (1 hunks)
✅ Files skipped from review due to trivial changes (7)
  • mockServer/src/mock/get/app-center/v1/apps/schema/918.json
  • mockServer/src/services/appinfo.json
  • packages/react-generator/src/templates/react-templates/template-files/README.md
  • packages/vue-generator/src/generator/vue/sfc/generateAttribute.js
  • packages/vue-generator/src/generator/vue/sfc/generateTemplate.js
  • packages/vue-generator/src/plugins/genDependenciesPlugin.js
  • packages/vue-generator/src/plugins/parseSchemaPlugin.js
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/react-generator/src/plugins/genPagePlugin.js
  • packages/react-generator/src/templates/react-templates/template-files/packageJson.js
🧰 Additional context used
🪛 Biome
packages/react-generator/src/generator/page.js

[error] 424-424: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 428-429: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 430-430: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 432-434: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 436-438: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 443-446: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 450-454: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (23)
packages/vue-generator/test/testcases/sfc/case05/case05.test.js (1)

5-5: Verify consistent import path updates across test files.

The AI summary indicates similar changes were made in other test files. Let's verify this for consistency.

✅ Verification successful

All test files consistently use the same import path pattern

The verification shows that all test files under packages/vue-generator/test/testcases/sfc/ consistently use the same relative import path ../../../../src/utils/formatCode for importing the formatCode utility. This confirms proper consistency across the test suite.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if all test files have been updated consistently
# Expected: All formatCode imports should use the same relative path pattern

# Search for formatCode imports in test files
echo "Checking formatCode imports in test files:"
rg "import.*formatCode.*from.*" "packages/vue-generator/test"

Length of output: 786

packages/react-generator/test/testcases/full/case1_normal/input/components-map.json (2)

5-7: Verify React component compatibility.

The package change from @opentiny/vue to @opentiny/react for TinyButton aligns with the project's Vue to React transition. However, we should ensure compatibility.


Line range hint 1-28: Consider updating other @opentiny components.

Since TinyButton has been migrated to React, consider reviewing if other components in this map (like FormTable, ImageTitle) should also be updated for React compatibility.

packages/react-generator/src/templates/react-templates/template-files/genViteConfig.js (1)

5-28: Consider adding essential Vite configurations

The current configuration might be insufficient for a production React application. Consider adding:

  1. TypeScript support configuration
  2. CORS settings for development
  3. Build optimization options
  4. Proxy configuration for API requests

Let's check if this is a TypeScript project:

packages/vue-generator/test/testcases/sfc/case02/case02.test.js (2)

6-6: Verify the impact of the import path change.

The import path has been changed from an alias-based import (@/utils/formatCode) to a relative path. This might affect module resolution and build configurations.

✅ Verification successful

Based on the results, I can generate the final response as we have sufficient information. The search results show that:

  1. Path aliases with @/ are configured in multiple configuration files
  2. All test files consistently use relative paths (../../../../src/utils/formatCode) to import the formatCode utility

The change from alias to relative path is consistent with other test files

The modification aligns with the existing pattern in the codebase where all test files under packages/vue-generator/test/testcases/sfc/ use the same relative path ../../../../src/utils/formatCode to import the formatCode utility. This change actually improves consistency rather than introducing any issues.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for the presence of path alias configurations
echo "Checking for path alias configurations..."
fd -t f "vite.config|tsconfig|jsconfig|package.json" -x cat {} \; | rg -A 5 "@/"

# Check if formatCode utility is used consistently across the codebase
echo "Checking formatCode import patterns..."
rg -A 1 "import.*formatCode"

Length of output: 1889


6-6: Verify the relevance of Vue generator changes in React DSL PR.

This change appears in a Vue generator test file, but the PR is focused on React DSL implementation. Please clarify why modifications to Vue-related code are necessary for this React DSL feature.

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

6-6: 🛠️ Refactor suggestion

Consider maintaining alias-based imports for better maintainability.

The change from @/utils/formatCode to a deep relative path ../../../../src/utils/formatCode makes the imports more brittle and harder to maintain. Deep relative paths are sensitive to file moves and directory restructuring.

Consider either:

  1. Retaining the alias-based import:
-import { formatCode } from '../../../../src/utils/formatCode'
+import { formatCode } from '@/utils/formatCode'
  1. Or if moving away from aliases, restructuring the test directory layout to reduce path depth.

Let's verify the consistency of import patterns across test files:

packages/vue-generator/src/plugins/genPagePlugin.js (1)

Line range hint 1-43: Verify the architectural decision to modify Vue generator.

This file is part of the vue-generator package, but the PR objectives indicate this is for implementing React DSL support. This seems architecturally inconsistent.

Let's verify if this is the correct location for these changes:

Consider:

  1. Creating a separate react-generator package instead of modifying Vue-specific code
  2. If vue-generator is being repurposed, it should be renamed and refactored properly
  3. Document the architectural decision if there's a specific reason for this approach
packages/vue-generator/test/unit/parseRequiredBlocks.test.js (2)

Line range hint 4-41: Test coverage looks comprehensive.

The test cases effectively cover:

  1. Edge cases with non-array inputs
  2. Deep recursive parsing of nested block components

2-2: LGTM! Import path update looks correct.

The change from alias to relative path maintains the same reference while potentially improving portability.

Let's verify the consistency of import path changes across related test files:

✅ Verification successful

Import path update is consistent and correctly mapped

The verification confirms:

  • No remaining @/utils/parseRequiredBlocks alias imports found in test files
  • Target utility file exists at the expected location: packages/vue-generator/src/utils/parseRequiredBlocks.js
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining alias imports in test files
# and verify the existence of the target utility file

# Test 1: Check if there are any remaining @/ aliases in test files
echo "Checking for remaining alias imports in test files..."
rg "@/utils/parseRequiredBlocks" "packages/vue-generator/test"

# Test 2: Verify the target utility file exists at the new relative path
echo "Verifying target utility file exists..."
fd "parseRequiredBlocks.js" "packages/vue-generator/src/utils"

Length of output: 383

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

Line range hint 1-42: LGTM! Test implementation remains solid

The test implementation is well-structured with:

  • Consistent snapshot testing approach
  • Deterministic random value mocking
  • Clear test cases for both regular and block components
packages/vue-generator/test/unit/hasJSX.test.js (2)

Line range hint 1-45: Consider architectural implications of sharing JSX utilities.

Given that this JSX detection utility is in the vue-generator package but the PR is introducing React DSL support, we should consider:

  1. Whether this utility should be moved to a shared package
  2. If Vue and React generators should have separate implementations
  3. The potential differences in JSX handling between Vue and React

Consider extracting the JSX detection utility to a shared package (e.g., @tiny-engine/shared-utils) if it's meant to be used by both Vue and React generators. This would:

  • Make the shared nature of the utility explicit
  • Prevent potential divergence in JSX detection logic
  • Simplify maintenance when JSX parsing needs to be updated
#!/bin/bash
# Description: Check if JSX utility is already used across different packages
# Expected: Usage patterns will help determine if it should be shared

# Check for hasJsx imports across all packages
echo "Checking for hasJsx usage across packages:"
rg "import.*hasJsx" "packages/"

# Check for JSX-related utilities in other packages
echo -e "\nChecking for other JSX-related files:"
fd -e js -e ts "jsx|JSX" "packages/"

2-2: Verify the import path convention across the project.

The change from alias-based import (@/utils/hasJsx) to relative path (../../src/utils/hasJsx) might deviate from project conventions.

✅ Verification successful

Let me gather more information about the import patterns in the project to make a definitive decision.


Based on the analysis of import patterns across the codebase, I can now provide a final response:

The relative import path change is consistent with project conventions

Looking at the test files in the vue-generator package, relative imports (../../) are consistently used for importing from the src directory, while @/ alias is only used in a few specific test cases. The change from @/utils/hasJsx to ../../src/utils/hasJsx aligns with the predominant pattern in the test files.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check import path conventions in test files
# Expected: Consistent usage of either alias-based or relative imports

# Check for alias-based imports in test files
echo "Checking for alias-based imports (@/):"
rg "from '@/" "packages/*/test"

# Check for relative path imports in test files
echo -e "\nChecking for relative imports (../../):"
rg "from '\.\./\.\." "packages/*/test"

Length of output: 602


Script:

#!/bin/bash
# Check import patterns in vue-generator package tests
echo "Import patterns in vue-generator test files:"
rg "^import.*from" "packages/vue-generator/test" -A 1

# Check import patterns in react-generator package tests
echo -e "\nImport patterns in react-generator test files:"
rg "^import.*from" "packages/react-generator/test" -A 1

# Check if there's any webpack/jest config that might define path aliases
echo -e "\nChecking for config files that might define aliases:"
fd -e js -e json "jest.config|webpack.config|tsconfig" packages/

Length of output: 22739

packages/vue-generator/src/plugins/genGlobalState.js (2)

60-62: Verify type validation for getters and actions.

The current implementation only checks for type === 'JSFunction' but might need additional validation to ensure the function content is safe and well-formed.

✅ Verification successful

Let me gather more specific information about the validation context and usage.


Based on the gathered information, I can now provide the final response:

The type validation for getters and actions is sufficient in this context.

The current implementation's check for type === 'JSFunction' is appropriate because:

  • The type check is consistently used across the codebase for both getters and actions
  • The validation is part of a filtering mechanism that ensures only function-type values are processed
  • The function content safety is handled by the Vue framework's runtime checks and the existing code transformation logic that properly formats the function content (as seen in the surrounding code that processes value.value)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Look for type validation patterns across the codebase
# Search for validation utilities or similar type checking patterns

# Check for validation utilities
rg "type.*validation|validateFunction|validateSchema" 

# Look for JSFunction type usage
ast-grep --pattern 'type === "JSFunction"'

Length of output: 611


Script:

#!/bin/bash
# Check the implementation context of genGlobalState
rg -A 5 -B 5 "JSFunction" packages/vue-generator/src/plugins/genGlobalState.js

# Look for any type validation or schema validation in vue-generator
rg -A 3 "type.*=|type.*validation" packages/vue-generator/src/

# Check if there are any existing validation utilities
fd validation packages/vue-generator/src/

Length of output: 29299


60-62: Verify the necessity of Vue generator changes in React DSL PR.

This file is part of the Vue generator package, but the PR is focused on React DSL changes. Please clarify why modifications to Vue-specific code are necessary in this context.

✅ Verification successful

Based on the gathered information, I can now provide the final response:

The changes to Vue generator are part of a unified state management implementation

The modification to the filter condition in the Vue generator is valid as both React and Vue generators share a common schema structure for state management where functions are typed as JSFunction. This is evidenced by:

  • Both generators handle global state with similar patterns (Vue using Pinia, React using Zustand)
  • The JSFunction type is consistently used across both generators for methods, actions, and getters
  • The change is part of a commit that specifically addresses state management code generation
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if this change is part of a larger refactoring affecting both Vue and React generators
# Look for similar patterns in React generator files

# Search for similar state management patterns in React files
rg -g "packages/react-generator/**" -A 5 "defineStore|globalState"

# Check for shared utilities or common patterns
rg -g "packages/{react,vue}-generator/**" -l "genGlobalState|stateManagement"

Length of output: 611


Script:

#!/bin/bash
# Let's examine the actual implementation and usage patterns in both generators

# Check the implementation in React generator
rg -g "packages/react-generator/**" -A 10 "JSFunction"

# Look for shared types or interfaces that might be used across generators
rg -g "packages/**" -A 5 "type.*JSFunction|interface.*JSFunction"

# Check the git history of the Vue generator file to understand the context
git log -p packages/vue-generator/src/plugins/genGlobalState.js

# Examine the imports in both generators to check for shared dependencies
rg -g "packages/{react,vue}-generator/**" "^import.*from.*@"

Length of output: 87615

packages/vue-generator/src/generator/vue/sfc/parseImport.js (1)

1-2: Verify the scope and necessity of these changes in vue-generator.

While the import path changes align with similar modifications across other files, I have some concerns:

  1. This file is in the vue-generator package, but the PR is focused on React DSL implementation. Could you clarify why these changes are necessary in the Vue-related code?
  2. The deep relative paths (../../../) might make the code more susceptible to breaking during future refactoring.

Let's check if these changes are part of a broader pattern:

packages/react-generator/src/plugins/genGlobalState.js (1)

166-166: LGTM!

The export statement is clean and follows best practices.

packages/vue-generator/src/generator/vue/sfc/genSetupSFC.js (1)

9-9: Verify the necessity of adding the .js extension.

Adding explicit .js extensions to imports is usually unnecessary and might cause issues with certain bundlers. If this is part of an ESM migration, consider documenting this requirement.

packages/react-generator/src/generator/page.js (2)

67-68: ⚠️ Potential issue

Remove debug console.log statement.

Remove the console.log statement to keep the production code clean.

    const eventHandler = item.value.replace('this.', '')
-    console.log(item, 'eventHandler>>>>>.')

Likely invalid or redundant comment.


434-439: ⚠️ Potential issue

Remove debug console.log statements.

Remove all console.log statements to keep the production code clean.

-  console.log(getters.join('\n'), 'current>>>>>>')
-  console.log(arrowMethods.join('\n'), 'arrowMethod>>>>>>')
-  console.log(statement, 'stateStatement>>>>>>')

Likely invalid or redundant comment.

🧰 Tools
🪛 Biome

[error] 436-438: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

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

2129-2129: Function name typo fix looks good.

The correction of dataHanlder to dataHandler improves code consistency.

#!/bin/bash
# Description: Check for any remaining instances of the misspelled function name
# Test: Search for 'dataHanlder' to ensure all instances are fixed
rg 'dataHanlder'

2129-2129: Verify the usage of new global state variable.

The addition of 'fishThing' to global_state array may require corresponding state management implementation in components that use this global state.

✅ Verification successful

Let me try another search to find references to 'fishThing' specifically:


Let's check the actual context where 'fishThing' is used in these files:


No issues with the global state variable addition

The addition of 'fishThing' to global_state array is consistent across the test mock data and corresponding mock server files. This appears to be a valid test case setup where the mock data matches the expected server response schema, and doesn't require additional implementation since it's contained within test fixtures.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for usage of the new global state variable 'fishThing'
# Test: Look for references to 'fishThing' in component files
rg -l 'fishThing'

Length of output: 3692


Script:

#!/bin/bash
# Search for any references to 'fishThing' in the codebase
rg -l "fishThing"

Length of output: 173


Script:

#!/bin/bash
# Get the context around 'fishThing' usage
rg "fishThing" -C 5

Length of output: 2546

packages/react-generator/src/constant/index.js (1)

Line range hint 2172-2196: Consider version alignment strategy.

The built-in components use version ^0.1.0 while the default components use ^3.10.0. This version disparity might indicate:

  1. These components are in early development
  2. Potential compatibility issues between different package versions

Consider:

  • Documenting why these versions differ
  • Whether these versions should be aligned
  • Adding a comment explaining the version strategy

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: 9

🧹 Outside diff range and nitpick comments (4)
packages/react-generator/src/plugins/genPagePlugin.js (2)

3-3: Remove commented-out import if unused.

The commented import genSFCWithDefaultPlugin appears to be unused. If it's no longer needed, consider removing it to maintain clean code.


5-7: Consider making the page path more configurable.

The hardcoded path './src/views' might not accommodate different project structures. Consider:

  1. Making it more flexible by allowing environment variables or configuration files to override it
  2. Adding more configuration options like file extensions, component naming conventions, etc.
packages/toolbars/generate-react/src/Main.vue (1)

2-3: Consider internationalizing the popover content.

The popover content is hardcoded in Chinese ("生成当前页面/区块的React代码到本地文件"). Consider using an i18n system to support multiple languages.

-    content="生成当前页面/区块的React代码到本地文件">
+    :content="t('generate.react.tooltip')">
packages/react-generator/src/generator/page.js (1)

190-190: Improve documentation for state access transformation.

The comment "改写类语法" (rewriting class syntax) could be more explicit about the transformation from class component state access to hooks.

-    const loopData = (loop.type ? loop.value : JSON.stringify(loop)).replace('this.state.', '') // 改写类语法
+    const loopData = (loop.type ? loop.value : JSON.stringify(loop)).replace('this.state.', '') // Transform class component state access pattern to hooks pattern
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 267c62b and 326e736.

📒 Files selected for processing (4)
  • packages/react-generator/src/generator/page.js (8 hunks)
  • packages/react-generator/src/plugins/genPagePlugin.js (1 hunks)
  • packages/toolbars/generate-react/src/Main.vue (2 hunks)
  • packages/utils/src/fs/index.js (2 hunks)
🧰 Additional context used
🪛 Biome
packages/react-generator/src/generator/page.js

[error] 424-424: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 428-429: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 430-430: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 432-434: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 436-438: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 443-446: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 450-454: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (6)
packages/react-generator/src/plugins/genPagePlugin.js (2)

49-49: LGTM!

The export statement follows the standard module.exports pattern.


1-49: Verify plugin integration and consistency.

Let's verify the plugin's integration and identify similar patterns that might need improvement.

✅ Verification successful

Plugin structure and path handling are consistent across the codebase

The verification shows:

  • The plugin follows the same structure as other plugins in both React and Vue generators
  • Hardcoded paths are consistently used across all plugins with similar patterns:
    • genPagePlugin uses ./src/views
    • genBlockPlugin uses ./src/components
    • genRouterPlugin uses ./src/router
    • genI18nPlugin uses ./src/i18n
  • The plugin is properly integrated and used in both React and Vue generators via their respective generateApp.js files with consistent configuration patterns
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check plugin structure consistency and usage

# Test 1: Find similar plugins to ensure consistent structure
echo "Checking for similar plugins..."
ast-grep --pattern 'function $PLUGIN_NAME($_) {
  $$$
  return {
    name: $_,
    description: $_,
    run($_) {
      $$$
    }
  }
}'

# Test 2: Check for hardcoded paths that might need similar improvements
echo "Checking for hardcoded paths..."
rg -g '*.js' -g '*.ts' "'\./src/[^']*'"

# Test 3: Find plugin usage to verify integration
echo "Checking plugin usage..."
rg "genPagePlugin" -A 5

Length of output: 12179

packages/utils/src/fs/index.js (1)

2-11: LGTM: License header is properly formatted and attributed.

The copyright notices and MIT license header are correctly structured with appropriate attributions.

packages/toolbars/generate-react/src/Main.vue (1)

Line range hint 126-140: Enhance error handling with structured errors.

Building upon the previous review comment about error handling:

  1. Consider creating specific error types for different failure scenarios.
  2. Add error tracking or monitoring integration.
  3. Include more context in error messages.
+      class CodeGenerationError extends Error {
+        constructor(stage, message, originalError = null) {
+          super(`Failed during ${stage}: ${message}`);
+          this.stage = stage;
+          this.originalError = originalError;
+        }
+      }
+
       try {
         // 保存代码前置任务:调用接口生成代码并获取用户本地文件夹授权
         const [params, codeList, metaData, pageList, dirHandle] = await getPreGenerateInfo()
         // ...
       } catch (error) {
-        // eslint-disable-next-line no-console
-        console.error(error)
-        useNotify({ type: 'error', title: '代码生成失败', message: error?.message || error })
+        const genError = error instanceof CodeGenerationError ? error : 
+          new CodeGenerationError('unknown', error?.message || 'Unknown error', error);
+        console.error('Code generation failed:', {
+          stage: genError.stage,
+          message: genError.message,
+          originalError: genError.originalError
+        });
+        useNotify({ 
+          type: 'error',
+          title: `代码生成失败 (${genError.stage})`,
+          message: genError.message
+        });
       }
packages/react-generator/src/generator/page.js (2)

367-372: Previous optimization suggestion still applies.


443-460: Previous export syntax suggestion still applies.

🧰 Tools
🪛 Biome

[error] 443-446: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 450-454: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

packages/react-generator/src/plugins/genPagePlugin.js Outdated Show resolved Hide resolved
packages/utils/src/fs/index.js Outdated Show resolved Hide resolved
packages/utils/src/fs/index.js Outdated Show resolved Hide resolved
packages/toolbars/generate-react/src/Main.vue Outdated Show resolved Hide resolved
packages/toolbars/generate-react/src/Main.vue Outdated Show resolved Hide resolved
packages/react-generator/src/generator/page.js Outdated Show resolved Hide resolved
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: 18

🧹 Outside diff range and nitpick comments (13)
packages/react-generator/src/plugins/genUtilsPlugin.js (3)

21-25: Simplify subName assignment logic.

The current implementation can be simplified using a more concise approach.

-    let realExportName = exportName
-
-    if (subName) {
-      realExportName = subName
-    }
+    const realExportName = subName || exportName

78-82: Improve file content template formatting.

The current template might produce inconsistent spacing. Consider using a more structured approach.

-      const fileContent = `
-${importStatements.join('\n')}
-${variableStatements.join('\n')}
-export { ${exportVariables.join(',')} }
-`
+      const fileContent = [
+        importStatements.join('\n'),
+        '',
+        variableStatements.join('\n'),
+        '',
+        `export { ${exportVariables.join(', ')} }`,
+        ''
+      ].join('\n')

45-49: Update documentation language and types.

The comments need the following changes:

  1. Translate Chinese comments to English
  2. Update type annotation to reference React DSL instead of Vue
-    /**
-     * 生成 utils 源码
-     * @param {tinyEngineDslVue.IAppSchema} schema
-     * @returns
-     */
+    /**
+     * Generate utility source code from schema
+     * @param {tinyEngineDslReact.IAppSchema} schema
+     * @returns {Object} Generated file information
+     */
packages/react-generator/src/plugins/genRouterPlugin.js (3)

38-41: Translate JSDoc comments to English.

For better international collaboration, JSDoc comments should be in English.

-     * 根据页面生成路由配置
+     * Generate router configuration based on page schema
      * @param {tinyEngineDslVue.IAppSchema} schema
      * @returns

35-35: Consider using a more conventional plugin name.

The current plugin name uses camelCase and hyphens inconsistently.

-    name: 'tinyEngine-generateCode-plugin-router',
+    name: 'tiny-engine-router-generator',

45-45: Document router mode requirements in TODO.

The TODO comment should be more specific about the requirements and acceptance criteria for different router modes.

-      // TODO: 支持 hash 模式、history 模式
+      // TODO: Add support for hash and history router modes
+      // Requirements:
+      // 1. Allow configuration of router mode via options
+      // 2. Generate appropriate router setup code for each mode
+      // 3. Update imports and configuration accordingly
packages/toolbars/generate-react/src/Main.vue (3)

2-3: Consider internationalizing the tooltip text.

The hardcoded Chinese text "生成当前页面/区块的React代码到本地文件" should be moved to an i18n system for better maintainability and internationalization support.

-    content="生成当前页面/区块的React代码到本地文件">
+    :content="t('generate.tooltip')">

94-99: Clarify the architectural approach for React generation.

There are multiple commented options for the Page handler (generateApp vs generateCode). This suggests uncertainty about the architectural approach.

Please clarify which approach should be used:

  1. If generateApp is for full application generation and generateCode is for single page generation, consider supporting both:
 const handlers = {
-  Block: generateVueBlock,
-  Page: generateVuePage
-  // Page: generateApp
-  // Page: generateCode
+  Block: generateBlocksCode,
+  Page: generateCode,
+  Application: generateApp
 }

Line range hint 119-146: Improve loading state management during code generation.

The current implementation uses a boolean generating flag, but the UI could benefit from more granular loading states to show progress during the multi-step generation process.

Consider using an enum for generation states:

enum GenerationState {
  IDLE = 'idle',
  FETCHING_DATA = 'fetching_data',
  GENERATING_CODE = 'generating_code',
  SAVING_FILES = 'saving_files'
}

Then update the state management:

 const state = reactive({
   dirHandle: null,
-  generating: false,
+  generationState: GenerationState.IDLE,
   showDialogbox: false,
   saveFilesInfo: []
 })

This would allow for more informative progress indicators in the UI.

packages/react-generator/src/generator/page.js (1)

440-457: Consider adding prop-types or TypeScript for better type safety.

The functional component could benefit from runtime type checking using PropTypes or TypeScript interfaces.

Example implementation:

import PropTypes from 'prop-types';

const ${name} = () => {
  // ... component implementation
}

${name}.propTypes = {
  // Add prop type definitions here
};

export default ${name};
🧰 Tools
🪛 Biome

[error] 443-447: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 449-454: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

packages/react-generator/src/constant/index.js (2)

14-15: Update comment to reflect React naming conventions

The current comment doesn't provide clear guidance on React-specific naming conventions. Consider adding information about:

  • PascalCase for component names
  • Prefix conventions
  • Handling of sub-components

Update the comment to:

- * 组件映射关系,默认使用 Tiny React 组件,支持传入其它组件库的映射关系(tiny react如今只有两个组件)
+ /**
+  * Component mapping for Tiny React components with support for external component libraries.
+  * Naming conventions:
+  * - Use PascalCase for component names
+  * - Prefix Tiny components with 'Tiny'
+  * - For sub-components, use Parent.SubComponent format (e.g., Radio.Group)
+  * Note: Currently only two Tiny React components are available
+  */

Line range hint 2178-2183: Improve export organization

The current export pattern mixes individual exports with a grouped export at the end. This makes it harder to track what's being exported and maintain the exports.

Consider consolidating all exports at the end of the file:

const ProtocolTypes = {
  JS_EXPRESSION: 'JSExpression',
  JS_FUNCTION: 'JSFunction',
  JS_I18N: 'i18n',
  JS_RESOURCE: 'JSResource',
  JS_SLOT: 'JSSlot'
};

export {
  DEFAULT_COMPONENTS_MAP,
  BUILTIN_COMPONENTS_MAP,
  AntdComponents,
  BUILTIN_COMPONENT_NAME,
  TINY_ICON,
  UNWRAP_QUOTES,
  IntrinsicElements,
  ProtocolTypes
};
packages/react-generator/src/generator/codeGenerator.js (1)

166-166: Rename variable isExist for clarity

The variable isExist implies a boolean value but actually holds the existing file object. Renaming it to something like existingFile improves clarity.

-const isExist = this.getFile(path, fileName)
+const existingFile = this.getFile(path, fileName)

Adjust subsequent references to use existingFile.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 326e736 and ef3921c.

📒 Files selected for processing (19)
  • README.zh-CN.md (2 hunks)
  • packages/react-generator/src/constant/index.js (1 hunks)
  • packages/react-generator/src/generator/codeGenerator.js (1 hunks)
  • packages/react-generator/src/generator/page.js (6 hunks)
  • packages/react-generator/src/plugins/genGlobalState.js (1 hunks)
  • packages/react-generator/src/plugins/genPagePlugin.js (1 hunks)
  • packages/react-generator/src/plugins/genRouterPlugin.js (1 hunks)
  • packages/react-generator/src/plugins/genTemplatePlugin.js (1 hunks)
  • packages/react-generator/src/plugins/genUtilsPlugin.js (1 hunks)
  • packages/react-generator/src/templates/react-templates/template-files/packageJson.js (1 hunks)
  • packages/react-generator/src/templates/react-templates/template-files/src/App.jsx (1 hunks)
  • packages/react-generator/src/templates/react-templates/template-files/src/index.js (1 hunks)
  • packages/toolbars/generate-react/src/Main.vue (2 hunks)
  • packages/toolbars/generate-vue/src/FileSelector.vue (3 hunks)
  • packages/toolbars/generate-vue/src/Main.vue (8 hunks)
  • packages/toolbars/generate-vue/src/generateCode.js (3 hunks)
  • packages/utils/src/fs/index.js (1 hunks)
  • packages/vue-generator/src/generator/vue/sfc/genSetupSFC.js (1 hunks)
  • packages/vue-generator/src/generator/vue/sfc/generateTemplate.js (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • README.zh-CN.md
  • packages/toolbars/generate-vue/src/FileSelector.vue
🚧 Files skipped from review as they are similar to previous changes (11)
  • packages/react-generator/src/plugins/genGlobalState.js
  • packages/react-generator/src/plugins/genPagePlugin.js
  • packages/react-generator/src/plugins/genTemplatePlugin.js
  • packages/react-generator/src/templates/react-templates/template-files/packageJson.js
  • packages/react-generator/src/templates/react-templates/template-files/src/App.jsx
  • packages/react-generator/src/templates/react-templates/template-files/src/index.js
  • packages/toolbars/generate-vue/src/Main.vue
  • packages/toolbars/generate-vue/src/generateCode.js
  • packages/utils/src/fs/index.js
  • packages/vue-generator/src/generator/vue/sfc/genSetupSFC.js
  • packages/vue-generator/src/generator/vue/sfc/generateTemplate.js
🧰 Additional context used
🪛 Biome
packages/react-generator/src/generator/page.js

[error] 423-423: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 427-428: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 429-429: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 431-433: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 435-438: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 443-447: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 449-454: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (10)
packages/react-generator/src/plugins/genUtilsPlugin.js (2)

42-92: Verify plugin integration with CodeGenerator.

Please ensure this plugin is properly registered and executed in the code generation pipeline.

#!/bin/bash
# Check plugin registration and usage
rg -A 5 "genUtilsPlugin" --type js

33-40: Add validation for function utilities.

The function handler should validate:

  1. The content.value is a valid function
  2. The name is a valid JavaScript identifier
  3. Potential name conflicts with other utilities
packages/react-generator/src/plugins/genRouterPlugin.js (1)

1-6: LGTM: Clean import and sensible defaults.

The import statement and default options are well-structured and follow good practices.

packages/react-generator/src/generator/page.js (6)

26-26: LGTM: Import for hook state translation.

The addition of translateHookState import is appropriate for the transition to React hooks-based state management.


366-371: Optimize state initialization using template literals.


386-398: Simplify lifecycle methods mapping.


433-437: Remove debugging console.log statements.


440-457: Fix functional component export syntax.

🧰 Tools
🪛 Biome

[error] 443-447: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 449-454: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


189-189: Verify loop data transformation.

The removal of this.state. references needs verification to ensure all state access patterns are correctly transformed.

✅ Verification successful

Let's gather more context about the specific usage of this.state in the file we're reviewing to understand the transformation better.


Let's check how this transformation is being used in the broader context and if there are any related test cases to verify the behavior.


Based on the context gathered, I can now provide the final response:

Loop data transformation is correctly implemented

The transformation of this.state references in loop data is properly handled:

  • It's specifically scoped to loop data transformation for React components
  • The replacement is part of a larger transformation that handles both typed values (loop.type ? loop.value) and literal values (JSON.stringify(loop))
  • The transformation is used in the context of generating map operations for React's rendering pattern
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining 'this.state' references that might have been missed
rg -l "this\.state\." --type js

Length of output: 816


Script:

#!/bin/bash
# Check the context of this.state usage in page.js
rg "this\.state\." -C 3 packages/react-generator/src/generator/page.js

# Also check for any loop-related transformations in the file
rg "loop\." -C 3 packages/react-generator/src/generator/page.js

Length of output: 786


Script:

#!/bin/bash
# Check for test files related to loop transformations
fd -e test.js -e spec.js -X rg -l "loop.*value" --type js

# Get more context around the loop transformation
rg -C 10 "loop\.type \? loop\.value" --type js

Length of output: 1587

packages/react-generator/src/generator/codeGenerator.js (1)

47-60: 🛠️ Refactor suggestion

Uncomment transformStart and transformEnd if required

The calls to transformStart() and transformEnd() in the generate method are commented out. If these hooks are necessary for initialization and cleanup, consider uncommenting them to ensure the full lifecycle is executed.

Uncomment the methods if they are required:

 try {
+  await this.transformStart()
   await this.transform()
 } catch (error) {
   this.error.push(error)
   if (!this.tolerateError) {
     throw new Error(
-      `[codeGenerator][generate] get error when running hook: ${curHookName}. error message: ${JSON.stringify(
-        error
-      )}`
+      `[codeGenerator][generate] encountered an error: ${error.message}`
     )
   }
 } finally {
+  await this.transformEnd()
 }

Ensure that the hooks are functioning as intended and that any necessary plugin actions are performed.

packages/react-generator/src/plugins/genUtilsPlugin.js Outdated Show resolved Hide resolved
packages/react-generator/src/plugins/genUtilsPlugin.js Outdated Show resolved Hide resolved
packages/react-generator/src/plugins/genUtilsPlugin.js Outdated Show resolved Hide resolved
packages/react-generator/src/plugins/genUtilsPlugin.js Outdated Show resolved Hide resolved
packages/react-generator/src/plugins/genRouterPlugin.js Outdated Show resolved Hide resolved
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: 12

🧹 Outside diff range and nitpick comments (4)
packages/react-generator/src/utils/uaperCase.js (1)

1-4: Add JSDoc documentation and consider renaming the file.

The implementation is correct, but there are a few improvements needed:

  1. The filename appears to have a typo ("uaperCase.js" → "upperCase.js")
  2. Add JSDoc documentation for better maintainability

Apply this diff:

+/**
+ * Capitalizes the first letter of a string.
+ * @param {string} string - The input string to capitalize
+ * @returns {string} The input string with its first letter capitalized
+ */
 export const capitalizeFirstLetter = (string) => {
-  if (!string) return string // 检查空字符串
+  if (!string) return string // Check for empty string
   return string.charAt(0).toUpperCase() + string.slice(1)
 }
packages/react-generator/src/plugins/genRouterPlugin.js (1)

106-111: Consider adding source maps for generated code.

The generated code would benefit from source maps for better debugging experience.

 const res = {
   fileType: 'jsx',
   fileName,
   path,
-  fileContent: `${importSnippet}\n \n ${lazyPage.join('')} \n ${exportSnippet}`
+  fileContent: `${importSnippet}\n \n ${lazyPage.join('')} \n ${exportSnippet}`,
+  sourceMap: {
+    version: 3,
+    sources: [fileName],
+    names: [],
+    mappings: '' // Generate proper source map
+  }
 }
packages/toolbars/generate-vue/src/Main.vue (2)

2-3: Internationalize UI text strings.

The Chinese text "生成当前应用代码到本地文件" should be moved to an i18n configuration file for better maintainability and localization support.

-    content="生成当前应用代码到本地文件">
+    :content="$t('generate.tooltip')">

72-72: Remove commented debug code.

Remove the commented console.log statement as it's not needed in production code.

-      // console.log(useCanvas().canvasApi.value, 'value>>>>>')
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 56c47d8 and cbf9a53.

📒 Files selected for processing (4)
  • packages/react-generator/src/generator/page.js (7 hunks)
  • packages/react-generator/src/plugins/genRouterPlugin.js (1 hunks)
  • packages/react-generator/src/utils/uaperCase.js (1 hunks)
  • packages/toolbars/generate-vue/src/Main.vue (8 hunks)
🧰 Additional context used
🪛 Biome
packages/react-generator/src/generator/page.js

[error] 424-424: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 428-429: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 429-430: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 432-434: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 436-438: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 442-445: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 449-452: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (4)
packages/react-generator/src/generator/page.js (4)

26-27: LGTM: New imports enhance code functionality.

The addition of translateHookState and capitalizeFirstLetter imports supports the transition to React hooks and improves string manipulation capabilities.


68-68: Consider using a more robust method for 'this' removal.

The current implementation using a simple string replacement remains fragile. This was previously flagged and the suggestion to use regex for more reliable results is still valid.


367-371: Optimize state initialization using template literals.

The current implementation using string concatenation in a loop was previously flagged. The suggestion to use template literals and array methods remains valid.


434-439: Remove debugging console.log statements.

These debugging statements should be removed before merging to production, as previously noted in past reviews.

🧰 Tools
🪛 Biome

[error] 436-438: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

packages/react-generator/src/utils/uaperCase.js Outdated Show resolved Hide resolved
packages/react-generator/src/plugins/genRouterPlugin.js Outdated Show resolved Hide resolved
packages/react-generator/src/plugins/genRouterPlugin.js Outdated Show resolved Hide resolved
packages/react-generator/src/plugins/genRouterPlugin.js Outdated Show resolved Hide resolved
packages/react-generator/src/plugins/genRouterPlugin.js Outdated Show resolved Hide resolved
packages/toolbars/generate-vue/src/Main.vue Outdated Show resolved Hide resolved
packages/toolbars/generate-vue/src/Main.vue Show resolved Hide resolved
packages/react-generator/src/generator/page.js Outdated Show resolved Hide resolved
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

🧹 Outside diff range and nitpick comments (2)
packages/toolbars/generate-vue/src/Main.vue (2)

81-81: Remove commented console.log statement

Remove the commented console.log statement instead of leaving it in the code. Commented debug statements can lead to code clutter.

-      // console.log(useCanvas().canvasApi.value, 'value>>>>>')

Line range hint 165-175: Extract framework-specific fetch logic

Consider extracting the framework-specific fetch logic into a separate function for better readability and maintainability.

+    const fetchAppSchema = async (framework, id, params) => {
+      return framework === 'Vue' 
+        ? useHttp().get(`/app-center/v1/api/apps/schema/${id}`)
+        : fetchBlockSchema(params)
+    }

     const getPreGenerateInfo = async () => {
       const params = getParams()
       const { id } = useEditorInfo().useInfo()
       const promises = [
-        curFramework === 'Vue' ? useHttp().get(`/app-center/v1/api/apps/schema/${id}`) : fetchBlockSchema(params),
+        fetchAppSchema(curFramework, id, params),
         fetchMetaData(params),
         fetchPageList(params.app)
       ]
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between cbf9a53 and bbd485c.

📒 Files selected for processing (2)
  • packages/react-generator/src/generator/codeGenerator.js (1 hunks)
  • packages/toolbars/generate-vue/src/Main.vue (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/react-generator/src/generator/codeGenerator.js
🔇 Additional comments (3)
packages/toolbars/generate-vue/src/Main.vue (3)

36-40: Skip - Duplicate comment about temporary imports


64-76: Skip - Duplicate comment about framework options


213-244: Skip - Duplicate comments about schema generation optimization and factory pattern

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: 60

🧹 Outside diff range and nitpick comments (28)
packages/design-core/src/previewReact/src/srcFiles/main.jsx (1)

1-5: Add component documentation and type definitions

The component lacks documentation and type definitions. Consider adding:

  1. JSDoc documentation explaining the component's purpose
  2. PropTypes or TypeScript types if the component will accept props in the future
+/**
+ * Main loading component displayed while the application is initializing
+ * @component
+ */
 const Main = () => {
   return <h2>页面加载中...</h2>
 }
 
+Main.displayName = 'Main';
 export default Main
packages/design-core/src/previewReact/src/component/util/parseString.js (2)

1-1: Translate comment to English for consistency.

The comment should be in English to maintain consistency and accessibility across the codebase.

-// 解析字符串为函数或组件
+// Parse string into function or component

2-4: Add comprehensive documentation.

Add JSDoc documentation to clearly explain:

  • Function purpose
  • Parameters and return types
  • Security considerations
  • Usage examples
+/**
+ * Parses a string into a function or component.
+ * @param {string} str - The string to parse
+ * @returns {Function|React.Component} The parsed function or component
+ * @throws {Error} If the string is invalid or cannot be parsed
+ * @example
+ * const fn = parseStringToFunction("(props) => <div>{props.text}</div>");
+ * @security This function should only be used with trusted input
+ */
 export const parseStringToFunction = (str) => {
packages/design-core/src/previewReact/src/srcFiles/app.jsx (1)

4-6: Add component documentation and prop validation.

The App component would benefit from:

  1. JSDoc documentation describing its purpose and usage
  2. PropTypes validation for any props that Main component might require

Consider enhancing the component like this:

+import PropTypes from 'prop-types'
+
+/**
+ * App component serves as the main entry point of the application.
+ * Renders the Main component which displays the loading state.
+ */
const App = () => {
  return <Main />
}

+App.propTypes = {
+  // Add PropTypes for any props that Main component requires
+}
packages/design-core/src/previewReact/src/component/errorboundry/index.jsx (2)

1-4: Add PropTypes and documentation.

The component is missing proper type checking and usage documentation.

Add the following at the top of the file:

 import React from 'react'
+import PropTypes from 'prop-types'
 
+/**
+ * ErrorBoundary catches JavaScript errors anywhere in their child component tree,
+ * logs those errors, and displays a fallback UI instead of the component tree that crashed.
+ * 
+ * @example
+ * <ErrorBoundary>
+ *   <YourComponent />
+ * </ErrorBoundary>
+ */
 export class ErrorBoundary extends React.Component {
+  static propTypes = {
+    children: PropTypes.node.isRequired
+  }

5-8: Implement proper error tracking for production.

Using console.error is appropriate for development but should be replaced with proper error tracking in production.

Consider integrating with an error monitoring service like Sentry, LogRocket, or a custom error tracking solution for production environments. This will help in:

  • Capturing and aggregating runtime errors
  • Providing detailed error context and stack traces
  • Monitoring error trends and impact
🧰 Tools
🪛 eslint

[error] 7-7: Unexpected console statement.

(no-console)

packages/design-core/src/previewReact/src/srcFiles/login.jsx (2)

1-4: Component initialization needs improvement.

The component lacks proper type definitions and documentation. Consider adding:

  • JSDoc comments describing the component's purpose
  • PropTypes or TypeScript types for better maintainability
+import PropTypes from 'prop-types'
 import React from 'react'
 
+/**
+ * Login component that renders a full-viewport iframe
+ * @param {string} initialUrl - The initial URL to load in the iframe
+ */
-const Login = () => {
+const Login = ({ initialUrl }) => {

12-12: Add PropTypes definitions.

Define the component's prop types for better documentation and runtime validation.

 export default Login
+
+Login.propTypes = {
+  initialUrl: PropTypes.string.isRequired
+}
packages/design-core/src/previewReact/src/component/util/parseViews.js (1)

1-17: Consider adding JSDoc documentation.

The function's purpose and parameters should be documented for better maintainability.

Add documentation:

+/**
+ * Parses a views object to generate React component code.
+ * @param {Object} views - The views object containing pageInfo and component code
+ * @param {Object} views.pageInfo - Information about the page
+ * @param {string} views.pageInfo.name - The name of the component
+ * @param {string} views['Main.jsx'] - The component's source code
+ * @returns {string|undefined} The processed component code or undefined if views is empty
+ */
 export const parseView = (views) => {
packages/design-core/src/previewReact/src/srcFiles/constant/index.js (1)

13-15: Consider adding JSDoc documentation for the BROADCAST_CHANNEL constant.

Adding documentation would help other developers understand the purpose and usage of this broadcast channel.

+/**
+ * Broadcast channel names used for cross-window communication in the preview mode.
+ * @constant
+ */
 const BROADCAST_CHANNEL = {
   PreviewLang: 'tiny-lowcode-preview-lang'
 }
packages/design-core/src/previewReact/src/srcFiles/storesHelper.js (1)

1-29: Consider making the store validation more configurable

The current implementation enforces a specific store pattern (useStore name and $id property). For better flexibility and reusability, consider making the validation rules configurable.

You could:

  1. Accept a validator function as a parameter
  2. Move validation rules to a configuration file
  3. Support different store patterns through a strategy pattern

This would make the helper more adaptable to different store implementations while maintaining the current functionality as the default.

packages/design-core/src/previewReact/src/component/fileSelector/index.jsx (4)

6-6: Enhance JSDoc documentation for better type clarity.

The JSDoc could be more descriptive about the expected shape of the files array and the onSelectFile callback signature.

-@param {{files: {fileName: string, fileContent: string}[],  onSelectFile: () => void}} props
+@param {{
+  files: Array<{
+    fileName: string,
+    fileContent: string
+  }>,
+  onSelectFile: (fileName: string) => void
+}} props

20-27: Remove or implement commented code.

There's commented code related to srcFiles that should either be implemented or removed to maintain code cleanliness.

Consider removing these comments if they're no longer needed, or implement the dynamic tab generation using the files prop as suggested above.


1-3: Clean up unused import comment.

The commented import statement for srcFiles should be removed if it's no longer needed.

import { Tabs } from 'antd'
-// import srcFiles from '../../srcFiles'
import './index.css'

10-10: Destructure all used props.

For consistency and clarity, destructure the files prop along with onSelectFile since it's required for the component.

-const { onSelectFile } = props
+const { files, onSelectFile } = props
packages/design-core/src/previewReact/src/srcFiles/dataSourceMap.js (1)

21-25: Consider using standard response codes.

The result object initializes code as an empty string. Consider using standard HTTP-like response codes (e.g., "200" for success) for consistency with API patterns.

 const result = {
-  code: '',
+  code: '200',
   msg: 'success',
   data: {}
 }
packages/design-core/src/preview/src/preview/srcFiles/App.vue (1)

Based on the gathered information, I can now provide the final response:

React preview i18n integration needs attention

The investigation reveals potential issues with i18n integration between Vue and React previews:

  • While both previews share the same constants (BROADCAST_CHANNEL, I18N_KEY_MAPS), the React preview's i18n implementation appears incomplete:
    • Vue preview has a complete i18n setup with locale switching via broadcast channel
    • React preview only imports Vue's i18n components (vue-i18n) but lacks proper React-specific i18n implementation
    • No React i18n provider or proper language switching mechanism was found in the React preview
🔗 Analysis chain

Line range hint 1-67: Verify the relationship between Vue and React preview functionality.

This Vue component handles i18n setup for preview functionality. Since this PR introduces React DSL changes, please verify that:

  1. The i18n configuration is shared between Vue and React preview components
  2. The broadcast channel for language switching works across both Vue and React contexts

Let's verify the integration:


Let's gather more information about the i18n implementation in React preview:


Let me check one more aspect to verify the React preview's i18n integration:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if the i18n configuration and broadcast channel are used in both Vue and React preview components

# Test 1: Check for i18n usage in React preview components
echo "Checking i18n usage in React preview components..."
rg -l "I18N_KEY_MAPS|BROADCAST_CHANNEL" packages/design-core/src/previewReact/

# Test 2: Check for shared constant file usage
echo "Checking constant file usage..."
fd constant "packages/design-core/src" --type f --exec rg -l "BROADCAST_CHANNEL|I18N_KEY_MAPS" {}

Length of output: 433


Script:

#!/bin/bash
# Check the implementation details of i18n and broadcast channel in React preview

# Show the constant file content in React preview
echo "Content of React preview constant file:"
cat packages/design-core/src/previewReact/src/srcFiles/constant/index.js

# Check for i18n setup in React preview
echo -e "\nChecking i18n setup in React preview main component:"
rg -A 10 "i18n" packages/design-core/src/previewReact/src/srcFiles/ --type js

# Check for broadcast channel usage in React preview
echo -e "\nChecking broadcast channel usage in React preview:"
rg -A 5 "useBroadcastChannel|BROADCAST_CHANNEL" packages/design-core/src/previewReact/src/srcFiles/

Length of output: 4875


Script:

#!/bin/bash
# Check for App component and i18n setup in React preview

# Show the main App component content
echo "Content of React preview App component:"
cat packages/design-core/src/previewReact/src/srcFiles/App.jsx 2>/dev/null || cat packages/design-core/src/previewReact/src/srcFiles/App.js 2>/dev/null || cat packages/design-core/src/previewReact/src/srcFiles/App.tsx 2>/dev/null

# Check for any i18n provider or setup components
echo -e "\nChecking for i18n provider components:"
rg -A 5 "I18nProvider|IntlProvider|i18nProvider" packages/design-core/src/previewReact/src/srcFiles/

Length of output: 478

packages/design-core/src/previewReact/src/component/monacoEditor/index.jsx (1)

5-6: Add prop types for better type safety.

Consider adding PropTypes or TypeScript types for the component props to improve maintainability and catch potential issues early.

+import PropTypes from 'prop-types';

 export const ReactMonacoEditor = ({ code, onChange }) => {
   // ... component implementation
 }
+
+ReactMonacoEditor.propTypes = {
+  code: PropTypes.string.isRequired,
+  onChange: PropTypes.func.isRequired
+};
packages/design-core/src/preview/src/iframe/index.vue (1)

65-71: Improve styles and responsiveness

The styles section needs some improvements:

Apply these changes:

 <style scoped>
-/* 添加样式 */
+/* Iframe container styles */
 .iframe {
     width: 100%;
-    height: 100vh
+    height: 100vh;
+    max-height: calc(100vh - var(--header-height, 0px));
+    display: block;
 }
 </style>
packages/design-core/src/preview/src/Toolbar.vue (2)

Line range hint 45-50: Consider using refs instead of direct DOM manipulation

The current implementation uses direct DOM manipulation which goes against Vue's reactive paradigm and could be fragile.

Consider refactoring to use Vue refs:

+ const iframeRef = ref(null)
+ const appRef = ref(null)

  const setViewPort = (item) => {
-   const iframe = document.getElementsByClassName('iframe-container')[0]
-   const app = document.getElementById('app')
-   iframe.style.width = item
-   iframe.style.margin = 'auto'
-   app.style.overflow = 'hidden'
+   if (iframeRef.value) {
+     iframeRef.value.style.width = item
+     iframeRef.value.style.margin = 'auto'
+   }
+   if (appRef.value) {
+     appRef.value.style.overflow = 'hidden'
+   }
  }

Then in template:

<div ref="iframeRef" class="iframe-container">

80-92: Consider adding responsive design support

The toolbar styles look good but could benefit from responsive design considerations for different viewport sizes.

Consider adding media queries for better mobile support:

.toolbar-left,
.toolbar-right {
  margin: 0 12px;
  display: flex;
  gap: 12px;
  
  @media (max-width: 768px) {
    margin: 0 8px;
    gap: 8px;
  }
}

.toolbar-button-text {
  color: var(--ti-lowcode-toolbar-title-color);
  margin-left: 4px;
  font-size: 12px;
  
  @media (max-width: 768px) {
    display: none; /* Hide text on mobile */
  }
}
packages/design-core/src/previewReact/src/srcFiles/lowcode.js (2)

1-20: LGTM! Consider adding JSDoc documentation.

The license header and imports are well-structured. Consider adding JSDoc documentation to describe the module's purpose and its role in the React DSL implementation.

Add a module description like:

+/**
+ * @fileoverview Provides low-code functionality wrapper for React components in the design system.
+ * Handles state management, i18n, and routing in the preview context.
+ */

1-92: Consider separating Vue.js dependencies from React DSL implementation.

The current implementation tightly couples Vue.js internals (getCurrentInstance, nextTick, etc.) with React DSL functionality. This could make it difficult to maintain and evolve the React DSL independently.

Consider:

  1. Creating a framework-agnostic core for the DSL
  2. Implementing separate Vue.js and React adapters
  3. Using dependency injection for framework-specific features

This would improve maintainability and make it easier to support other frameworks in the future.

packages/design-core/src/previewReact/src/srcFiles.js (1)

1-108: Consider architectural improvements for better maintainability and safety.

Suggestions for improving the architecture:

  1. Add TypeScript type definitions for better type safety and documentation
  2. Consider separating the storage (srcFiles) and template generation into different modules
  3. Add validation for file contents to ensure they're non-empty and properly formatted
  4. Consider using a more structured approach for file paths, possibly organizing files by type or feature

Would you like assistance in implementing any of these architectural improvements?

packages/design-core/src/preview/src/preview/Preview.vue (1)

208-212: Clean up unused return values.

The return object includes:

  1. Commented out handleIframeMessage
  2. Variables (showIframe, iframeSrc) that aren't used in the template due to commented IframeVue

Consider removing unused variables until the iframe implementation is complete.

packages/toolbars/generate-vue/src/Main.vue (1)

2-3: Consider translating the tooltip text to English.

The tooltip text "生成当前应用代码到本地文件" should be internationalized for better accessibility.

-    content="生成当前应用代码到本地文件">
+    :content="t('Generate current application code to local files')">
packages/design-core/src/previewReact/src/component/reactLive/index.jsx (1)

54-54: Use consistent language for code comments

The code contains comments in Chinese on lines 54 and 64. For consistency and maintainability, it's recommended to use English for all code comments.

Also applies to: 64-64

packages/design-core/src/preview/src/previewReact/Preview.vue (1)

28-28: Ensure consistency in code comment language

Some comments are written in Chinese:

  • Line 28: // 你想要嵌入的 URL
  • Line 124: // 将css代码嵌入到jsx代码之中
  • Line 138: // 有报错,需要处理一下

To maintain readability and consistency across the codebase for all team members, consider translating these comments into English.

Also applies to: 124-124, 138-138

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between bbd485c and c400c64.

📒 Files selected for processing (45)
  • packages/design-core/config/lowcode.config.js (2 hunks)
  • packages/design-core/src/preview/src/App.vue (2 hunks)
  • packages/design-core/src/preview/src/Toolbar.vue (4 hunks)
  • packages/design-core/src/preview/src/constant/index.js (1 hunks)
  • packages/design-core/src/preview/src/iframe/index.vue (1 hunks)
  • packages/design-core/src/preview/src/preview/Preview.vue (6 hunks)
  • packages/design-core/src/preview/src/preview/srcFiles/App.vue (1 hunks)
  • packages/design-core/src/preview/src/previewApp.vue (2 hunks)
  • packages/design-core/src/preview/src/previewReact/Preview.vue (1 hunks)
  • packages/design-core/src/preview/src/previewReact/generate.js (1 hunks)
  • packages/design-core/src/preview/src/previewReact/srcFiles.js (1 hunks)
  • packages/design-core/src/previewReact/.gitignore (1 hunks)
  • packages/design-core/src/previewReact/README.md (1 hunks)
  • packages/design-core/src/previewReact/eslint.config.js (1 hunks)
  • packages/design-core/src/previewReact/index.html (1 hunks)
  • packages/design-core/src/previewReact/package.json (1 hunks)
  • packages/design-core/src/previewReact/src/App.jsx (1 hunks)
  • packages/design-core/src/previewReact/src/component/case/index.jsx (1 hunks)
  • packages/design-core/src/previewReact/src/component/constant/index.js (1 hunks)
  • packages/design-core/src/previewReact/src/component/errorboundry/index.jsx (1 hunks)
  • packages/design-core/src/previewReact/src/component/fileSelector/index.css (1 hunks)
  • packages/design-core/src/previewReact/src/component/fileSelector/index.jsx (1 hunks)
  • packages/design-core/src/previewReact/src/component/monacoEditor/index.jsx (1 hunks)
  • packages/design-core/src/previewReact/src/component/reactLive/index.jsx (1 hunks)
  • packages/design-core/src/previewReact/src/component/util/parseString.js (1 hunks)
  • packages/design-core/src/previewReact/src/component/util/parseViews.js (1 hunks)
  • packages/design-core/src/previewReact/src/main.jsx (1 hunks)
  • packages/design-core/src/previewReact/src/srcFiles.js (1 hunks)
  • packages/design-core/src/previewReact/src/srcFiles/app.js (1 hunks)
  • packages/design-core/src/previewReact/src/srcFiles/app.jsx (1 hunks)
  • packages/design-core/src/previewReact/src/srcFiles/bridge.js (1 hunks)
  • packages/design-core/src/previewReact/src/srcFiles/constant/index.js (1 hunks)
  • packages/design-core/src/previewReact/src/srcFiles/dataSource.js (1 hunks)
  • packages/design-core/src/previewReact/src/srcFiles/dataSourceMap.js (1 hunks)
  • packages/design-core/src/previewReact/src/srcFiles/injectGlobal.js (1 hunks)
  • packages/design-core/src/previewReact/src/srcFiles/locales.js (1 hunks)
  • packages/design-core/src/previewReact/src/srcFiles/login.jsx (1 hunks)
  • packages/design-core/src/previewReact/src/srcFiles/lowcode.js (1 hunks)
  • packages/design-core/src/previewReact/src/srcFiles/main.jsx (1 hunks)
  • packages/design-core/src/previewReact/src/srcFiles/stores.js (1 hunks)
  • packages/design-core/src/previewReact/src/srcFiles/storesHelper.js (1 hunks)
  • packages/design-core/src/previewReact/src/srcFiles/utils.js (1 hunks)
  • packages/design-core/src/previewReact/vite.config.js (1 hunks)
  • packages/react-generator/src/plugins/genGlobalState.js (1 hunks)
  • packages/toolbars/generate-vue/src/Main.vue (8 hunks)
✅ Files skipped from review due to trivial changes (15)
  • packages/design-core/src/preview/src/previewApp.vue
  • packages/design-core/src/previewReact/.gitignore
  • packages/design-core/src/previewReact/README.md
  • packages/design-core/src/previewReact/index.html
  • packages/design-core/src/previewReact/package.json
  • packages/design-core/src/previewReact/src/component/case/index.jsx
  • packages/design-core/src/previewReact/src/component/constant/index.js
  • packages/design-core/src/previewReact/src/main.jsx
  • packages/design-core/src/previewReact/src/srcFiles/bridge.js
  • packages/design-core/src/previewReact/src/srcFiles/dataSource.js
  • packages/design-core/src/previewReact/src/srcFiles/injectGlobal.js
  • packages/design-core/src/previewReact/src/srcFiles/locales.js
  • packages/design-core/src/previewReact/src/srcFiles/stores.js
  • packages/design-core/src/previewReact/src/srcFiles/utils.js
  • packages/design-core/src/previewReact/vite.config.js
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/design-core/config/lowcode.config.js
  • packages/react-generator/src/plugins/genGlobalState.js
🧰 Additional context used
🪛 ast-grep
packages/design-core/src/previewReact/src/App.jsx

[warning] 9-9: Wildcard postMessage configuration detected. This allows any origin to send messages to the target window. This can lead to security vulnerabilities. Set the targetOrigin parameter to the specific origin you expect messages from.
Context: window.parent.postMessage('OK', '*')
Note: [CWE-345] Insufficient Verification of Data Authenticity [OWASP A08:2021] Software and Data Integrity Failures [REFERENCES]
- https://owasp.org/Top10/A08_2021-Software_and_Data_Integrity_Failures

🪛 eslint
packages/design-core/src/previewReact/src/component/errorboundry/index.jsx

[error] 7-7: Unexpected console statement.

(no-console)

🔇 Additional comments (40)
packages/design-core/src/previewReact/src/srcFiles/main.jsx (1)

5-5: Verify the component's integration

Let's ensure this component is properly integrated into the application's routing/loading system.

#!/bin/bash
# Check how the Main component is being used
echo "Checking Main component usage..."
rg -l "import.*Main.*from.*main" --type js --type jsx --type tsx
packages/design-core/src/previewReact/src/component/util/parseString.js (1)

2-4: Consider implementing proper error boundaries.

Since this function is used in a React context and could potentially throw runtime errors, ensure it's wrapped in an error boundary component.

Let's verify if error boundaries are properly implemented:

#!/bin/bash
# Check for ErrorBoundary implementation and usage
echo "Checking for ErrorBoundary components..."
ast-grep --pattern 'class $_ extends React.Component {
  $$$
  componentDidCatch($$$) {
    $$$
  }
  $$$
}'

echo "Checking for ErrorBoundary usage..."
rg -i "errorboundary" --type js --type jsx --type ts --type tsx
packages/design-core/src/previewReact/src/component/fileSelector/index.css (1)

1-3: LGTM! Clean flexbox implementation.

The button group layout using flexbox is a standard and effective approach.

packages/design-core/src/previewReact/src/component/util/parseViews.js (3)

2-6: LGTM! Proper null/empty object handling.

The function correctly handles edge cases by checking for both null and empty objects.


10-10: ⚠️ Potential issue

Clarify the purpose of Antd replacement.

The global replacement of 'Antd' with 'Antd.' seems arbitrary. This could lead to incorrect replacements in strings or comments.

Consider using a more precise regex that only targets Antd component usage:

-  code = code.replace(/Antd/g, 'Antd.')
+  code = code.replace(/(?<!\.)(Antd)(?=\.[A-Z])/g, 'Antd.')

7-8: ⚠️ Potential issue

Verify the structure of pageInfo object.

The code assumes views['pageInfo']['name'] exists without validation. Consider adding a defensive check.

Consider adding validation:

-  const name = capitalizeFirstLetter(views['pageInfo']['name'])
+  if (!views.pageInfo?.name) {
+    throw new Error('Invalid views object: missing pageInfo.name')
+  }
+  const name = capitalizeFirstLetter(views.pageInfo.name)
✅ Verification successful

Let me generate additional scripts to understand how the views object is constructed and passed to the parseViews function.


Let me try a different search strategy to understand the usage context.


Let me check how the views object is passed to this function from the React Live component.


Based on the code analysis, I can now provide the final response:

Add validation for views object structure

The parseView function is used in a React Live preview component where views is passed as a prop and already has a top-level validation. However, the nested pageInfo.name access should still be protected. Suggested changes:

export const parseView = (views) => {
  if (!views || Object.keys(views).length === 0) {
    return
  }
+  if (!views.pageInfo?.name) {
+    console.warn('Missing required pageInfo.name in views object')
+    return
+  }

  const name = capitalizeFirstLetter(views.pageInfo.name)
  let code = views['Main.jsx']

Rationale:

  1. The parent component already checks if views exists and has content
  2. The function is used in a controlled environment (React Live preview)
  3. A warning and early return is more appropriate than throwing an error since this is a preview functionality
  4. Using optional chaining aligns with the modern JavaScript practices seen in the codebase
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for pageInfo structure usage
rg -A 5 "pageInfo.*name" 

Length of output: 7549


Script:

#!/bin/bash
# Search for where views object is created/passed to parseViews
rg -B 5 -A 2 "parseViews\(" 

# Search for the structure of views object
ast-grep --pattern 'const views = $_'

Length of output: 158


Script:

#!/bin/bash
# Search for the file content to understand the context
cat packages/design-core/src/previewReact/src/component/util/parseViews.js

# Search for where this file is imported/used
rg -l "parseViews"

Length of output: 718


Script:

#!/bin/bash
# Check the React Live component implementation
cat packages/design-core/src/previewReact/src/component/reactLive/index.jsx

# Search for any test files that might show the structure
fd -e test.js -e spec.js parseViews

Length of output: 2827

packages/design-core/src/previewReact/src/srcFiles/constant/index.js (2)

1-11: LGTM: License header is complete and properly formatted.


17-20: Add documentation and consider type safety for I18N_KEY_MAPS.

The constant would benefit from JSDoc documentation and potentially TypeScript types if the project supports it.

+/**
+ * Maps language codes to their corresponding locale identifiers.
+ * @constant
+ * @type {Object.<string, string>}
+ */
 export const I18N_KEY_MAPS = {
   zhCN: 'zh_CN',
   enUS: 'en_US'
 }

Additionally, let's verify if these are all the supported languages in the codebase.

✅ Verification successful

The I18N_KEY_MAPS constant is correctly defined and matches the codebase usage.

Based on the comprehensive verification of i18n files across the codebase:

  • The mapping zhCN: 'zh_CN' and enUS: 'en_US' are the only two language codes consistently used throughout the project
  • These mappings are used to convert between different format conventions (camelCase to underscore)
  • The constant is used in the controller's i18n setup for TinyVue component library integration

The suggested JSDoc documentation would be beneficial, but the language mapping is complete and accurate.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for language/locale references in the codebase to ensure we haven't missed any supported languages

echo "Searching for potential language codes and locale strings..."
rg -g '!*.{lock,svg,md}' -i "locale.*['\"]([a-z]{2}_[A-Z]{2}|[a-z]{2}-[A-Z]{2})['\"]" 

echo "Searching for i18n related configuration files..."
fd -e json -e js -e ts --full-path "i18n|locale|lang" --exec echo "Found: {}"

Length of output: 4575


Script:

#!/bin/bash
# Let's check the actual content of some key i18n files to verify the language codes used

echo "Checking locales.js files content..."
cat packages/design-core/src/previewReact/src/srcFiles/locales.js
cat packages/design-core/src/preview/src/preview/srcFiles/locales.js

echo -e "\nChecking i18n configuration files..."
cat packages/i18n/src/i18n.js
cat packages/canvas/src/i18n.js

echo -e "\nChecking for any other language codes in JSON files..."
fd -e json -e js --full-path "i18n" --exec grep -l "language\|locale" {} \; --exec cat {}

Length of output: 11754

packages/design-core/src/preview/src/constant/index.js (1)

2-11: Copyright notice formatting changes

These changes only affect formatting and don't modify the substance of the copyright notice.

packages/design-core/src/previewReact/src/App.jsx (2)

1-4: LGTM! Clean component setup with proper imports.

The component follows React best practices with appropriate hooks and state management.


22-26: Verify ReactLive component contract.

The component rendering looks clean, but we should verify the contract of the ReactLive component regarding the expected shape of the views prop.

packages/design-core/src/previewReact/src/srcFiles/app.js (2)

1-11: LGTM: Copyright header is properly formatted.

The copyright header includes all necessary information and follows the standard format.


19-20: Verify the configuration of VITE_CDN_DOMAIN and Vue theme usage.

There are two potential concerns here:

  1. The VITE_CDN_DOMAIN placeholder needs to be properly configured at build time
  2. Vue theme CSS is being loaded in what appears to be a React preview package

Let's verify the configuration and usage:

✅ Verification successful

Let me gather more specific information about the Vue theme usage in the React preview context.


Let me check the preview import map configuration to understand if Vue theme is actually needed in the React preview.


Vue theme CSS is required as OpenTiny Vue components are used in React preview

The Vue theme CSS files are necessary because the React preview actually uses OpenTiny Vue components (Pager, Select, Modal, Input) imported from @opentiny/vue in its utility files. The CSS files provide the styling for these Vue components that are being used within the React preview context.

  • packages/design-core/src/previewReact/src/srcFiles/utils.js imports Vue components: Pager, Select, Modal, Input
  • packages/design-core/src/previewReact/src/srcFiles/lowcode.js imports Vue Modal component
  • The VITE_CDN_DOMAIN is properly configured in the build system through Vite's environment variables
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if VITE_CDN_DOMAIN is configured in environment files
echo "Checking for VITE_CDN_DOMAIN configuration..."
rg -l "VITE_CDN_DOMAIN" 

# Check if Vue theme is actually needed
echo "Checking for Vue component usage..."
rg -l "@opentiny/vue"

Length of output: 15021


Script:

#!/bin/bash
# Check the content of the app.js file to understand the context
echo "Checking the React preview app.js content..."
cat packages/design-core/src/previewReact/src/srcFiles/app.js

# Check if there are any Vue components or dependencies in the React preview
echo -e "\nChecking for Vue dependencies in React preview..."
rg -l "vue" packages/design-core/src/previewReact/

# Check how VITE_CDN_DOMAIN is configured
echo -e "\nChecking VITE_CDN_DOMAIN configuration in vite.config.js..."
cat packages/design-core/vite.config.js

Length of output: 15582


Script:

#!/bin/bash
# Check preview import map configuration
echo "Checking preview import map configuration..."
cat packages/design-core/src/preview/src/preview/importMap.json

# Check if there are any OpenTiny Vue components used in React preview
echo -e "\nChecking for OpenTiny Vue usage in React preview..."
rg "@opentiny/vue" packages/design-core/src/previewReact/

# Check if there are any style dependencies in React preview
echo -e "\nChecking for style dependencies in React preview..."
rg "addCss|link.*stylesheet" packages/design-core/src/previewReact/

Length of output: 3303

packages/design-core/src/previewReact/src/srcFiles/storesHelper.js (2)

29-29: LGTM!

The export statement is clean and follows best practices.


13-13: Verify the existence and exports of stores.js

Let's ensure the referenced stores.js file exists and contains the expected exports.

✅ Verification successful

Empty stores.js file is acceptable for now

The stores.js file exists but only contains a license header and an empty export. This is acceptable as it appears to be a placeholder file that will be populated with store definitions during the React DSL implementation. The wildcard import in storesHelper.js is forward-compatible with this design, allowing for future store additions without modifying the import statement.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the existence and content of stores.js

# Test 1: Check if stores.js exists in the same directory
fd -p ".*stores\.js$" packages/design-core/src/previewReact/src/srcFiles/

# Test 2: Look for store definitions that match our validation criteria
rg -l "useStore.*\$id" packages/design-core/src/previewReact/src/srcFiles/stores.js

Length of output: 221


Script:

#!/bin/bash
# Let's examine the content of stores.js to understand its structure
cat packages/design-core/src/previewReact/src/srcFiles/stores.js

# Also check for any store-related exports
rg "export.*store" -i packages/design-core/src/previewReact/src/srcFiles/stores.js

Length of output: 626

packages/design-core/src/previewReact/eslint.config.js (2)

20-25: LGTM! React settings and plugins are well configured

The React version is correctly specified, and all necessary plugins (react, react-hooks, react-refresh) are properly included.


1-5: Verify ESLint plugin versions in package.json

The imports look good, but we should ensure that the package.json specifies compatible versions for these ESLint plugins, especially since we're using the new flat config format which requires ESLint >=8.21.0.

✅ Verification successful

Let me analyze the output. I can see that there are multiple package.json files in the repository, and I found the relevant one for the React preview configuration that contains the ESLint dependencies:

{
  "dependencies": {
    "antd": "^5.21.6",
    "react": "^18.3.1",
    "react-dom": "^18.3.1",
    "react-jsx-parser": "^2.2.0",
    "react-live": "^4.1.7",
    "react-monaco-editor": "^0.56.2"
  },
  "devDependencies": {
    "@eslint/js": "^9.13.0",
    "@types/react": "^18.3.11",
    "@types/react-dom": "^18.3.1",
    "@vitejs/plugin-react": "^4.3.3",
    "eslint": "^9.13.0",
    "eslint-plugin-react": "^7.37.1",
    "eslint-plugin-react-hooks": "^5.0.0",
    "eslint-plugin-react-refresh": "^0.4.13",
    "globals": "^15.11.0",
    "vite": "^5.4.9"
  }
}

ESLint dependencies are properly configured

The package.json contains all the required ESLint dependencies with compatible versions:

  • ESLint core: eslint@^9.13.0
  • ESLint plugins used in the config:
    • @eslint/js@^9.13.0
    • eslint-plugin-react@^7.37.1
    • eslint-plugin-react-hooks@^5.0.0
    • eslint-plugin-react-refresh@^0.4.13
    • globals@^15.11.0

All versions are compatible with the flat config format introduced in ESLint 8.21.0, as they are using much newer versions.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check package.json for ESLint and plugin dependencies
# Expected: All required dependencies should be present with compatible versions

# Search for package.json files that might contain these dependencies
fd package.json | xargs cat | jq 'select(.dependencies != null or .devDependencies != null) | {dependencies, devDependencies}'

Length of output: 24107

packages/design-core/src/preview/src/App.vue (4)

3-4: LGTM: Clean implementation of conditional preview rendering.

The conditional rendering implementation correctly switches between React and Vue previews based on the DSL mode.


17-18: LGTM: Component registration is consistent.

The components are properly registered and align with their imports and template usage.


Line range hint 42-52: LGTM: Well-structured and documented styles.

The CSS implementation is clean, using variables appropriately and providing clear documentation for different preview contexts.


9-11: Verify the import paths resolve correctly.

While the imports are logically correct, let's verify the relative paths resolve properly, especially the Config import that traverses multiple parent directories.

✅ Verification successful

Import paths are correctly resolved and files exist

All imported files are present at their expected locations:

  • Config import from ../../../config/lowcode.config resolves to packages/design-core/config/lowcode.config.js
  • PreviewReact import from ./previewReact/Preview.vue resolves to packages/design-core/src/preview/src/previewReact/Preview.vue
  • PreviewVue import from ./preview/Preview.vue resolves to packages/design-core/src/preview/src/preview/Preview.vue
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify the existence and paths of imported files
echo "Checking import paths..."
fd -t f "lowcode.config.(js|ts)" packages/design-core/config
fd -t f "Preview.vue" packages/design-core/src/preview/src/previewReact
fd -t f "Preview.vue" packages/design-core/src/preview/src/preview

Length of output: 425

packages/design-core/src/previewReact/src/srcFiles/dataSourceMap.js (3)

13-13: LGTM! Clear and explicit import statement.


35-35: LGTM! Clean export statement.


13-13: Verify integration with related modules.

Let's verify how this module integrates with other components:

✅ Verification successful

Let me gather more information about the actual usage and integration patterns.


Import integration is correctly implemented and consistent

The verification shows that:

  • The dataSource.js exports a default object with list and dataHandler properties
  • The import is correctly used in lowcode.js and srcFiles.js
  • The module is properly integrated within the preview system files
  • No inconsistencies or issues were found in the integration pattern
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check how dataSourceMap is used in other files
echo "Checking dataSourceMap usage..."
rg -l "from.*dataSourceMap" 

# Check CodeGenerator integration
echo "Checking CodeGenerator integration..."
rg -l "CodeGenerator.*dataSourceMap"

# Check dataSource.js structure
echo "Checking dataSource.js structure..."
rg -p "export.*default" --type js -g "dataSource.js"

Length of output: 1233


Script:

#!/bin/bash
# Check the actual usage patterns in the files that import dataSourceMap
echo "Checking usage in lowcode.js files..."
rg -A 5 "from.*dataSourceMap" packages/design-core/src/previewReact/src/srcFiles/lowcode.js

echo "\nChecking usage in srcFiles.js..."
rg -A 5 "from.*dataSourceMap" packages/design-core/src/previewReact/src/srcFiles.js

# Check the structure of dataSource.js being imported
echo "\nChecking dataSource.js content..."
cat packages/design-core/src/previewReact/src/srcFiles/dataSource.js

Length of output: 1543

packages/design-core/src/preview/src/preview/srcFiles/App.vue (1)

10-10: LGTM! Import statement follows modern module resolution patterns.

The change from './constant.js' to './constant' aligns with modern module bundler conventions that can automatically resolve extensions.

packages/design-core/src/preview/src/iframe/index.vue (1)

30-62: Verify component reactivity and cleanup

The component's setup looks generally good, but let's verify a few things:

✅ Verification successful

Based on the shell script results, I can now provide the final response:

Event listener cleanup and reactivity implementation are correct

The component's implementation follows best practices:

  • Event listener cleanup is properly handled with removeEventListener in onBeforeUnmount
  • The interval timer is correctly cleared when receiving the 'OK' message
  • No reactivity watchers are needed since the component uses props directly in the interval callback
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for proper cleanup in similar components
rg -l "addEventListener.*message" | xargs rg "removeEventListener.*message"

# Check for proper watch usage in similar components
ast-grep --pattern 'watch($_, $_)'

Length of output: 7948

packages/design-core/src/preview/src/Toolbar.vue (2)

36-36: LGTM: Improved reactivity with ref()

The change to make debugSwitch reactive using ref() follows Vue 3 composition API best practices.


17-17: Verify integration with React components

Given that this Vue component is part of a system transitioning to React (as mentioned in the PR objectives), please ensure that this toolbar properly integrates with the new React components.

packages/design-core/src/preview/src/previewReact/srcFiles.js (2)

1-26: LGTM! Well-structured imports with clear purpose.

The license header is complete and the imports are properly organized using the raw import method for template generation.


108-108: LGTM! Clear and appropriate default export.

packages/design-core/src/previewReact/src/srcFiles.js (2)

1-26: LGTM! Well-structured imports and proper copyright notice.

The imports are logically organized and the copyright header is properly formatted.


29-31: Verify the inconsistency between srcFiles and genPreviewTemplate.

Main.jsx is included in srcFiles but missing from genPreviewTemplate. This inconsistency should be addressed.

Let's check if Main.jsx is used elsewhere:

packages/design-core/src/preview/src/preview/Preview.vue (4)

219-222: LGTM! Clean and well-structured CSS changes.

The style changes are well-organized:

  • Iframe styles provide full viewport coverage
  • Preview debug mode styles properly handle visibility toggling

Also applies to: 249-259


153-156: Verify React DSL integration.

The code includes React-specific handling, but we should verify:

  1. The langReg replacement works correctly for React components
  2. The transformation maintains component functionality
✅ Verification successful

React DSL integration verified and working as expected

The implementation is correct and properly handles React components:

  • PanelType.REACT is correctly defined as 'jsx'
  • The langReg replacement removes 'lang="jsx"' attribute which is necessary since @vue/repl only supports lang="ts" for script blocks
  • The transformation is properly scoped to React panel types only
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for other React-specific transformations in the codebase
rg -l "panelType === PanelType.REACT" packages/design-core/src/

Length of output: 122


Script:

#!/bin/bash
# Let's check the full context of React-specific transformations
rg -A 5 "panelType === PanelType.REACT" packages/design-core/src/preview/src/preview/Preview.vue

# Check for PanelType enum definition and usage
rg "PanelType" packages/design-core/src/

# Check for langReg definition and usage
rg "langReg" packages/design-core/src/preview/src/preview/Preview.vue

Length of output: 895


Script:

#!/bin/bash
# Let's check the PanelType enum definition
cat packages/design-core/src/preview/src/constant/index.js

# Let's see the broader context of Preview.vue to understand the transformation
rg -B 5 -A 10 "const langReg = /lang=\"jsx\"/" packages/design-core/src/preview/src/preview/Preview.vue

Length of output: 1293


14-14: Maintain consistency in commented code.

The IframeVue component has inconsistent commenting patterns:

  • Import is commented at line 23
  • Registration is commented at line 37
  • Template usage is commented at line 3

Consider either:

  1. Removing all commented code if not needed
  2. Adding a clear TODO comment explaining the plan for all related code

Also applies to: 23-23, 36-37

✅ Verification successful

Commented code is consistent with its usage pattern

The Config import is actively used in the code for the showIframe ref initialization:

const showIframe = ref(Config.dslMode === 'React');

The IframeVue component's commenting is also consistent throughout the file:

  • Import is commented (line 23)
  • Component registration is commented (line 37)
  • Template usage is commented (line 3)
  • Related method is commented (line 177)

The Config import path is verified to exist at the correct location.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify the Config import path exists
test -f packages/design-core/config/lowcode.config.js && echo "Config file exists" || echo "Config file not found"

Length of output: 102


Script:

#!/bin/bash
# Check if Config is used in Preview.vue
ast-grep --pattern 'Config' packages/design-core/src/preview/src/preview/Preview.vue

# Check for any other usages of Config from lowcode.config.js
rg -l "from.*lowcode\.config\.js" --type vue --type js

Length of output: 169


Script:

#!/bin/bash
# Check if Config is used in Preview.vue and show context
rg "Config" packages/design-core/src/preview/src/preview/Preview.vue -C 2

# Check for any other usages of Config from lowcode.config.js without file type restriction
rg -l "from.*lowcode\.config\.js"

# Show the content of Preview.vue to analyze commented code
cat packages/design-core/src/preview/src/preview/Preview.vue

Length of output: 8519


3-5: Verify the status of IframeVue integration.

The commented-out IframeVue component suggests incomplete iframe integration. If this is work in progress, consider:

  1. Adding a TODO comment explaining the plan
  2. Documenting any dependencies or prerequisites
  3. Creating a tracking issue for the implementation
packages/toolbars/generate-vue/src/Main.vue (4)

27-31: Reuse existing review comment about temporary imports.


55-67: Reuse existing review comment about framework options.


129-133: Reuse existing review comment about promise handling.


203-226: Reuse existing review comment about React schema optimization.

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: 4

🧹 Outside diff range and nitpick comments (3)
packages/toolbars/generate-vue/src/Main.vue (3)

2-3: Consider internationalizing the popover content text.

The hardcoded Chinese text "生成当前应用代码到本地文件" should be moved to an i18n configuration for better maintainability and internationalization support.

-    content="生成当前应用代码到本地文件">
+    :content="t('generate.tooltip')">

29-30: Remove Chinese comment and empty line.

The Chinese comment "初期,方便调试" should be removed along with the empty line below it, as they don't provide value to the codebase.


Line range hint 56-228: Consider implementing a Framework Strategy pattern.

The current implementation mixes framework-specific logic throughout the code. Consider implementing a Strategy pattern to encapsulate framework-specific behavior:

  1. Create separate strategy classes for Vue and React
  2. Move schema generation logic to respective strategy classes
  3. Use a factory to create the appropriate strategy

This would improve:

  • Code organization
  • Maintainability
  • Testability
  • Future framework support

Example structure:

// strategies/BaseFrameworkStrategy.ts
interface FrameworkStrategy {
  generateSchema(pageDetailList: any[]): Promise<any>;
  createGenerator(): any;
}

// strategies/ReactStrategy.ts
class ReactStrategy implements FrameworkStrategy {
  async generateSchema(pageDetailList: any[]) {
    // React-specific schema generation
  }
  
  createGenerator() {
    return generateReactApp();
  }
}

// factories/StrategyFactory.ts
class FrameworkStrategyFactory {
  static create(framework: string): FrameworkStrategy {
    switch (framework) {
      case 'React':
        return new ReactStrategy();
      case 'Vue':
        return new VueStrategy();
      default:
        throw new Error(`Unsupported framework: ${framework}`);
    }
  }
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between c400c64 and 8ae2994.

⛔ Files ignored due to path filters (1)
  • mockServer/src/database/pages.db is excluded by !**/*.db
📒 Files selected for processing (5)
  • mockServer/src/mock/get/app-center/v1/apps/schema/918.json (2 hunks)
  • mockServer/src/services/appinfo.json (113 hunks)
  • packages/react-generator/src/generator/page.js (7 hunks)
  • packages/toolbars/generate-vue/index.js (1 hunks)
  • packages/toolbars/generate-vue/src/Main.vue (9 hunks)
✅ Files skipped from review due to trivial changes (1)
  • packages/toolbars/generate-vue/index.js
🚧 Files skipped from review as they are similar to previous changes (2)
  • mockServer/src/mock/get/app-center/v1/apps/schema/918.json
  • mockServer/src/services/appinfo.json
🧰 Additional context used
🪛 Biome
packages/react-generator/src/generator/page.js

[error] 424-424: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 428-429: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 429-430: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 432-434: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 436-438: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 446-449: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 452-458: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (3)
packages/toolbars/generate-vue/src/Main.vue (1)

53-56: LGTM!

The state initialization and framework configuration look clean and well-structured.

packages/react-generator/src/generator/page.js (2)

68-68: 🛠️ Refactor suggestion

Consider using a more robust approach for handling 'this' references.

The current string replacement approach could lead to incorrect transformations in complex scenarios (e.g., nested objects with 'this' references).

Consider using an AST-based transformation:

-    const eventHandler = item.value.replace('this.', '') // 强制 replace 一下
+    const eventHandler = item.value.replace(/\bthis\b(?=\.[^.]*(?:\.|$))/g, '')

Likely invalid or redundant comment.


438-458: 🛠️ Refactor suggestion

Enhance component structure with React.memo and better organization.

Consider improving the component structure for better performance and maintainability.

- const ${componentName} = () => {
+ const ${componentName} = React.memo(() => {
    ${statement}
    
+   // Group hooks
    ${stringUseEffect}
    ${stringUseLayoutEffect}
    ${stringUseMemo}
    
+   // Group utility functions
    const utils = {}
    ${arrowMethods.join('\n')}
    
    return (
      <>
        ${jsxNode}
      </>
    )
- }
+ })

  export default ${componentName}

Likely invalid or redundant comment.

🧰 Tools
🪛 Biome

[error] 446-449: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 452-458: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

@wjywy wjywy force-pushed the ospp-2024/003-react-dsl branch 2 times, most recently from 62e9274 to 0125e1d Compare October 31, 2024 01:08
@wjywy
Copy link
Author

wjywy commented Oct 31, 2024

出码:QQ20241031-95421 (1).zip

@Issues-translate-bot
Copy link

Bot detected the issue body's language is not English, translate it automatically.


出码:QQ20241031-95421 (1).zip

@wjywy
Copy link
Author

wjywy commented Oct 31, 2024

预览:
QQ20241031-101948.zip

@Issues-translate-bot
Copy link

Bot detected the issue body's language is not English, translate it automatically.


预览:
QQ20241031-101948.zip

@wjywy
Copy link
Author

wjywy commented Oct 31, 2024

预览:

QQ20241031-101948.mp4

@Issues-translate-bot
Copy link

Bot detected the issue body's language is not English, translate it automatically.


Preview:

QQ20241031-101948.mp4

@wjywy
Copy link
Author

wjywy commented Oct 31, 2024

预览与出码视频:https://www.yuque.com/u29297079/sfghcg/qgtpld1m5go5g9dg?singleDoc# 《React DSL出码与预览功能实现》

@wjywy wjywy force-pushed the ospp-2024/003-react-dsl branch from d0a0835 to fcfefc1 Compare October 31, 2024 04:34
@hexqi
Copy link
Collaborator

hexqi commented Oct 31, 2024

image
我启动看到画布有些组件无法显示出来了,你本地会有这个问题吗,如图,画布只显示出来了4个组件

@wjywy
Copy link
Author

wjywy commented Oct 31, 2024 via email

@wjywy wjywy force-pushed the ospp-2024/003-react-dsl branch from c705c6f to 35f99f3 Compare October 31, 2024 11:15
@hexqi hexqi merged commit 588e8a6 into opentiny:ospp-2024/003-react-dsl Oct 31, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
ospp-2024 ospp-2024
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants