Skip to content

fix:自定义渲染函数中的组件,如果页面没有引入,预览页面和出码页面会存在问题#1146

Merged
chilingling merged 4 commits intoopentiny:developfrom
webzmj530:zmj/handlejsx
Mar 17, 2025
Merged

fix:自定义渲染函数中的组件,如果页面没有引入,预览页面和出码页面会存在问题#1146
chilingling merged 4 commits intoopentiny:developfrom
webzmj530:zmj/handlejsx

Conversation

@webzmj530
Copy link
Contributor

@webzmj530 webzmj530 commented Feb 25, 2025

English | 简体中文

PR

PR Checklist

Please check if your PR fulfills the following requirements:

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

PR Type

What kind of change does this PR introduce?

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

Background and solution

  • 背景:
    自定义渲染函数中的组件,如果页面没有引入,预览页面和出码页面会存在问题
  • 原因:
    当前出码还不支持检测自定义渲染函数中使用到的组件并生成对应的 import 语句
  • 解决方案:
    在 generateScript 的时候 追加 handleJSXComponentsHook 获取自定义的渲染函数,从里面抽取组件名, 根据componentsMap的映射关系拿到package名称自动导入

What is the current behavior?

Issue Number: #1127

What is the new behavior?

自定义渲染函数中的组件,如果页面没有引入,预览页面和出码页面会自动导入依赖,正常显示

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

Summary by CodeRabbit

  • New Features
    • Enhanced the system to automatically detect component names from JavaScript content, including support for namespaced components.
    • Integrated automatic import handling based on the detected component configurations to streamline component usage in generated output.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 25, 2025

Walkthrough

This change introduces a new utility, componentNameUtils, with a method extractComponents to identify component names from JavaScript content. It updates the specialTypeHandler[JS_FUNCTION] to accept an additional config parameter and uses the new utility to extract component names. When component names are found, corresponding configurations in componentsMap are matched, triggering import additions through globalHooks.addImport.

Changes

File Path Change Summary
packages/vue-generator/.../generateAttribute.js - Added componentNameUtils.extractComponents(jsContent) to extract and deduplicate component names.
- Updated specialTypeHandler[JS_FUNCTION] to include a config parameter and invoke extractComponents, then add imports via globalHooks.addImport if components are found.

Sequence Diagram(s)

sequenceDiagram
    participant F as JSFunction
    participant H as specialTypeHandler
    participant C as componentNameUtils.extractComponents
    participant M as componentsMap
    participant G as globalHooks

    F->>H: Trigger JS_FUNCTION with { value, config }
    H->>C: Extract component names from value
    C-->>H: Return deduplicated component list
    H->>M: Lookup corresponding component config
    M-->>H: Return component config or none
    H->>G: Add import statements using globalHooks.addImport
Loading

Suggested labels

refactor-main

Suggested reviewers

  • hexqi
  • gene9831

Poem

I am a clever little rabbit, hopping in delight,
With names and imports dancing in the moonlit night.
Components leap and play in the fields of code,
Bringing fresh magic down the winding road.
Hip-hip-hooray for changes bright!
🐇🌟🐾

Warning

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

🔧 ESLint

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

 ERR_PNPM_OPTIONAL_DEPS_REQUIRE_PROD_DEPS  Optional dependencies cannot be installed without production dependencies

Tip

⚡🧪 Multi-step agentic review comment chat (experimental)
  • We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments.
    - To enable this feature, set early_access to true under in the settings.
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

@github-actions github-actions bot added the bug Something isn't working label Feb 25, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (3)
packages/vue-generator/src/generator/vue/sfc/generateScript.js (3)

130-136: Consider enhancing the component extraction regex pattern.

The current regex pattern /<[A-Z][a-zA-Z0-9]*/g may miss certain component formats:

  • Doesn't handle namespaced components like <Namespace.Component>
  • Won't extract components from JSX attributes like <div component={<AnotherComponent />} />
  extractComponents(jsContent) {
-    const matches = jsContent.match(/<[A-Z][a-zA-Z0-9]*/g) || []
+    // Match standalone components and those within namespaces
+    const tagMatches = jsContent.match(/<([A-Z][a-zA-Z0-9]*(\.[A-Z][a-zA-Z0-9]*)*)/g) || []
+    // Extract actual component names (handling both standalone and namespaced)
+    const componentNames = tagMatches.map(comp => {
+      const withoutBracket = comp.slice(1)
+      // For namespaced components, take the part after the last dot
+      return withoutBracket.includes('.') ? withoutBracket : withoutBracket
+    })
+    return [...new Set(componentNames)]
  }

