Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

fix(block): fix block group info missing when edit block & fix filed block_id is undefined when change bock version; #1056

Open
wants to merge 11 commits into
base: refactor/develop
Choose a base branch
from

Conversation

betterdancing
Copy link
Contributor

@betterdancing betterdancing commented Jan 21, 2025

… delete;

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

修改仅针对java版本,nodejs版本无影响,对于nodejs版本而言区块分类字段是categories且是单选,而java版本改成了区块分组,使用的字段是groups且是多选,无论创建还是修改都要求传递参数groups为数组格式,因此在这个文件里做一个转换

  1. 区块修改后,区块原来所属的分组信息丢失;
  2. 区块创建并保存时不选择分组,由于参数group错误接口报错;
  3. 切换区块版本时,提交参数中version值为null,是由于未找到block_id字段

What is the current behavior?

Issue Number: N/A

What is the new behavior?

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

Summary by CodeRabbit

  • Bug Fixes
    • Updated block handling to ensure that group information is consistently initialized as an array during creation and updating, preventing potential issues when group data is missing.
    • Enhanced selection behavior of the "区块分组" component to allow multiple selections based on specific conditions, improving user experience and flexibility in category management.

Copy link
Contributor

coderabbitai bot commented Jan 21, 2025

Walkthrough

This pull request modifies the createBlock and updateBlock functions in the blockSetting.jsx file to ensure that extraParams.groups is always initialized as an array. The createBlock function now uses categories || [], while the updateBlock function uses categories || (groups || []).map(({ id }) => id). Additionally, the tiny-select component in SaveNewBlock.vue has been updated to allow for multiple selections based on the shouldReplaceCategoryWithGroup() method.

Changes

