Skip to content

【fix】:When splitting materials, a component can exist in multiple snippets. Also, there can be two components within one snippet (with the same componentName but different snippetName)#1199

Closed
webzmj530 wants to merge 2 commits intoopentiny:developfrom
webzmj530:zmj/split-materials

Conversation

@webzmj530
Copy link
Contributor

@webzmj530 webzmj530 commented Mar 7, 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

What is the current behavior?

  • 背景:
    表单分类里面存在复选框组和复选框拖拽按钮组两个组件,使用的是同一个组件TinyCheckboxGroup,但是在拆分之后TinyCheckboxGroup.json文件中复选框拖拽按钮组组丢失!
  • 原因:
    拆包的时候没有考虑一个组件在多个分组里面也没有考虑一个分组里面存在两个组件(组件名相同,配置项不同)
  • 解决方案:
    在splitMaterials拆分物料脚本的时候将组件名相同,snippetName不相同的组件都写入在拆分的组件文件的snippets字段里面

Issue Number: N/A

What is the new behavior?

拆分物料的时候一个组件在snippets中使用多次时在拆分的单个组件文件中snippets存在多项,TinyCheckboxGroup.json文件中存在复选框组和复选框组拖拽组

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

Summary by CodeRabbit

  • Refactor

    • Updated content matching logic to provide more reliable categorization and improved component assignment.
  • Bug Fixes

    • Enhanced text formatting by handling empty or null inputs safely to prevent potential errors.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 7, 2025

Walkthrough

The changes enhance the snippet matching process in the splitMaterials function and improve utility functions. The capitalize and toPascalCase functions now include null checks to return an empty string if the input is falsy. The previous use of some and find for snippet selection is replaced by a more robust combination of forEach and filter, collecting matched snippets into an array and assigning them a category based on the first matching child group. A component is updated only if matched snippets exist, and error handling within the try block remains intact.

Changes

File Change Summary
scripts/splitMaterials.mjs Added null checks to capitalize and toPascalCase functions. Revamped the splitMaterials logic by replacing some/find with forEach/filter to collect matched snippets, assign a category, and conditionally update components.

Sequence Diagram(s)

sequenceDiagram
    participant C as Component
    participant SM as splitMaterials
    participant U as Utils (capitalize/toPascalCase)
    
    C->>SM: Pass input materials
    SM->>U: Validate & transform string inputs
    SM->>SM: Iterate over snippets using forEach/filter
    SM->>SM: Enrich snippets with category (from first child group match)
    SM-->>C: Return updated component with matched snippets (if any)
Loading

Possibly related PRs

Suggested labels

bug, refactor-main

Suggested reviewers

  • chilingling
  • hexqi

Poem

I'm a rabbit on a code spree,
Hopping through snippets so merrily.
Null checks guard every leap,
In forEach loops, no errors creep.
With clean logic, we bound ahead—
A joyful hop where bugs are shed! 🐇

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @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.

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)
scripts/splitMaterials.mjs (1)

23-56: Excellent architectural improvement.

The refactoring from some/find to collecting all matches with forEach/filter successfully addresses the core issue where components can exist in multiple snippets. This approach ensures that components with the same name but different snippet configurations are properly preserved during material splitting.

The new architecture:

  1. Collects all matched snippets into an array
  2. Enriches each snippet with its category
  3. Only updates components when matches exist

This is a robust solution that maintains component integrity during the splitting process.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9152de2 and c075643.

📒 Files selected for processing (1)
  • scripts/splitMaterials.mjs (1 hunks)
🔇 Additional comments (3)
scripts/splitMaterials.mjs (3)

14-15: Good defensive programming!

Adding null checks to these utility functions ensures they'll safely handle falsy inputs without causing errors, improving the robustness of the code.


23-25: Good initialization setup.

Properly initializing the matchedSnippets array and category variable establishes the foundation for collecting multiple snippet matches for a single component.


53-56: Good conditional assignment.

Checking matchedSnippets.length > 0 before assigning ensures that components are only updated when they have matching snippets, preventing empty or null assignments.

Comment on lines +26 to +51
snippets.forEach((child) => {
// 修改这里:检查 children 中的 schema.componentName || snippetName
const matched = child.children.filter((item) => {
const snippetComponentName = item?.schema?.componentName || item.snippetName;
if (!snippetComponentName) return false;

if (Array.isArray(comp.component)) {
return toPascalCase(comp.component[0]) === toPascalCase(item.snippetName)
return toPascalCase(comp.component[0]) === toPascalCase(snippetComponentName);
}
return toPascalCase(comp.component) === toPascalCase(snippetComponentName);
});

return toPascalCase(comp.component) === toPascalCase(item.snippetName)
})

if (snippet) {
comp.snippets = [snippet]
comp.category = child.group

return true
if (matched.length > 0) {
// 为每个 snippet 添加 category
const enrichedSnippets = matched.map(snippet => ({
...snippet,
category: child.group,
}));

matchedSnippets.push(...enrichedSnippets);
// 使用第一个匹配的分组作为组件级别的类别
if (!category) {
category = child.group;
}
}
});
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add optional chaining for snippetName.

The new matching logic correctly allows components to exist in multiple snippets, but there's a potential issue in line 29:

const snippetComponentName = item?.schema?.componentName || item.snippetName;

You're using optional chaining for item?.schema?.componentName but not for item.snippetName, which could cause errors if item is null or undefined.

- const snippetComponentName = item?.schema?.componentName || item.snippetName;
+ const snippetComponentName = item?.schema?.componentName || item?.snippetName;

components.forEach((comp) => {
snippets.some((child) => {
const snippet = child.children.find((item) => {
const matchedSnippets = [];
Copy link
Member

Choose a reason for hiding this comment

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

项目的约定是不要分号,麻烦去除一下

const matchedSnippets = [];
let category = null;

snippets.forEach((child) => {
Copy link
Member

Choose a reason for hiding this comment

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

这里的逻辑可以尝试一下是不是有优化空间(需验证):

  1. 预处理 snippet:
const snippetsMap = {}

snippets.forEach((snippetItem) => {
    if (!Array.isArray(snippetItem?.children)) {
       return;
    }
    
    snippetItem.children.forEach((item) => {
         const key = item?.schema?.componentName || item.snippetName
         if (!key) {
             return;
         }
        const realKey = toPascalCase(key)
        if (!snippetsMap[realKey]) {
            snippetsMap[realKey] = []
        }

        snippetsMap[realKey].push({ ...item, category: snippetItem.category || snippetItem.group })
    })
})
  1. components.forEach 循环中,直接进行匹配:
let matchKey = toPascalCase(comp.component)
if (Array.isArray(comp.component)) {
  matchKey = toPascalCase(comp.component[0])
}
const matchedSnippets = snippetsMap[matchKey]

if (matchedSnippets) {
  comp.snippets = matchedSnippets;
}

好处是:避免每次都在 components.forEach 中进行完整的循环 snippet(这样的话,是 n*n 的时间复杂度),如果在 components.forEach 外部预处理 snippets,是 n + n 的时间复杂度,提升性能。

@webzmj530 webzmj530 closed this Mar 11, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants