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: blockCompile get correct version #964

Merged
merged 7 commits into from
Dec 31, 2024

Conversation

chilingling
Copy link
Member

@chilingling chilingling commented Dec 26, 2024

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?

Issue Number: N/A

What is the new behavior?

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a new API method, fetchGroupBlocksByIds, enhancing module capabilities.
    • Added a new asynchronous function, getAllGroupBlocks, for fetching block groups and their associated blocks.
  • Improvements

    • Streamlined the block compilation process by simplifying logic and enhancing block version management.
    • Updated the way block components are loaded asynchronously, improving performance.
  • User Experience

    • Removed confirmation dialog for refreshing the page after changing block versions, streamlining the version change process.
    • Updated the block compile cache update process to eliminate dependency on specific file names.
    • Renamed method for clearing block component cache to improve clarity in usage.
    • Enhanced the loading mechanism for block components to simplify the process.

Copy link
Contributor

coderabbitai bot commented Dec 26, 2024

Walkthrough

This pull request introduces modifications across multiple packages to enhance block component loading and caching mechanisms. Key changes include updating the resolveRelativeImport function's default parameter, renaming methods for consistency, and introducing a new loadBlockComponent function to streamline asynchronous loading. Additionally, the management of block versions and cache clearing has been improved, along with updates to various related functions to ensure cohesive functionality.

Changes

File Change Summary
packages/block-compiler/src/index.ts Updated resolveRelativeImport function signature, changing default globalGetterName from 'getBlockComponentBlobUrl' to 'loadBlockComponent'
packages/canvas/container/src/container.js Renamed removeBlockCompsCacheByName method to removeBlockCompsCache
packages/canvas/render/src/RenderMain.js Renamed removeBlockCompsCacheByName method to removeBlockComps
packages/canvas/render/src/render.js Introduced loadBlockComponent function, modified block component loading logic, updated globalNotify, getBlockComponent, and added removeBlockCompsCache
packages/plugins/materials/src/composable/block-compile.js Added blockVersionMap, introduced getAllGroupBlocks, modified updateBlockCompileCache, getBlockCompileRes, and getBlockByName functions
packages/plugins/materials/src/meta/block/index.js Added fetchGroupBlocksByIds import and to apis property
packages/plugins/materials/src/meta/block/src/BlockVersionSelect.vue Updated handleChangeVersion function to call updateBlockCompileCache() without arguments

Possibly related PRs

  • fix(block): 新建区块保存后发布区块,发布无效 #438: The changes in this PR involve modifications to the logic for obtaining the current block, which may relate to how components are resolved and imported, similar to the changes in the resolveRelativeImport function in the main PR.
  • feat: move composables to module #569: This PR involves reorganizing exports and could relate to the overall structure of how components are imported and utilized, which is relevant to the changes in the resolveRelativeImport function.
  • refactor: canvas 元应用改造1 #576: The modifications in this PR include changes to the rendering logic, which may connect to how components are loaded and displayed, similar to the changes in the main PR regarding asynchronous component handling.
  • feat(canvas): add the renderer extension capability #718: This PR introduces significant changes to the rendering logic, which could relate to how components are resolved and rendered asynchronously, similar to the changes in the resolveRelativeImport function.
  • feat: support checking all blocks in material add block panel #923: The addition of a select-all feature in the block list may relate to how components are managed and imported, which connects to the changes in the resolveRelativeImport function regarding component loading.
  • fix: resolve some schema update issue #956: This PR addresses issues related to schema updates and component interactions, which may connect to the changes in how components are resolved and imported in the main PR.
  • fix: resolve warnings #957: The changes in this PR focus on resolving warnings, which may relate to the overall structure and handling of components, similar to the changes in the resolveRelativeImport function.

Suggested Labels

ready_for_review, refactor-main

Suggested Reviewers

  • hexqi
  • rhlin

Poem

🐰 Blocks dance and leap with glee,
Async magic, now set free!
Caches clear, components bright,
Refactored code takes playful flight!
A rabbit's code, both swift and light 🚀


📜 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 7ea3e77 and b4e794b.

📒 Files selected for processing (1)
  • packages/canvas/render/src/render.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/canvas/render/src/render.js

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 bug Something isn't working label Dec 26, 2024
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 (4)
packages/canvas/render/src/render.js (3)

260-291: Consider concurrency or re-entrancy in block loading
If multiple calls to loadBlockComponent for the same block occur simultaneously, you might get concurrent fetches. Also consider the security implications of dynamically importing code from external sources.


294-294: Global scope usage caution
Attaching loadBlockComponent to window can open it to external tampering or naming collisions. Consider scoping or restricting usage if possible.


300-302: Clearing all block cache
removeBlockCompsCache fully clears blockComponentsBlobUrlMap. If you need more granular cache invalidation, a per-block approach might be beneficial.

packages/block-compiler/src/index.ts (1)

89-89: No longer using dynamic import
Switching to async () => window.${globalGetterName}('${fileName}') removes code splitting benefits of import(). Check if this impacts performance or bundling.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7f05029 and 8622585.

📒 Files selected for processing (7)
  • packages/block-compiler/src/index.ts (2 hunks)
  • packages/canvas/container/src/container.js (1 hunks)
  • packages/canvas/render/src/RenderMain.js (2 hunks)
  • packages/canvas/render/src/render.js (1 hunks)
  • packages/plugins/materials/src/composable/block-compile.js (4 hunks)
  • packages/plugins/materials/src/meta/block/index.js (1 hunks)
  • packages/plugins/materials/src/meta/block/src/BlockVersionSelect.vue (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • packages/canvas/container/src/container.js
🔇 Additional comments (11)
packages/plugins/materials/src/composable/block-compile.js (6)

4-4: Initialize a global Map for block versions
This approach is fine if you do not require reactivity. Otherwise, consider storing it in a reactive store.


67-71: Lazy loading block versions
This logic ensures the version map is only fetched when needed, which can be more performant.


80-81: Graceful handling of missing version
If blockVersionMap.get(name) doesn't match any history item, the fallback is to blockItem?.content. This is a sensible fallback approach.


86-86: Fallback to default block content
Using the historical version if available, otherwise falling back to blockItem?.content, provides a clear path for version resolution.


49-50: Confirm generatePageCode usage of blockRelativePath
Ensure blockRelativePath: './' is recognized by generatePageCode and has the intended effect.

✅ Verification successful

Let me gather more information about the generatePageCode implementation and its usage of blockRelativePath.


blockRelativePath: './' is correctly used and recognized by the code generator

The verification shows that blockRelativePath is a well-established configuration option in the Vue code generator system:

  • It's used in multiple parts of the codebase, particularly in the Vue SFC (Single File Component) generation
  • The default value is '../components/' but can be overridden, as done in this case with './'
  • The parameter is used for:
    • Generating import statements for blocks
    • Resolving paths when generating template code
    • Processing block components in the SFC generator
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
rg -A 5 'function generatePageCode'

Length of output: 491


Script:

#!/bin/bash
# Search for generatePageCode implementation
ast-grep --pattern 'function generatePageCode($_) {
  $$$
}'

# Search for interface or type definitions related to generatePageCode
rg -A 10 'interface.*generatePageCode|type.*generatePageCode'

# Search for blockRelativePath usage
rg -B 2 -A 2 'blockRelativePath'

Length of output: 6081


29-32: Verify that all references to this updated signature are correct
Previously, updateBlockCompileCache accepted a parameter. If old code still passes an argument, it might break. Please confirm there are no leftover references that expect a parameter.

✅ Verification successful

No issues found with updateBlockCompileCache usage

Based on the codebase analysis, the only reference to updateBlockCompileCache() is in BlockVersionSelect.vue, and it's already being called without any parameters, which matches the new signature. No other references were found in the codebase that might be passing arguments to this function.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
rg "updateBlockCompileCache\("

Length of output: 157


Script:

#!/bin/bash
# Let's check the git history to see the previous signature and its usage
git log -L :updateBlockCompileCache:packages/plugins/materials/src/composable/block-compile.js

Length of output: 0


Script:

#!/bin/bash
# Let's also check for any other potential references using ast-grep
ast-grep --pattern 'updateBlockCompileCache($_)'

Length of output: 50


Script:

#!/bin/bash
# Let's also check the content of BlockVersionSelect.vue to see how it's used
cat packages/plugins/materials/src/meta/block/src/BlockVersionSelect.vue

Length of output: 4444

packages/canvas/render/src/render.js (1)

296-298: Asynchronous component loading
Using defineAsyncComponent(async () => loadBlockComponent(name)) aligns well with your caching in blockComponentsBlobUrlMap. This is a clean design.

packages/plugins/materials/src/meta/block/index.js (1)

3-10: New fetchGroupBlocksByIds usage
Adding fetchGroupBlocksByIds expands functionality. Verify that it correctly handles error states and large data sets.

packages/plugins/materials/src/meta/block/src/BlockVersionSelect.vue (1)

91-91: Revisiting the removed parameter
Previously, updateBlockCompileCache accepted a fileName. Confirm that switching to a no-parameter call does not break partial invalidation logic or other references.

packages/block-compiler/src/index.ts (1)

61-61: Updated default global getter name
globalGetterName now defaults to 'loadBlockComponent'. Ensure all references to the old 'getBlockComponentBlobUrl' are removed or updated.

packages/canvas/render/src/RenderMain.js (1)

508-508: Confirm external usage references to avoid broken imports.

Exporting removeBlockCompsCache is fine, but ensure that any dependent code or documentation referencing removeBlockComps or the old name removeBlockCompsCacheByName is updated accordingly.

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

♻️ Duplicate comments (1)
packages/plugins/materials/src/composable/block-compile.js (1)

8-23: ⚠️ Potential issue

Add error handling for API calls

The function makes multiple API calls without error handling, which could lead to silent failures.

Apply this diff to add proper error handling:

 const getAllGroupBlocks = async () => {
   const { fetchGroups, fetchGroupBlocksByIds } = getMetaApi('engine.plugins.materials.block')
   const appId = getMetaApi(META_SERVICE.GlobalService).getBaseInfo().id

-  const groups = await fetchGroups(appId)
+  try {
+    const groups = await fetchGroups(appId)
+    if (!groups?.length) {
+      console.warn('No block groups found')
+      return
+    }

     const groupIds = groups.map((groupItem) => groupItem.id)
     const blocks = await fetchGroupBlocksByIds({ groupIds })

     for (const blockItem of blocks) {
       if (blockItem?.content?.fileName && blockItem?.current_version) {
         blockVersionMap.set(blockItem.content.fileName, blockItem.current_version)
       }
     }
+  } catch (error) {
+    console.error('Failed to fetch block groups:', error)
+    throw error
+  }
 }
🧹 Nitpick comments (3)
packages/plugins/materials/src/composable/block-compile.js (3)

4-6: Consider implementing cache size limits and cleanup strategy

The module-level Maps (blockVersionMap and blockCompileCache) could potentially grow unbounded. Consider implementing:

  • Maximum cache size limits
  • Least-recently-used (LRU) eviction policy
  • Periodic cleanup mechanism

7-8: Translate comments to English for better accessibility

Consider translating the Chinese comment "获取所有区块分组下的所有区块" to English for better international collaboration.

-// 获取所有区块分组下的所有区块
+// Fetch all blocks from all block groups

Line range hint 67-81: Consider splitting getBlockByName into smaller functions

The function handles multiple responsibilities:

  1. Version map management
  2. Block schema fetching
  3. Version comparison
  4. Resource management

Consider splitting these into separate functions for better maintainability and testing.

Example refactor:

const ensureVersionMapPopulated = async () => {
  if (blockVersionMap.size === 0) {
    await getAllGroupBlocks()
  }
}

const findHistorySchema = (blockItem, version) => {
  return blockItem?.histories?.find?.(
    (historyItem) => historyItem?.version === version
  )
}

const getBlockByName = async (name) => {
  await ensureVersionMapPopulated()
  const blockItem = (await fetchBlockSchema(name))?.[0]
  if (!blockItem) return

  const historyVersion = blockVersionMap.get(name)
  const historySchema = findHistorySchema(blockItem, historyVersion)
  // ... rest of the 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 8622585 and cb4a0e3.

📒 Files selected for processing (1)
  • packages/plugins/materials/src/composable/block-compile.js (4 hunks)
🔇 Additional comments (2)
packages/plugins/materials/src/composable/block-compile.js (2)

29-32: Verify the impact of complete cache clearing

The function now clears all caches instead of targeted clearing by name. This could impact performance if called frequently.


49-58: Verify compatibility with blockCompiler consumers

The blocksSourceCode structure has changed from an array to an object. This could be a breaking change for consumers of the compiled result.

✅ Verification successful

Let me gather more information about the blockCompiler implementation and its usage.


Let me check the implementation of the block compiler from the external package.


The change appears safe as blockCompiler expects an array

From the code analysis, we can see that blockCompiler is imported from @opentiny/tiny-engine-block-compiler and the code explicitly wraps the blocksSourceCode object in an array when passing it to blockCompiler([blocksSourceCode], ...). This means the change from array to object for blocksSourceCode is safe as the array structure is maintained at the point of interaction with blockCompiler.

Additionally, this is the only usage of blockCompiler in the codebase, so there are no other consumers to consider.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for usages of blockCompiler to verify compatibility
ast-grep --pattern 'blockCompiler($_, $_)'

Length of output: 332


Script:

#!/bin/bash
# Check the blockCompiler implementation
ast-grep --pattern 'function blockCompiler($_, $_) {
  $$$
}'

# Also check for const/let/var declarations
ast-grep --pattern 'const blockCompiler = $_'

# Search for any other references to blockCompiler
rg "blockCompiler" -A 3

Length of output: 864


Script:

#!/bin/bash
# Check if the compiler package is available in the repository
fd "@opentiny/tiny-engine-block-compiler"

# Check package.json for this dependency
rg "@opentiny/tiny-engine-block-compiler" -A 3 "package.json"

Length of output: 101

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

♻️ Duplicate comments (1)
packages/canvas/render/src/render.js (1)