138-165: Add error handling to the JSX component processing function.

The function lacks error handling which could lead to silent failures if an unexpected structure is encountered in the schema, particularly when processing JSX content.

export const handleJSXComponentsHook = (schema, hooks, config) => {
  const componentsMap = config?.componentsMap || []

  const processJSXContent = (jsContent) => {
+   try {
      const components = componentNameUtils.extractComponents(jsContent)
      components.forEach((componentName) => {
        const componentConfig = componentsMap.find((cfg) => cfg.componentName === componentName)
        if (componentConfig) {
          const { package: pkgName, destructuring, componentName, exportName } = componentConfig
          hooks.addImport(pkgName, { destructuring, componentName, exportName })
        }
      })
+   } catch (error) {
+     console.warn('Error processing JSX content:', error)
+   }
  }

  const traverseSchema = (obj) => {
    if (!obj) return

+   try {
      Object.values(obj).forEach((value) => {
        if (value?.type === 'JSFunction') {
          processJSXContent(value.value)
        } else if (typeof value === 'object') {
          traverseSchema(value)
        }
      })
+   } catch (error) {
+     console.warn('Error traversing schema:', error)
+   }
  }

  traverseSchema(schema)
}

152-162: Optimize schema traversal for performance.

The current recursive traversal could be inefficient for large schemas. Consider adding a depth limit or more targeted traversal.