File(s) Change Summary
packages/plugins/block/src/js/blockSetting.jsx Updated createBlock and updateBlock functions to ensure that extraParams.groups is initialized as an array using `categories
packages/plugins/block/src/SaveNewBlock.vue Modified tiny-select component to include a :multiple attribute based on shouldReplaceCategoryWithGroup(), allowing for multiple selections.

Possibly related PRs

Suggested labels

bug

Suggested reviewers

  • hexqi
  • gene9831

Poem

I'm just a little rabbit,
Hopping through the code so neat,
Adding defaults to my blocks,
Making every function complete.
With a twitch of my nose 🐰, the bugs retreat!


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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

@github-actions github-actions bot added the refactor-main refactor/develop branch feature label Jan 21, 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 (2)
packages/plugins/block/src/js/blockSetting.jsx (2)

401-413: Add error handling for the API call.

While the function correctly handles the category/group logic and sorting, it should include error handling for the API call to ensure robustness and provide feedback to users when the refresh fails.

 export const updateBlockList = () => {
   let params = useBlock().shouldReplaceCategoryWithGroup()
     ? { groupId: currentCategory.value }
     : { categoryId: currentCategory.value }
   if (!currentCategory.value) {
     params = {}
   }
   const appId = getAppId()
-  fetchBlockList({ appId, ...params }).then((data) => {
-    const blockListDescByUpdateAt = data.sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at))
-    useBlock().setBlockList(blockListDescByUpdateAt)
-  })
+  fetchBlockList({ appId, ...params })
+    .then((data) => {
+      const blockListDescByUpdateAt = data.sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at))
+      useBlock().setBlockList(blockListDescByUpdateAt)
+    })
+    .catch((error) => {
+      useNotify({
+        type: 'error',
+        message: '刷新区块列表失败',
+        description: error.message
+      })
+    })
 }

535-537: Consider removing redundant refresh mechanism.

The function uses both updateBlockList() and isRefresh.value = true for refresh. Since updateBlockList() already triggers a reactive update, the isRefresh flag might be redundant.

-        updateBlockList()
-        useBlock().isRefresh.value = true
+        updateBlockList()
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ceb8bae and 82d781e.

📒 Files selected for processing (2)
  • packages/plugins/block/src/Main.vue (2 hunks)
  • packages/plugins/block/src/js/blockSetting.jsx (9 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: push-check
🔇 Additional comments (3)
packages/plugins/block/src/js/blockSetting.jsx (2)

56-56: LGTM! Well-structured state management implementation.

The reactive variable and its setter function are implemented following Vue's best practices.

Also applies to: 279-281


Line range hint 414-433: LGTM! Proper list refresh implementation after deletion.

The function correctly refreshes the block list after successful deletion and includes proper error handling and user feedback.

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

351-352: LGTM! Clean and focused implementation.

The changeCategory method is well-refactored to be more focused and maintainable, properly utilizing the new state management 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: 0

🧹 Nitpick comments (5)
packages/plugins/materials/src/meta/block/src/BlockGroupPanel.vue (1)

169-169: Consolidate repeated refresh triggers.

isRefresh.value is already set to true earlier in the same flow. Using it twice in quick succession may be redundant and could potentially cause confusion. Consider removing or clarifying one of the triggers if it’s not needed.

packages/plugins/block/src/BlockConfig.vue (1)

170-175: Handle empty groups or categories gracefully.

If block.groups or block.categories is empty, the fallback logic may result in an unexpected empty array or undefined identifier. Consider adding a default or a guard condition to prevent potential assignment errors.

packages/plugins/block/src/js/blockSetting.jsx (3)

279-281: Check for invalid or empty category IDs.

setCurrentCategory sets currentCategory.value without validation. If categoryId is null or invalid, subsequent calls to updateBlockList may yield unexpected results. Consider adding a guard if needed.


537-538: Unify post-publish refresh logic.

Similarly calling updateBlockList() and isRefresh.value = true ensures the UI is in sync. Confirm all relevant create/update flows mirror this logic for uniform user experience.


724-724: Invoke “isRefresh” for uniformity.

updateBlockList() is called after new or updated blocks are saved. If other flows also trigger isRefresh.value = true, consider whether to apply the same pattern here to avoid partial states.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 82d781e and 17e4c97.

📒 Files selected for processing (4)
  • packages/common/component/BlockHistoryList.vue (1 hunks)
  • packages/plugins/block/src/BlockConfig.vue (4 hunks)
  • packages/plugins/block/src/js/blockSetting.jsx (9 hunks)
  • packages/plugins/materials/src/meta/block/src/BlockGroupPanel.vue (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: push-check
🔇 Additional comments (9)
packages/common/component/BlockHistoryList.vue (1)

2-2: Ensure that the “row-id” is indeed unique.

Adding row-id="id" helps the grid track rows by their unique identifier, which is important for row-level operations. However, please verify that id values are truly unique across the data set to avoid potential rendering or state mismatch issues.

packages/plugins/block/src/BlockConfig.vue (3)

41-41: Confirm that multiple selection is desired.

By dynamically setting :multiple="shouldReplaceCategoryWithGroup()", you switch between single and multiple category/group selection. Ensure that users will not be confused when the dropdown behavior changes based on this condition.


246-250: Use descriptive property keys for clarity.

Using 'id' or 'category_id' depending on shouldReplaceCategoryWithGroup() is correct. However, ensure that developers easily recognize which key is active and handle potential edge cases (e.g., an empty selection).


291-291: Propagating the condition is consistent.

Exposing shouldReplaceCategoryWithGroup in the returned setup object is logical for reusability across templates. The addition looks clean.

packages/plugins/block/src/js/blockSetting.jsx (5)

13-13: Importing “ref” is necessary.

Good catch integrating ref from Vue. This aligns with the newly introduced reactive variables below.


56-56: Initialize the reactive category to a known state.

Defining currentCategory as an empty string by default is acceptable. Be mindful of how your watchers handle this initial empty state and whether any early calls might cause unintended requests.


401-413: Ensure robust error handling for “updateBlockList.”

This function properly sets parameters based on shouldReplaceCategoryWithGroup(). However, if updated_at is missing or invalid, the sort might fail. Consider verifying the field or adding a fallback before sorting.


427-428: Maintain consistency with other refresh mechanisms.

Calling updateBlockList() followed by isRefresh.value = true is consistent with the approach in other methods like publishBlock. This ensures the UI remains in sync after block deletion.


659-659: Consider matching other operations’ patterns.

While updating a block sets isRefresh.value = true, other operations also call updateBlockList(). Decide if an immediate block list refresh is needed here for consistency (or rely solely on watchers).

@betterdancing betterdancing changed the title fix(block-refresh): fix block list not refresh when create update and delete fix(block): fix block group info missing when edit block & fix filed block_id is undefined when change bock version; Feb 12, 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 (1)
packages/plugins/materials/src/meta/block/src/BlockVersionSelect.vue (1)

81-81: LGTM! Consider adding a comment explaining the fallback logic.

The use of the nullish coalescing operator to determine blockId improves robustness by providing a fallback to refId. This change helps ensure consistent block management.

Consider adding a comment explaining why we fall back to refId:

+              // Fall back to refId if block_id is undefined to handle legacy or migrated blocks
               blockId: selectedRow.block_id ?? selectedRow.refId,

Let's verify that this change properly integrates with the block refresh functionality:

✅ Verification successful

🏁 Script executed:

#!/bin/bash
# Search for other usages of block_id and refId to ensure consistent handling
rg -A 3 'block_id|refId' --type vue --type jsx

Length of output: 76


I'll re-run the check without restricting to file types (since “vue” isn’t recognized) to see if there are any other usages of block_id or refId that might affect consistency with the block refresh functionality:

Let's review the output from this command before finalizing our analysis.


🏁 Script executed:

#!/bin/bash
# Search across the repository for usages of block_id and refId
rg -A 3 'block_id|refId'

Length of output: 695


LGTM! The use of the nullish coalescing operator is appropriate and the fallback to refId is consistent with other usages found.

The search across the repository confirmed that this pattern is only applied in the Vue component (and does not conflict with other contexts such as the JSON data), so the change properly integrates with block refresh functionality. For clarity, consider adding an inline comment:

+              // Fall back to refId if block_id is not available (ensuring compatibility with legacy/migrated blocks)
               blockId: selectedRow.block_id ?? selectedRow.refId,
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 13e75d2 and 04610f7.

📒 Files selected for processing (1)
  • packages/plugins/materials/src/meta/block/src/BlockVersionSelect.vue (1 hunks)
⏰ 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

🔭 Outside diff range comments (1)
packages/plugins/block/src/SaveNewBlock.vue (1)

64-69: 🛠️ Refactor suggestion

Initialize group as an array when multiple selections are enabled.

When shouldReplaceCategoryWithGroup() is true and multiple selections are enabled, initializing group as an empty string could lead to type mismatches.

Update the initialization:

     const formData = reactive({
       label: '',
       path: 'default',
       name_cn: '',
-      group: ''
+      group: shouldReplaceCategoryWithGroup() ? [] : ''
     })
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b61325c and d88b23a.

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

90-94:

❓ Verification inconclusive

Verify block creation with multiple groups.

Please verify that block creation works correctly when multiple groups are selected, especially focusing on:

  1. The block_id generation
  2. The persistence of all selected groups
  3. The proper handling of the path parameter

🏁 Script executed:

#!/bin/bash
# Description: Check block creation implementation and group handling

# Search for block creation and update logic
echo "Searching for block creation implementation..."
rg -A 10 "createBlock|updateBlock" --type js

# Search for block_id handling
echo "Searching for block_id usage..."
rg "block_id" --type js

Length of output: 25152


Verify multi-group block creation and plugin activation behavior.
Please ensure the following during verification:

  • Verify that block creation correctly generates and propagates the block_id.
  • Confirm that when multiple groups are selected, all groups persist in the block's configuration.
  • Check that the path parameter is properly handled during block creation.
  • Revisit the rationale for activating the Materials plugin (via activePlugin(PLUGIN_NAME.Materials)) after creating a block to ensure this behavior is intentional and does not introduce side-effects.

packages/plugins/block/src/SaveNewBlock.vue Outdated Show resolved Hide resolved
@hexqi hexqi added this to the v2.3.0 milestone Feb 14, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
refactor-main refactor/develop branch feature
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants