Skip to content

fix: url unchanged after create block#1323

Merged
hexqi merged 2 commits into
opentiny:developfrom
gene9831:fix/url-unchanged-after-create-block
Apr 22, 2025
Merged

fix: url unchanged after create block#1323
hexqi merged 2 commits into
opentiny:developfrom
gene9831:fix/url-unchanged-after-create-block

Conversation

@gene9831
Copy link
Copy Markdown
Collaborator

@gene9831 gene9831 commented Apr 22, 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

问题现象:在设计器区块插件中,新建区块后。url blockid参数没有更新,导致画布上下文不正确,可能渲染出错误的页面
关联Bug: #1311,另外 #1312 pr修改方案并非解决url参数的问题
原因:在设计器区块插件中,新建区块后,此时新区块数据未保存到服务器,所以拿不到新区块的id。导致url参数中的blockid无法更新
解决方案:在新建区块后,立即向服务器发起请求,使用新的区块id来更新url参数。(新建页面也是类似的逻辑,所以新建页面后url可以正常更新)

What is the current behavior?

Issue Number: N/A

What is the new behavior?

  • 在新建区块后,立即向服务器发起请求,使用新的区块id来更新url参数
  • 将新建或更新区块内容成功后的Modal弹窗,修改为通知,优化UI体验
    before:
    image
    aflter:
    image

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

Summary by CodeRabbit

Summary by CodeRabbit

  • Bug Fixes

    • Improved error handling when updating block categories to prevent runtime errors if a category is missing.
    • Enhanced safety checks for tenant data to avoid issues when certain fields are undefined.
  • New Features

    • Asynchronous handling of block creation now ensures the global block ID is updated only after successful creation.
    • Notifications for block operations are now unified and provide clearer success messages.
  • Refactor

    • Streamlined block creation and initialization by delegating to a unified meta API, allowing better promise management and more consistent behavior.
    • Updated block creation and update functions to return promises directly, improving asynchronous handling and caller control.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 22, 2025

Walkthrough

The changes introduce improved asynchronous handling and safer data access across several modules related to block creation and management. Route handlers and service methods now include null checks and use optional chaining to prevent runtime errors. The block creation workflow is refactored to return promises, allowing for proper chaining and post-processing, such as updating global state and triggering notifications only after successful completion. Notification mechanisms are unified to use a consistent interface. Additionally, internal logic is adjusted to delegate block initialization to a meta API, streamlining the process and ensuring proper sequencing of actions.

Changes

File(s) Change Summary
mockServer/src/routes/main-routes.js Modified POST /material-center/api/block/create handler to use async/await for block creation, safely extract category ID with optional chaining, and update the block category service after creation.
mockServer/src/services/blockCategory.js Added null check before updating the blocks array in the category object to prevent errors if the category does not exist.
packages/plugins/block/src/SaveNewBlock.vue Refactored block creation logic to handle promises asynchronously, updating the global block ID and activating the plugin only after successful creation. Imported getMetaApi and META_SERVICE for global state updates.
packages/plugins/block/src/composable/useBlock.ts Changed block creation functions to use the meta API’s saveBlock method instead of direct initialization, removing direct initBlock calls and returning the result of saveBlock.
packages/plugins/block/src/js/blockSetting.tsx Refactored to return promises from createBlock and saveBlock, allowing callers to await results. Switched success notifications to use useNotify and unified notification style.
packages/plugins/materials/src/composable/useResource.ts Updated condition to use optional chaining when checking public_scope_tenants?.length to avoid errors if the property is undefined.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant SaveNewBlock.vue
    participant useBlock.ts
    participant blockSetting.tsx
    participant MetaAPI
    participant Server

    User->>SaveNewBlock.vue: Click "Add Block"
    SaveNewBlock.vue->>useBlock.ts: createBlock() or createEmptyBlock()
    useBlock.ts->>MetaAPI: saveBlock(block)
    MetaAPI->>blockSetting.tsx: createBlock(params)
    blockSetting.tsx->>Server: POST /material-center/api/block/create
    Server-->>blockSetting.tsx: Block creation response
    blockSetting.tsx-->>MetaAPI: Promise resolves with block data
    MetaAPI-->>useBlock.ts: Promise resolves
    useBlock.ts-->>SaveNewBlock.vue: Promise resolves
    SaveNewBlock.vue->>MetaAPI: updateBlockId(block.id)
    SaveNewBlock.vue->>MaterialsPlugin: Activate plugin
    SaveNewBlock.vue->>Dialog: Close dialog
Loading

Poem