276-276: ⚠️ Potential issue

Fix style element query selector issue

The querySelector is called before the ID is set on the style element, which will always return null on the first load.

Move the query selector after setting the ID:

- const stylesheet = document.querySelector(`#${fileName}`)
+ const newStylesheet = document.createElement('style')
+ newStylesheet.setAttribute('id', fileName)
+ const stylesheet = document.querySelector(`#${fileName}`)
🧹 Nitpick comments (1)
packages/canvas/render/src/render.js (1)

289-292: Enhance error handling with logging

Consider adding error logging to help with debugging issues in production.

  } catch (error) {
+   console.error(`Failed to load block component ${name}:`, error);
+   globalNotify({
+     type: 'error',
+     title: `Failed to load block: ${name}`,
+     message: error.message
+   });
    return h(BlockLoadError, { name })
  }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between cb4a0e3 and e5189d0.

📒 Files selected for processing (2)
  • packages/block-compiler/src/index.ts (2 hunks)
  • packages/canvas/render/src/render.js (1 hunks)
🔇 Additional comments (1)
packages/block-compiler/src/index.ts (1)

61-61: LGTM: Function parameter and implementation updated correctly

The changes align well with the new block loading mechanism, updating both the default parameter and the async component definition consistently.

Let's verify that no old references to 'getBlockComponentBlobUrl' remain:

Also applies to: 89-89

✅ Verification successful

The remaining reference to getBlockComponentBlobUrl is in a development-only file

The only remaining reference to getBlockComponentBlobUrl is in packages/block-compiler/src/dev.ts, which is a development/test file used for rendering sample blocks. This is not part of the main implementation and doesn't affect the production code. The change in the main implementation (src/index.ts) is consistent and complete.

  • packages/block-compiler/src/dev.ts: Contains a development-only reference that can be updated separately if needed
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining references to the old function name
rg "getBlockComponentBlobUrl"

Length of output: 114


Script:

#!/bin/bash
# Let's check the dev.ts file to understand the context of the remaining reference
cat packages/block-compiler/src/dev.ts

Length of output: 2107

packages/canvas/render/src/render.js Outdated Show resolved Hide resolved
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: 2

🧹 Nitpick comments (2)
packages/canvas/render/src/render.js (2)

266-266: Add type checking for controller response.

The response from getBlockByName is used without type validation, which could lead to runtime errors if the response is malformed.

Add type validation:

 const blocksBlob = await getController().getBlockByName(name)
+if (!blocksBlob || typeof blocksBlob !== 'object') {
+  throw new Error(`Invalid response from getBlockByName for ${name}`)
+}

295-295: Document and type-guard the global API.

Exposing functions on the global window object without type declarations or documentation makes the API harder to discover and use safely.

Consider adding TypeScript declarations and JSDoc:

+/**
+ * Loads a block component by name and caches its blob URL.
+ * @param {string} name - The name of the block component to load
+ * @returns {Promise<any>} The loaded component module
+ * @throws {Error} If the component cannot be loaded
+ * @global
+ */
 window.loadBlockComponent = loadBlockComponent
+
+// Add to a separate .d.ts file:
+declare global {
+  interface Window {
+    loadBlockComponent(name: string): Promise<any>
+  }
+}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e5189d0 and 7ea3e77.

📒 Files selected for processing (1)
  • packages/canvas/render/src/render.js (1 hunks)
🔇 Additional comments (2)
packages/canvas/render/src/render.js (2)

276-276: ⚠️ Potential issue

Fix stylesheet selector to match the ID attribute.

The querySelector uses #${fileName} but the ID is set without any prefix in setAttribute. This could lead to incorrect stylesheet selection.

Apply this fix:

-const stylesheet = document.querySelector(`#${fileName}`)
+const stylesheet = document.querySelector(`style[id="${fileName}"]`)

Likely invalid or redundant comment.


289-292: 🛠️ Refactor suggestion

Add cleanup in error handling.

When an error occurs during block loading, any styles that were already injected remain in the DOM. This could lead to style pollution.

Apply this enhancement:

 } catch (error) {
+  // Clean up any styles that were injected before the error
+  blockComponentsBlobUrlMap.forEach((_, fileName) => {
+    const stylesheet = document.querySelector(`style[id="${fileName}"]`)
+    stylesheet?.remove()
+  })
+  blockComponentsBlobUrlMap.clear()
   // 加载错误提示
   return h(BlockLoadError, { name })
 }

Likely invalid or redundant comment.

packages/canvas/render/src/render.js Show resolved Hide resolved
packages/canvas/render/src/render.js Outdated Show resolved Hide resolved
@hexqi hexqi merged commit bdc26f6 into opentiny:release/v2.1.0 Dec 31, 2024
1 check 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