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-refresh): fix block list not refresh when create update and delete #1056

Open
wants to merge 3 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

  1. 区块创建、修改、删除和发布后,区块列表没有及时更新,需要切换到别的分组在切换回来才会重新请求,或刷新整个页面;
  2. 区块创建时指定了分组然后发布,如果此时消费端也就是物料区块正好选择了这个分组,该分组下的区块列表没有实时更新,需要切换到别的分组在切换回来才会重新请求;

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

  • New Features

    • Enhanced category and block management functionality
    • Improved block list updating mechanism
    • Added unique row identifiers for better data handling in block history
  • Refactor

    • Simplified category selection logic
    • Streamlined block list update process
    • Updated logic for handling category and group assignments
  • Bug Fixes

    • Improved dynamic handling of category and group selections
    • Ensured immediate refresh of block list after adding blocks

Copy link
Contributor

coderabbitai bot commented Jan 21, 2025

Walkthrough

The pull request introduces changes to the block plugin's category management system. The modifications focus on simplifying the logic for setting and updating categories in the block settings. A new reactive variable currentCategory is added, along with a setCurrentCategory function that streamlines how categories are handled. The updateBlockList function is enhanced to dynamically work with the new category state, improving the flexibility of block list management.

Changes

File Change Summary
packages/plugins/block/src/Main.vue Modified changeCategory method to simplify category change logic by calling setCurrentCategory(val) and updateBlockList() directly.
packages/plugins/block/src/js/blockSetting.jsx Added currentCategory reactive variable, new setCurrentCategory function, and updated updateBlockList method to utilize currentCategory.
packages/common/component/BlockHistoryList.vue Added row-id="id" attribute to <tiny-grid> component for unique row identification.
packages/plugins/block/src/BlockConfig.vue Updated logic for handling categoryId in formData based on shouldReplaceCategoryWithGroup() function. Modified changeCategory function to accommodate new logic.
packages/plugins/materials/src/meta/block/src/BlockGroupPanel.vue Added line to set isRefresh to true in addBlocks method to refresh block list after adding blocks.

Sequence Diagram

sequenceDiagram
    participant UI as User Interface
    participant Main as Main.vue
    participant BlockSetting as blockSetting.jsx
    
    UI->>Main: Change Category
    Main->>BlockSetting: setCurrentCategory(val)
    BlockSetting-->>BlockSetting: Update currentCategory
    BlockSetting->>BlockSetting: updateBlockList()
    BlockSetting-->>UI: Refresh Block List
Loading

Possibly related PRs

  • fix: wrong composable usage and spelling #640: The changes in blockSetting.jsx involve refactoring functions that interact with block management, including the updateBlockList function, which is directly related to the changes made in the main PR regarding the setCurrentCategory function and the updateBlockList() call.
  • fix: add block panel can't open #827: The modification in Main.vue to change the event listener for the <plugin-block-list> component from @click to @editBlock indicates a direct connection to the changes in the main PR that also involve event handling and block management.
  • fix: blockPublishLogic #973: The changes in BlockDeployDialog.vue regarding the block publishing logic directly connect to the modifications in the main PR that simplify the control flow for updating the block list and managing categories.

Suggested labels

bug

Suggested reviewers

  • hexqi
  • chilingling

Poem

🐰 Hop, hop, through the code we go,
Categories dancing, smooth and flow
Refactored logic, clean and bright
Blocks now update with pure delight!
A rabbit's dance of pure design 🎉

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

@github-actions github-actions bot added 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).

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.

1 participant