In the warren of code, async hops anew,
Promises return, as all rabbits do.
With checks for null and chains so neat,
Our blocks now land on safer feet.
Notifications chirp with a unified call,
And global IDs update for all.
🐇✨ The garden grows more robust each day—
Bugs beware, the rabbits play!


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5707313 and 64c0eee.

📒 Files selected for processing (2)
  • packages/plugins/block/src/SaveNewBlock.vue (2 hunks)
  • packages/plugins/block/src/js/blockSetting.tsx (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/plugins/block/src/SaveNewBlock.vue
  • packages/plugins/block/src/js/blockSetting.tsx
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: push-check

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.

@github-actions github-actions Bot added the bug Something isn't working label Apr 22, 2025
Copy link
Copy Markdown
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/block/src/js/blockSetting.tsx (1)

588-588: Typo in success message.

There's an extra exclamation mark in the success message.

-      useNotify({ message: '新建区块成功!!', type: 'success' })
+      useNotify({ message: '新建区块成功!', type: 'success' })
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9de1275 and 5707313.

📒 Files selected for processing (6)
  • mockServer/src/routes/main-routes.js (1 hunks)
  • mockServer/src/services/blockCategory.js (1 hunks)
  • packages/plugins/block/src/SaveNewBlock.vue (2 hunks)
  • packages/plugins/block/src/composable/useBlock.ts (3 hunks)
  • packages/plugins/block/src/js/blockSetting.tsx (3 hunks)
  • packages/plugins/materials/src/composable/useResource.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: push-check
🔇 Additional comments (11)
mockServer/src/services/blockCategory.js (1)

50-54: Added null check for categories improves robustness.

This change adds proper error handling to prevent runtime errors when no matching category is found in the database, allowing the function to gracefully continue execution.

packages/plugins/materials/src/composable/useResource.ts (1)

116-116: Improved null/undefined handling with optional chaining.

Using optional chaining (?.length) prevents potential runtime errors when accessing the length property on an undefined or null public_scope_tenants object.

mockServer/src/routes/main-routes.js (1)

107-108: Properly await block creation and safely extract category ID.

These changes improve the block creation workflow by:

  1. Properly awaiting the asynchronous block creation operation
  2. Using optional chaining and fallback logic to safely extract the category ID

This ensures that block creation completes before updating the category service, preventing race conditions and potential errors.

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

46-46: Added necessary imports for meta API access.

The added imports enable access to the global service for updating the block ID in the URL.


91-97: Fixed URL update after block creation.

This is the core fix that addresses the main issue. Now the code:

  1. Captures the returned promise from block creation
  2. Updates the global block ID in the URL only after block creation completes successfully
  3. Then activates the Materials plugin and closes the dialog

This sequential flow ensures the URL parameter is properly updated before navigating away from the current view.

packages/plugins/block/src/composable/useBlock.ts (2)

373-375: Good refactoring to delegate block initialization to the meta API.

This change properly delegates block creation to the saveBlock method from the BlockManage meta API, which allows for centralized handling of block initialization and ensures the block ID is retrieved from the server before subsequent operations.


392-394: Consistent pattern applied to createEmptyBlock.

Good consistency by applying the same pattern to createEmptyBlock as was done with createBlock, ensuring both methods properly return promises that resolve with the server-generated block data.

packages/plugins/block/src/js/blockSetting.tsx (4)

580-581: Good improvement to return the Promise.

This change enables proper promise chaining by explicitly returning the Promise from the API call, which is crucial for the fix where the URL needs to be updated only after the server returns the block ID.


597-598: Important fix to return data to the caller.

This is a critical part of the fix - returning the data (including the new block ID) enables the caller to update the URL parameter after block creation.


656-656: UI improvement with notification.

Good switch from modal message to notification for a more consistent and less intrusive user experience.


728-728: Consistent Promise handling in saveBlock.

This change ensures the promise from either updateBlock or createBlock is properly returned to the caller, allowing for proper async flow control.

Comment thread packages/plugins/block/src/js/blockSetting.tsx
Comment thread packages/plugins/block/src/js/blockSetting.tsx
rhlin
rhlin previously approved these changes Apr 22, 2025
Comment thread packages/plugins/block/src/SaveNewBlock.vue Outdated
hexqi
hexqi previously approved these changes Apr 22, 2025
@gene9831 gene9831 dismissed stale reviews from hexqi and rhlin via 64c0eee April 22, 2025 09:47
@hexqi hexqi merged commit 030ece7 into opentiny:develop Apr 22, 2025
2 checks passed
@gene9831 gene9831 deleted the fix/url-unchanged-after-create-block branch May 7, 2025 01:36
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.

🐛 [Bug]: 停留在子路由页面时,创建区块,画布没有清除父级路由的内容

3 participants