- const traverseSchema = (obj) => {
+ const traverseSchema = (obj, depth = 0, maxDepth = 20) => {
    if (!obj) return
+   // Prevent excessive recursion for deep objects
+   if (depth > maxDepth) return

    Object.values(obj).forEach((value) => {
      if (value?.type === 'JSFunction') {
        processJSXContent(value.value)
-     } else if (typeof value === 'object') {
+     } else if (typeof value === 'object' && value !== null) {
-       traverseSchema(value)
+       traverseSchema(value, depth + 1, maxDepth)
      }
    })
  }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8d51ad4 and 177482f.

📒 Files selected for processing (2)
  • packages/vue-generator/src/generator/vue/sfc/genSetupSFC.js (2 hunks)
  • packages/vue-generator/src/generator/vue/sfc/generateScript.js (1 hunks)
🔇 Additional comments (2)
packages/vue-generator/src/generator/vue/sfc/genSetupSFC.js (2)

40-41: Appropriate import added for the JSX components hook.

The handleJSXComponentsHook has been properly imported from the generateScript module.


246-247: Integration of JSX components handling into the parse script pipeline.

The handleJSXComponentsHook has been appropriately added to the defaultParseScriptHook array, which will enable automatic detection and import of components used in custom rendering functions.

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

🧹 Nitpick comments (1)
packages/vue-generator/src/generator/vue/sfc/generateScript.js (1)

145-172: Robust JSX component processing implementation with good error handling

The hook logic for processing JSX content and adding the necessary imports is well-structured. The error handling is comprehensive, providing detailed context for debugging.

One suggestion for improvement:

Consider reducing the verbosity of error messages in production environments to avoid exposing internal implementation details:

- throw new Error('Error processing JSX content:', error, '\nContent:', jsContent)
+ throw new Error(`Error processing JSX content: ${error.message}`)

Similar changes could be applied to other error messages in this function.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 177482f and 5750f94.

📒 Files selected for processing (1)
  • packages/vue-generator/src/generator/vue/sfc/generateScript.js (1 hunks)
🔇 Additional comments (2)
packages/vue-generator/src/generator/vue/sfc/generateScript.js (2)

174-197: Well-implemented schema traversal with safety mechanisms

The recursive traversal implementation is sound with a depth limit to prevent infinite recursion. The function effectively processes JSFunction types and navigates through nested objects.


199-203: Robust top-level error handling

The try-catch block at the top level ensures that any errors during schema traversal are properly caught and reported, which is essential for debugging issues in complex schemas.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (3)
packages/vue-generator/src/generator/vue/sfc/generateScript.js (3)

144-171: Effective component processing with robust error handling

The handleJSXComponentsHook and processJSXContent functions correctly identify components in JSX content and add the necessary imports. The error handling is comprehensive with specific error messages.

However, the Error constructor only accepts a single message argument, so additional arguments like the error object will be ignored.

-      throw new Error('Invalid JSX content:', jsContent)
+      throw new Error(`Invalid JSX content: ${jsContent}`)

Similar fixes should be applied to other error messages in the code.


173-196: Improvement needed in schema traversal error handling

The recursive traversal logic is well-implemented with a depth limit to prevent infinite recursion. However, the error message construction needs improvement.

The error message construction has two issues:

  1. The Error constructor only accepts a single message parameter
  2. The error condition check could be improved for clarity
-    if (!obj || depth > MAX_DEPTH) {
-      throw new Error('Schema traversal stopped: ', depth > MAX_DEPTH ? 'Max depth exceeded' : 'Invalid object')
+    if (depth > MAX_DEPTH) {
+      throw new Error(`Schema traversal stopped: Max depth exceeded (${depth})`)
+    }
+    
+    if (!obj) {
+      throw new Error('Schema traversal stopped: Invalid object')

Similar error handling improvements should be applied to the error at line 194.


198-203: Final error handling needs improvement

The top-level error handling is good for capturing any issues during schema traversal, but has the same issue with Error constructor arguments.

-    throw new Error('Fatal error in handleJSXComponentsHook:', error)
+    throw new Error(`Fatal error in handleJSXComponentsHook: ${error.message || error}`)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5750f94 and 87c5e79.

📒 Files selected for processing (1)
  • packages/vue-generator/src/generator/vue/sfc/generateScript.js (1 hunks)
🔇 Additional comments (1)
packages/vue-generator/src/generator/vue/sfc/generateScript.js (1)

130-142: Good implementation of JSX component extraction utility

The componentNameUtils object provides a clean way to extract component names from JSX content. The regex pattern correctly identifies components starting with capital letters, which follows JSX convention.

@chilingling
Copy link
Member

chilingling commented Mar 10, 2025

@webzmj530 git commit 的提交用户与 GitHub 账户不一致,检查一下?
截屏2025-03-10 20 38 43

@Issues-translate-bot
Copy link

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


@webzmj530 The submission user of git commit is inconsistent with the GitHub account. Check it?

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

🔭 Outside diff range comments (1)
packages/vue-generator/src/generator/vue/sfc/generateScript.js (1)

167-203: ⚠️ Potential issue

Critical issue: Duplicate function name with incorrect implementation

There appears to be a serious code error where addDefaultVueImport is defined twice (here and at line 205). The implementation here contains error handling code that seems intended for handleJSXComponentsHook but is incorrectly placed.

Remove this duplicate function or correct it:

-export const addDefaultVueImport = (schema, globalHooks) => {
-  globalHooks.addImport('vue', {
-      throw new Error('Error processing JSX content:', error, '\nContent:', jsContent)
-    }
-  }
-
-  const traverseSchema = (obj, depth = 0) => {
-    const MAX_DEPTH = 100 // 防止无限递归
-
-    if (!obj || depth > MAX_DEPTH) {
-      throw new Error('Schema traversal stopped: ', depth > MAX_DEPTH ? 'Max depth exceeded' : 'Invalid object')
-    }
-
-    try {
-      Object.entries(obj).forEach(([key, value]) => {
-        if (!value) return
-
-        if (value.type === 'JSFunction') {
-          if (!value.value) {
-            throw new Error('Invalid JSFunction found:', { key, value })
-          }
-          processJSXContent(value.value)
-        } else if (typeof value === 'object') {
-          traverseSchema(value, depth + 1)
-        }
-      })
-    } catch (error) {
-      throw new Error('Error traversing schema:', error, '\nCurrent object:', obj)
-    }
-  }
-
-  try {
-    traverseSchema(schema)
-  } catch (error) {
-    throw new Error('Fatal error in handleJSXComponentsHook:', error)
-  }
-}

The robust error handling from this code should be incorporated into the handleJSXComponentsHook function.

🧹 Nitpick comments (3)
packages/vue-generator/src/generator/vue/sfc/generateScript.js (3)

130-136: Good implementation of JSX component extraction utility

The componentNameUtils object provides a clean way to extract component names from JSX content. The regex pattern correctly identifies components starting with capital letters, which follows JSX convention.

However, there's a possibility of missing namespaced components or components with special characters.

Consider enhancing the regex to handle more complex component names:

-  extractComponents(jsContent) {
-    const matches = jsContent.match(/<[A-Z][a-zA-Z0-9]*/g) || []
-    return [...new Set(matches.map((comp) => comp.slice(1)))]
+  extractComponents(jsContent) {
+    if (!jsContent) return []
+    const matches = jsContent.match(/<[A-Z][a-zA-Z0-9]*(?:\.[A-Z][a-zA-Z0-9]*)*/g) || []
+    return [...new Set(matches.map((comp) => comp.slice(1)))]
+  }

141-150: Enhance JSX content processing with error handling

The processJSXContent function lacks error handling when extracting components or processing component configs.

Add error handling to make the function more robust:

  const processJSXContent = (jsContent) => {
+    if (!jsContent) return
+    
+    try {
      const components = componentNameUtils.extractComponents(jsContent)
      components.forEach((componentName) => {
+        if (!componentName) return
+        
        const componentConfig = componentsMap.find((cfg) => cfg.componentName === componentName)
        if (componentConfig) {
          const { package: pkgName, destructuring, componentName, exportName } = componentConfig
          hooks.addImport(pkgName, { destructuring, componentName, exportName })
        }
      })
+    } catch (error) {
+      console.error('Error processing JSX content:', error, '\nContent:', jsContent)
+    }
  }

152-164: Add validation for component names

The traversal logic doesn't validate component names before processing, which could lead to issues with invalid component references.

Add component name validation:

  const traverseSchema = (obj) => {
    if (!obj) return

    Object.values(obj).forEach((value) => {
      if (value?.type === 'JSFunction') {
-        processJSXContent(value.value)
+        if (value.value) {
+          processJSXContent(value.value)
+        }
      } else if (typeof value === 'object') {
        traverseSchema(value)
      }
    })
  }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 87c5e79 and 8afadc5.

📒 Files selected for processing (4)
  • packages/vue-generator/src/generator/vue/sfc/genSetupSFC.js (2 hunks)
  • packages/vue-generator/src/generator/vue/sfc/generateScript.js (1 hunks)
  • packages/vue-generator/src/generator/vue/sfc/generateScript.js (1 hunks)
  • packages/vue-generator/src/generator/vue/sfc/generateScript.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/vue-generator/src/generator/vue/sfc/genSetupSFC.js
  • packages/vue-generator/src/generator/vue/sfc/generateScript.js
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: push-check

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

🧹 Nitpick comments (2)
packages/vue-generator/src/generator/vue/sfc/generateAttribute.js (2)

281-294: Good enhancement to support automatic component imports in custom rendering functions.

The updated JS_FUNCTION handler now identifies component references within custom rendering functions and automatically adds the necessary imports. This solves the reported issue where custom rendering functions containing components weren't working in preview and output pages due to missing imports.

A few suggestions:

  1. Consider adding a debug log for cases where a component is found but no matching configuration exists in componentsMap. This would help developers troubleshoot when their components aren't being imported.
  2. The regex in extractComponents might miss some valid component references that aren't explicitly wrapped in tags. You might need to enhance the detection in future iterations.
 components.forEach((componentName) => {
   const componentConfig = componentsMap.find((cfg) => cfg.componentName === componentName)
   if (componentConfig) {
     const { package: pkgName, destructuring, componentName, exportName } = componentConfig
     globalHooks.addImport(pkgName, { destructuring, componentName, exportName })
+  } else {
+    // For debugging: component referenced but not found in componentsMap
+    console.debug(`Component "${componentName}" found in custom rendering function but no matching config in componentsMap`)
   }
 })

285-286: Ensure config safety with proper fallback.

While the code does check for config?.componentsMap, it's directly accessing componentsMap as a variable on the next line. This is safe here since you're providing a fallback with || [], but generally it's a good practice to maintain consistent reference patterns.

// 处理 JSX 内容中的组件引用
const componentsMap = config?.componentsMap || []
-const components = componentNameUtils.extractComponents(value)
+const components = componentNameUtils.extractComponents(value || '')
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8afadc5 and 15bd2be.

📒 Files selected for processing (1)
  • packages/vue-generator/src/generator/vue/sfc/generateAttribute.js (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: push-check
🔇 Additional comments (1)
packages/vue-generator/src/generator/vue/sfc/generateAttribute.js (1)

257-268: Well-implemented component name extraction utility.

The newly added componentNameUtils object with its extractComponents method effectively identifies component names from JavaScript content using a regex pattern. The method correctly matches tags that start with uppercase letters (following React/Vue component naming conventions) and supports namespaced components like Tiny.Button. The implementation also properly handles deduplication using a Set.

Copy link
Member

@chilingling chilingling left a comment

Choose a reason for hiding this comment

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

LGTM.

可以增加测试用例到这里:
https://github.com/opentiny/tiny-engine/tree/develop/packages/vue-generator/test/testcases/sfc

测试单个用例方法:
到 vue-generator 文件夹下,执行 pnpm test:unit xxx (xxx为测试文件名)

@webzmj530
Copy link
Contributor Author

webzmj530 commented Mar 14, 2025 via email

@webzmj530
Copy link
Contributor Author

webzmj530 commented Mar 14, 2025 via email

@chilingling chilingling merged commit 13e7f96 into opentiny:develop Mar 17, 2025
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants