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

chore: sync bugfix of develop #922

Merged
merged 16 commits into from
Dec 4, 2024

Conversation

chilingling
Copy link
Member

@chilingling chilingling commented Dec 4, 2024

…one (#757)

  • fix: switch selected component event name list still show the origin one

修复画布切换选择组件后,高级面板事件列表仍然显示原组件事件列表的bug
close #747

  • fix: handle potential undefined values in renderEventList

  • fix: use locale instead of zh_CN attrEnglish | 简体中文

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

    • Enhanced block management functionality in various components.
    • Added support for batch deletion and improved data synchronization in DataSourceRecordList.vue.
    • Introduced favicon support in template generation with robust error handling for image processing.
  • Improvements

    • Updated response handling across services for consistency.
    • Enhanced error handling and user notifications during block deployment and page updates.
    • Improved localization and event management in BindEvents.vue.
    • Streamlined slot parameter handling and validation in JsSlotConfigurator.vue.
  • Bug Fixes

    • Corrected variable naming and logic in multiple components to ensure accurate functionality.

chilingling and others added 14 commits December 4, 2024 00:29
…one (opentiny#757)

* fix: switch selected component event name list still show the origin one

修复画布切换选择组件后,高级面板事件列表仍然显示原组件事件列表的bug
close opentiny#747

* fix: handle potential undefined values in renderEventList

* fix: use locale instead of zh_CN attr
修复 mockService 区块详情缺失 data 嵌套结构导致无法正确加载的 bug
* fix: page or block save update breadcrumb uncorrectly

1. 修复页面名称更新时,面包屑页名称没有同步更新的 bug
2. 修复区块保存更新时,强行切换当前画布到正在编辑区块的 bug
3. 修复区块保存更新时,如果画布不是当前编辑的区块,仍取截图的 bug

* fix: add handlePageUpdate mehtod missing params
…ntiny#660)

* feat(vue-generator): add public floder, support image generation

* feat(vue-generator):  code add public floder, support image generation
* fix(block): 新建区块保存后发布区块,发布无效

* fix: del useless null check

---------

Co-authored-by: chilingling <[email protected]>
* fix:table notch saving error message

* fix: change slotparams cause warning

* fix: change by review

* fix: typo parma -> param

---------

Co-authored-by: chilingling <[email protected]>
* fix: change namespace 2 export module

* fix: add missing type params
* fix: blockName regexp incorrect

* fix: change regexp by review

* fix: change by review

* fix: change by review comment
…tiny#847)

修复远程数据源面板请求结果输入框在编辑之后,重新点击发送请求,如果请求结果一样,无法重新填充到请求结果输入框的
bug
* fix: parse template name error

* fix: add detection for test env
Copy link
Contributor

coderabbitai bot commented Dec 4, 2024

Warning

Rate limit exceeded

@chilingling has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 9 minutes and 31 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between dc8dc91 and 79d76d0.

Walkthrough

The pull request includes several modifications across various files, primarily focusing on enhancing functionality, improving error handling, and standardizing response formats. Notable changes involve the replacement of service references in AppService, updates to response handling in BlockService, and improvements in the BlockDeployDialog for block deployment logic. Additionally, several components have updated type annotations to clarify their origins, and new utility functions have been introduced for better state management and error handling.

Changes

File Path Change Summary
mockServer/src/services/app.js Updated AppService to use mockService.pageService instead of pageService for occupier and updates.
mockServer/src/services/block.js Standardized response format in BlockService methods using getResponseData.
packages/common/component/BlockDeployDialog.vue Enhanced block deployment logic; added error handling and improved schema comparison.
packages/common/js/http.js Modified handlePageUpdate to include isCurEditPage parameter for breadcrumb updates.
packages/common/js/verification.js Updated regex for REGEXP_BLOCK_NAME to simplify block name validation.
packages/configurator/src/js-slot-configurator/JsSlotConfigurator.vue Refactored slot parameter handling and improved validation function names.
packages/engine-cli/template/designer/public/mock/bundle.json Corrected export name for PopEditor and updated component properties in the JSON configuration.
packages/plugins/block/src/BlockSetting.vue Added useBlock import; updated updateBlock logic to check current block ID before operations.
packages/plugins/block/src/Main.vue Corrected variable names for consistency in editBlock function.
packages/plugins/block/src/js/blockSetting.jsx Improved error handling in block management functions and added new utility functions for properties and events.
packages/plugins/datasource/src/DataSourceRecordList.vue Enhanced batch delete functionality and data synchronization after edits.
packages/plugins/datasource/src/DataSourceRemoteDataResult.vue Added event handler for monaco-editor to update state reactively.
packages/plugins/page/src/PageSetting.vue Enhanced updatePage logic with isCurEditPage parameter for better handling of page updates.
packages/settings/events/src/components/BindEvents.vue Refactored event handling logic and improved localization for event labels.
packages/toolbars/save/src/js/index.js Updated savePage function to pass additional parameters to handlePageUpdate.
packages/vue-generator/src/generator/generateApp.js Updated JSDoc annotations to use imports for parameter and return types.
packages/vue-generator/src/index.d.ts Significant updates to TypeScript definitions, introducing new functions and updating existing interfaces.
packages/vue-generator/src/plugins/* Updated JSDoc comments across multiple plugins to clarify type origins.
packages/vue-generator/src/templates/vue-template/index.js Introduced favicon handling and base64 to Blob conversion in template generation.

Assessment against linked issues

Objective Addressed Explanation
Ensure event list updates correctly when switching components. (#747)

Possibly related PRs

Suggested labels

bug, ready_for_review

Suggested reviewers

  • hexqi
  • rhlin

🐰 In the code we hop and play,
With fixes brightening up the way.
From blocks to pages, all in line,
Error handling, oh so fine!
So let us cheer, with joy we sing,
For every change, a better spring! 🌼


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 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 Dec 4, 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: 3

🧹 Outside diff range and nitpick comments (17)
packages/engine-cli/template/designer/public/mock/bundle.json (1)

10416-10416: Verify component export name casing

The export name has been changed from "PopEditor" to "Popeditor". While this works functionally, consider using consistent casing across component export names.

Consider using PascalCase for component export names to maintain consistency with Vue.js conventions:

-            "exportName": "Popeditor",
+            "exportName": "PopEditor",
packages/configurator/src/js-slot-configurator/JsSlotConfigurator.vue (4)

89-95: Enhance error message clarity.

The validation logic is correct, but the error message could be more specific about the format requirements.

-        callback(new Error('仅支持JavaScript中有效的变量名'))
+        callback(new Error('请输入有效的JavaScript变量名,多个参数用逗号分隔'))

97-120: Consider adding type checking for params.

The new slot parameter management functions are well-structured and handle reactivity correctly. Consider adding type checking for the params parameter to enhance robustness.

-    const setSlotParams = ({ name, params = '' }) => {
+    const setSlotParams = ({ name, params = '' }: { name: string; params?: string }) => {

122-157: Consider handling edge cases in toggleSlot.

The toggle functionality is well-implemented, but consider:

  1. Validating componentName in the slot value
  2. Handling modal cancellation explicitly
       slotInfo[name].params = params.split(',')
     }
 
+    // Validate component name
+    if (!slotInfo[name].value?.[0]?.componentName) {
+      console.warn('Invalid slot value: missing componentName')
+      return
+    }
+
     updateSlotParams({ ...(props.modelValue || {}), ...slotInfo })
   }

160-165: Add error handling for validation failures.

Consider adding error handling to provide feedback when validation fails.

     slotRef.value.validateField([paramsPath], (error) => {
       if (!error) {
         slot.bind && setSlotParams(slot)
+      } else {
+        console.warn('Slot parameter validation failed:', error)
       }
     })
mockServer/src/services/app.js (1)

18-19: Consider adding error handling for service calls

The service reference update looks good, but consider adding try-catch blocks around the service calls to handle potential failures gracefully.

 async lock(query) {
   const { id, state } = query
-  const occupier = state === 'occupy' ? mockService.pageService.userInfo : null
-  await mockService.pageService.update(id, { occupier })
+  try {
+    const occupier = state === 'occupy' ? mockService.pageService.userInfo : null
+    await mockService.pageService.update(id, { occupier })
+    return getResponseData({
+      operate: 'success',
+      occupier
+    })
+  } catch (error) {
+    return getResponseData({ error: error.message }, false)
+  }
-  return getResponseData({
-    operate: 'success',
-    occupier
-  })
 }
mockServer/src/services/block.js (1)

75-76: Remove unnecessary empty line

The empty line before the return statement is inconsistent with the code style in other methods.

 async detail(blockId) {
   const result = await this.db.findOneAsync({ _id: blockId })
-
   return getResponseData(result)
 }
packages/plugins/datasource/src/DataSourceRemoteDataResult.vue (1)

73-75: Consider adding error handling for JSON parsing

The handleChange handler should validate JSON format since this is used for data source configuration.

 const handleChange = (val) => {
+  try {
+    JSON.parse(val)
     state.value = val
+  } catch (e) {
+    useNotify({
+      type: 'warning',
+      message: '请输入有效的 JSON 格式'
+    })
+  }
 }
packages/plugins/block/src/BlockSetting.vue (1)

220-224: Consider adding error handling for screenshot capture

The block screenshot capture should handle potential failures gracefully.

 const currentId = useBlock().getCurrentBlock()?.id
 if (block.id === currentId) {
   // 获取区块截图
-  block.screenshot = await getBlockBase64()
+  try {
+    block.screenshot = await getBlockBase64()
+  } catch (error) {
+    useNotify({
+      type: 'warning',
+      message: '截图获取失败,将使用现有截图'
+    })
+  }
 }
packages/vue-generator/src/index.d.ts (2)

2-4: Consider replacing 'any' types with specific interfaces for better type safety

The function generateCode uses any types for pageInfo and returns a result of type { [key: string]: any }. Providing explicit interfaces instead of any enhances type safety and code clarity.


Line range hint 58-70: Enhance type definitions by specifying concrete types instead of using 'any' and 'object'

In the IAppSchema interface, properties like i18n, utils, dataSource, and globalState use Record<string, any> or object. Replacing these with concrete interfaces will improve type safety and maintainability.

packages/vue-generator/src/plugins/formatCodePlugin.js (1)

32-32: LGTM! Consider adding return type annotation.

The type import change improves type resolution. While we're updating types, consider adding a return type annotation to the run method for completeness.

-     * @returns
+     * @returns {void}
packages/vue-generator/src/plugins/parseSchemaPlugin.js (1)

Line range hint 33-41: Consider improving infinite loop protection.

The current depth limit of 1000 could be made more explicit and configurable. Consider extracting it as a named constant or configuration option.

+  const MAX_PAGE_DEPTH = 1000; // Maximum depth for page hierarchy
   let depth = 0;

-  while (curParentId !== '0' && depth < 1000) {
+  while (curParentId !== '0' && depth < MAX_PAGE_DEPTH) {
packages/vue-generator/src/plugins/genI18nPlugin.js (1)

Line range hint 24-24: Consider improving null safety handling.

The optional chaining on schema?.i18n could be combined with a default empty object to simplify the code.

-      const i18n = schema?.i18n || []
+      const i18n = schema?.i18n ?? {}
packages/vue-generator/src/templates/vue-template/index.js (2)

41-70: LGTM! Consider enhancing error messages.

The base64ToBlob implementation is robust with proper error handling. However, the error messages could be more descriptive.

Consider enhancing the error messages:

-    throw new Error('Invalid base64 data')
+    throw new Error('Invalid base64 data: Missing MIME type in data URI')

-    throw new Error('Failed to decode base64 string')
+    throw new Error('Failed to decode base64 string: Invalid base64 encoding')

163-178: Track the FIXME comment as a technical debt item.

The FIXME comment indicates a known issue with base64 data during testing that should be properly tracked and addressed.

Would you like me to create a GitHub issue to track this technical debt? The issue would focus on investigating and fixing the base64 data handling during vitest testing.

packages/plugins/page/src/PageSetting.vue (1)

Potential issues with page restoration edge cases

The code review reveals several concerns:

  1. There's no validation of pageData.page before using it as an ID, which could lead to undefined behavior if the page history item is malformed.
  2. The deletion of fields using delete operator is performed without checking if they exist.
  3. While there's a confirmation dialog before restoration, there's no error handling in the restoration process itself.

Recommended changes:

  • Add validation for pageData.page before assignment
  • Add error handling for the updatePage operation
  • Consider using object destructuring instead of field deletion to avoid potential side effects
🔗 Analysis chain

Line range hint 219-232: Verify page restoration edge cases.

While the page restoration logic looks correct, we should verify the handling of edge cases:

  1. What happens if pageData.page is undefined?
  2. Are there any side effects from deleting the fields?

Let me gather more information about the page restoration flow and error handling.


Let me check one more aspect about the page data validation before making the final assessment.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for all usages of restorePage to understand potential edge cases
rg -A 5 "restorePage" 

# Search for any error handling related to undefined page IDs
ast-grep --pattern 'if ($page === undefined || $page === null) {
  $$$
}'

Length of output: 2102


Script:

#!/bin/bash
# Check the implementation of updatePage function and its error handling
ast-grep --pattern 'updatePage($$$) {
  $$$
}'

# Look for any validation or error handling in PageSetting.vue
rg -A 5 "catch|error|throw" packages/plugins/page/src/PageSetting.vue

# Check how pageData is structured when emitted from PageHistory
ast-grep --pattern 'emit($_, $pageData)'

Length of output: 488


Script:

#!/bin/bash
# Check how pageData is validated or processed before restoration
rg -B 5 -A 10 "pageData\.page" packages/plugins/page/src/PageSetting.vue

# Look for any validation in the PageHistory component before emitting the data
rg -B 5 -A 10 "emit\('restorePage'" packages/plugins/page/src/PageHistory.vue

Length of output: 854

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7a753ca and a9b5db2.

⛔ Files ignored due to path filters (1)
  • packages/vue-generator/src/templates/vue-template/templateFiles/public/favicon.ico is excluded by !**/*.ico
📒 Files selected for processing (29)
  • mockServer/src/services/app.js (1 hunks)
  • mockServer/src/services/block.js (1 hunks)
  • packages/common/component/BlockDeployDialog.vue (2 hunks)
  • packages/common/js/http.js (3 hunks)
  • packages/common/js/verification.js (1 hunks)
  • packages/configurator/src/js-slot-configurator/JsSlotConfigurator.vue (3 hunks)
  • packages/engine-cli/template/designer/public/mock/bundle.json (1 hunks)
  • packages/plugins/block/src/BlockSetting.vue (2 hunks)
  • packages/plugins/block/src/Main.vue (2 hunks)
  • packages/plugins/block/src/js/blockSetting.jsx (2 hunks)
  • packages/plugins/datasource/src/DataSourceRecordList.vue (1 hunks)
  • packages/plugins/datasource/src/DataSourceRemoteDataResult.vue (2 hunks)
  • packages/plugins/page/src/PageSetting.vue (1 hunks)
  • packages/settings/events/src/components/BindEvents.vue (7 hunks)
  • packages/toolbars/save/src/js/index.js (1 hunks)
  • packages/vue-generator/src/generator/generateApp.js (1 hunks)
  • packages/vue-generator/src/index.d.ts (7 hunks)
  • packages/vue-generator/src/plugins/formatCodePlugin.js (1 hunks)
  • packages/vue-generator/src/plugins/genBlockPlugin.js (1 hunks)
  • packages/vue-generator/src/plugins/genDataSourcePlugin.js (1 hunks)
  • packages/vue-generator/src/plugins/genDependenciesPlugin.js (1 hunks)
  • packages/vue-generator/src/plugins/genGlobalState.js (1 hunks)
  • packages/vue-generator/src/plugins/genI18nPlugin.js (1 hunks)
  • packages/vue-generator/src/plugins/genPagePlugin.js (1 hunks)
  • packages/vue-generator/src/plugins/genRouterPlugin.js (1 hunks)
  • packages/vue-generator/src/plugins/genTemplatePlugin.js (1 hunks)
  • packages/vue-generator/src/plugins/genUtilsPlugin.js (1 hunks)
  • packages/vue-generator/src/plugins/parseSchemaPlugin.js (1 hunks)
  • packages/vue-generator/src/templates/vue-template/index.js (3 hunks)
✅ Files skipped from review due to trivial changes (1)
  • packages/vue-generator/src/plugins/genGlobalState.js
🔇 Additional comments (29)
packages/engine-cli/template/designer/public/mock/bundle.json (1)

Line range hint 1-10700: Component configurations look good

The component definitions are well-structured with proper schema definitions for properties, events, and slots. The configurations follow a consistent pattern across all components.

packages/configurator/src/js-slot-configurator/JsSlotConfigurator.vue (2)

22-22: LGTM! Function names corrected for better clarity.

The typos in function names have been fixed (parmasparams), improving code readability while maintaining the same functionality.

Also applies to: 28-28


178-179: LGTM! Exports updated correctly.

The exports have been updated to reflect the renamed functions.

packages/common/js/verification.js (1)

17-17: ⚠️ Potential issue

Breaking Change: More Restrictive Block Name Validation

The updated regex pattern enforces stricter PascalCase naming with at least two segments (e.g., HelloWorld, UserProfile). This change could potentially break existing block names that were valid under the previous pattern.

Let's verify the impact on existing block names:

✅ Verification successful

Let's also check if there are any test files or documentation that might reference block names:

And let's specifically look at the usage of this regex pattern:


Block Name Pattern Change is Safe to Proceed

Based on the verification results, the regex change appears to be aligned with existing usage and won't cause breaking changes:

  1. The REGEXP_BLOCK_NAME is only used in two places:

    • SaveNewBlock.vue: For validating new block names during creation
    • verification.js: The pattern definition and its verification method
  2. Existing block names found in the codebase (e.g., 'PortalHeader', 'PortalBlock', 'PortalHome', 'BlockFileName') already follow the new PascalCase pattern with two or more segments.

  3. The change actually better enforces the validation message that's already in the UI: "两个单词以上, 且是大写开头驼峰格式" (Two or more words in PascalCase format).

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for block names that would be invalid under the new regex
# Search for block definitions in the codebase and analyze their names

# Find potential block definition files
fd -e js -e jsx -e vue . | while read -r file; do
  # Extract and check block names against both old and new patterns
  rg -i 'block.*name.*["\']([^"\']+)["\']' "$file" -o -r '$1' | while read -r name; do
    if ! echo "$name" | grep -qP '^([A-Z][a-z0-9]*){2,}$'; then
      echo "File: $file"
      echo "Potentially invalid block name under new regex: $name"
    fi
  done
done

Length of output: 269


Script:

#!/bin/bash
# Let's try a simpler approach to find block name patterns
# Search for string patterns that look like block name assignments

# Using ripgrep to find potential block name assignments
rg -i "block.*name.*['\"]([^'\"]+)['\"]" -g "*.{js,jsx,vue}" --no-filename -o

Length of output: 664


Script:

#!/bin/bash
# Search in test files and documentation
rg -i "block" -g "*.{test.js,spec.js,md}" -C 2

Length of output: 12780


Script:

#!/bin/bash
# Find where REGEXP_BLOCK_NAME is used
rg "REGEXP_BLOCK_NAME" -C 2

Length of output: 1465

packages/plugins/datasource/src/DataSourceRemoteDataResult.vue (1)

13-19: LGTM: Monaco editor setup looks good

The Monaco editor component is properly configured with reactive bindings and change handler.

packages/common/component/BlockDeployDialog.vue (2)

84-84: LGTM: Import statement is properly organized

The import statement correctly includes all necessary functions from the meta register.


Line range hint 158-163: Verify block retrieval fallback behavior

The fallback to useBlock().getCurrentBlock() looks good, but we should verify it handles all edge cases.

✅ Verification successful

Based on the search results, I can now generate the final response:

The block retrieval fallback mechanism is properly implemented and safe

The fallback chain getEditBlock() || useBlock().getCurrentBlock() is well-designed because:

  • getEditBlock() is a simple state getter that returns state.block
  • getCurrentBlock() is a reliable fallback that returns the current block from the block state
  • Both functions are used extensively throughout the codebase with proper null checks (note the ?. operators in usage)
  • The fallback pattern is consistently used in other parts of the codebase for similar scenarios
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for potential null/undefined handling in block retrieval
ast-grep --pattern 'getEditBlock()' 

Length of output: 334


Script:

#!/bin/bash
# Let's check the implementation of getEditBlock() and getCurrentBlock()
ast-grep --pattern 'function getEditBlock() {
  $$$
}'

# Also check getCurrentBlock implementation
ast-grep --pattern 'function getCurrentBlock() {
  $$$
}'

# Let's also check for any error handling around these functions
rg "getEditBlock|getCurrentBlock" -A 3

Length of output: 21009

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

85-85: LGTM: Import statement is properly organized

The import of getMergeMeta and useBlock is correctly structured.

packages/settings/events/src/components/BindEvents.vue (3)

20-20: LGTM: Event list display improvements

The changes correctly address the event list display bug by:

  1. Using renderEventList for consistent event iteration
  2. Properly handling localized event labels
  3. Safely accessing nested properties with optional chaining

Also applies to: 25-25, 42-42


126-126: Verify data consistency between customEvents and componentEvent

The refactoring from componentEvents to customEvents and the introduction of renderEventList looks good. However, let's verify there are no edge cases where events might be lost during the merge.

Also applies to: 133-133

✅ Verification successful

No data consistency issues found between customEvents and componentEvents

The code analysis shows a clean implementation where:

  • customEvents is initialized with commonEvents
  • renderEventList properly merges both sources using computed property: { ...state.componentEvent, ...state.customEvents }
  • The AddEventsDialog component validates for duplicate event names before adding new ones
  • The event handling and merging logic maintains data consistency throughout the components
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any other uses of componentEvents to ensure complete migration
rg -A 3 "componentEvents" --type vue

Length of output: 64


Script:

#!/bin/bash
# Search for any uses of componentEvents in all files
rg -A 3 "componentEvents"

Length of output: 1042


Script:

#!/bin/bash
# Search for any uses of customEvents in all files
rg -A 3 "customEvents"

Length of output: 1095


Script:

#!/bin/bash
# Find all .vue files and search their content
fd -e vue -x cat {} | grep -A 3 "componentEvents\|customEvents"

Length of output: 800


143-143: Ensure proper cleanup of event bindings

The event iteration now uses renderEventList.value, but we should verify that old event bindings are properly cleaned up when switching components.

✅ Verification successful

Let me gather more information about the event binding and cleanup logic.


Let me search for the actual BindEvents component content since the previous search found a parent component.


Let me search for any cleanup or unmount related code since we now have the component content.


After analyzing the code and verification results, I can now provide the final response:

Event bindings are properly managed through reactive state

The event bindings are automatically cleaned up through Vue's reactivity system:

  • The watchEffect hook manages the event bindings by synchronizing with renderEventList.value and pageState.currentSchema
  • When switching components, the watchEffect automatically re-executes and updates state.bindActions, effectively cleaning up old bindings
  • The event bindings are stored in component-scoped reactive state that is automatically cleaned up when components are unmounted
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for component switching logic to verify cleanup
ast-grep --pattern 'useCanvas().canvasApi.value.getSchema()'

Length of output: 162


Script:

#!/bin/bash
# Search for event cleanup related code in BindEvents.vue
ast-grep --pattern 'function $name($$$) {
  $$$
  removeEventListener($$$)
  $$$
}'

# Also search for any unmount or beforeDestroy hooks
ast-grep --pattern 'onBeforeUnmount($$$)'

# Look for the full content of BindEvents.vue to understand the context
rg -l "BindEvents.vue" | xargs cat

Length of output: 800


Script:

#!/bin/bash
# Search for the actual BindEvents.vue component content
fd "BindEvents.vue" --exec cat {}

# Also search for any watch or effect related to renderEventList
ast-grep --pattern 'watch($$$renderEventList$$$)'

# Look for cleanup in setup or mounted hooks
ast-grep --pattern 'onMounted($$$)'
ast-grep --pattern 'setup($$$)'

Length of output: 22425


Script:

#!/bin/bash
# Search for onBeforeUnmount or cleanup related code
ast-grep --pattern 'onBeforeUnmount($$$)'

# Look for any cleanup in watchEffect
ast-grep --pattern 'watchEffect($$$)'

# Search for any event removal or cleanup patterns
rg "removeEventListener|cleanup|dispose" -A 2

Length of output: 7679

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

293-294: LGTM: Fixed typo in variable name

Good cleanup: renamed isEdite to isEdit for better code readability.

Also applies to: 297-297, 309-309

packages/plugins/datasource/src/DataSourceRecordList.vue (1)

476-476: LGTM: Improved batch delete button state management

Good addition: The button state is now properly updated after batch delete operation.

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

Line range hint 438-442: LGTM! Improved null safety handling

The addition of optional chaining for public_scope_tenants access is a good defensive programming practice that prevents potential runtime errors.

packages/vue-generator/src/plugins/genTemplatePlugin.js (1)

21-21: Confirmed update to use 'options.template' instead of 'context.template'

The template source has been correctly updated to use options.template rather than context.template, ensuring that the template selection is properly configurable through plugin options.

packages/vue-generator/src/plugins/genPagePlugin.js (1)

18-18: Updated JSDoc type annotation for clarity

The type annotation for the schema parameter now explicitly imports IAppSchema from @opentiny/tiny-engine-dsl-vue, enhancing type clarity and consistency across the codebase.

packages/vue-generator/src/plugins/genDataSourcePlugin.js (1)

18-18: Updated JSDoc type annotation for consistency

The schema parameter type has been updated to import IAppSchema from @opentiny/tiny-engine-dsl-vue, aligning with type definitions used in other plugins.

packages/vue-generator/src/plugins/genBlockPlugin.js (1)

18-18: Consistent type annotation update for 'schema' parameter

The schema parameter now imports IAppSchema, maintaining consistency across the codebase and improving type safety.

packages/vue-generator/src/plugins/parseSchemaPlugin.js (1)

10-10: LGTM! Type import change is consistent.

The change to use imported type improves consistency across the codebase.

packages/vue-generator/src/plugins/genI18nPlugin.js (2)

20-20: LGTM! Type import change aligns with codebase standards.

The change to use imported type maintains consistency with other plugins.


Line range hint 1-1: Verify PR objectives alignment.

The changes in these files only update type imports and don't appear to address the event list bug mentioned in the PR objectives (#747). Please verify if:

  1. There are additional files in the PR that contain the actual bug fixes
  2. These type changes are prerequisites for the bug fixes
  3. The PR description needs to be updated to reflect these type-only changes
packages/vue-generator/src/plugins/genUtilsPlugin.js (1)

45-45: LGTM: Type annotation update is consistent

The change to use an imported type reference improves type clarity and matches similar updates across other files.

✅ Verification successful

Type annotation update is consistently applied across plugin files

The verification confirms that the imported type import('@opentiny/tiny-engine-dsl-vue').IAppSchema is consistently used across all plugin files in the packages/vue-generator/src/plugins/ directory, including:

  • formatCodePlugin.js
  • genUtilsPlugin.js
  • genRouterPlugin.js
  • genPagePlugin.js
  • genI18nPlugin.js
  • genGlobalState.js
  • parseSchemaPlugin.js
  • genDependenciesPlugin.js
  • genBlockPlugin.js
  • genDataSourcePlugin.js
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify consistent type annotation updates across related files
rg -l "import\('@opentiny/tiny-engine-dsl-vue'\)\.IAppSchema" packages/vue-generator/src/plugins/

Length of output: 651

packages/vue-generator/src/plugins/genRouterPlugin.js (1)

39-39: LGTM: Consistent type annotation update

The type annotation change aligns with the standardization across the codebase.

packages/common/js/http.js (2)

61-62: Good defensive programming with optional chaining

The addition of optional chaining operator for updateTreeData prevents potential runtime errors when the method is undefined.


40-40: Verify impact of new parameter

The addition of isCurEditPage parameter changes the function signature. Ensure all callers are updated.

✅ Verification successful

All callers have been updated with the new parameter

Both occurrences of handlePageUpdate calls in the codebase are already passing the new isCurEditPage parameter:

  • packages/toolbars/save/src/js/index.js: Passes true as the fourth argument
  • packages/plugins/page/src/PageSetting.vue: Passes isCurEditPage parameter directly
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Find all calls to handlePageUpdate
rg "handlePageUpdate\(" --type js

Length of output: 272

packages/vue-generator/src/generator/generateApp.js (1)

18-19: LGTM: Type definitions properly imported

The update to import types from '@opentiny/tiny-engine-dsl-vue' improves type safety and documentation clarity.

packages/vue-generator/src/plugins/genDependenciesPlugin.js (1)

66-66: LGTM: Consistent type definition update

The schema parameter type is properly updated to use imported type from '@opentiny/tiny-engine-dsl-vue', maintaining consistency with other files.

packages/toolbars/save/src/js/index.js (1)

61-61: 🛠️ Refactor suggestion

Document the boolean parameters and improve readability

The addition of boolean parameters false, true to handlePageUpdate lacks clarity and documentation. Consider using named variables to make the intent clear:

- await handlePageUpdate(currentPage.id, { ...currentPage, ...params }, false, true)
+ const isForceUpdate = false;
+ const isCurEditPage = true;
+ await handlePageUpdate(
+   currentPage.id,
+   { ...currentPage, ...params },
+   isForceUpdate,
+   isCurEditPage
+ );

Let's verify the usage of these parameters across the codebase:

✅ Verification successful

Let me gather more information about the handlePageUpdate function implementation and its documentation.


Let me try again with correct file type flags:


Based on the search results, I can now provide a final response:

Document the boolean parameters and improve readability

The handlePageUpdate function is imported from @opentiny/tiny-engine-common/js/http and is used in both the save toolbar and page settings. Looking at PageSetting.vue, we can see that:

  • routerChange indicates if the page's route has changed
  • isCurEditPage indicates if the update is for the currently edited page

Suggested improvement:

- await handlePageUpdate(currentPage.id, { ...currentPage, ...params }, false, true)
+ const hasRouteChanged = false;
+ const isCurrentEditPage = true;
+ await handlePageUpdate(
+   currentPage.id,
+   { ...currentPage, ...params },
+   hasRouteChanged,
+   isCurrentEditPage
+ );
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other calls to handlePageUpdate to understand parameter usage
rg -A 2 "handlePageUpdate\(" 

# Search for documentation of handlePageUpdate
ast-grep --pattern 'function handlePageUpdate($_) {
  $$$
}'

Length of output: 530


Script:

#!/bin/bash
# Search for handlePageUpdate function definition and its documentation
rg -B 5 -A 10 "handlePageUpdate" --type ts --type js --type vue

# Search for any JSDoc or comment blocks related to handlePageUpdate
rg -B 3 "handlePageUpdate" --type ts --type js --type vue

Length of output: 177


Script:

#!/bin/bash
# Search for handlePageUpdate function definition and its documentation
rg -B 5 -A 10 "handlePageUpdate"

# Look for any exports or declarations of handlePageUpdate
ast-grep --pattern 'export $_$ handlePageUpdate'

# Look for any JSDoc comments above handlePageUpdate
rg -B 3 "@param.*handlePageUpdate|/\*\*.*handlePageUpdate"

Length of output: 5812

packages/plugins/page/src/PageSetting.vue (1)

213-215: LGTM! The isCurEditPage check aligns with PR objectives.

The addition of isCurEditPage parameter helps track the currently edited page, which is essential for fixing the event list display bug mentioned in issue #747.

packages/plugins/block/src/BlockSetting.vue Show resolved Hide resolved
packages/vue-generator/src/index.d.ts 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: 0

🧹 Outside diff range and nitpick comments (2)
packages/settings/events/src/components/BindEvents.vue (2)

118-118: Add safety check for commonEvents destructuring

While the changes look good overall, consider adding a safety check for the commonEvents destructuring to handle potential undefined values.

-    const { commonEvents = {} } = getMergeMeta('engine.setting.event').options
+    const { options = {} } = getMergeMeta('engine.setting.event') || {}
+    const { commonEvents = {} } = options

Also applies to: 126-126, 133-133


Line range hint 231-248: Consider improving event addition structure

The handleAddEvent method could be improved to:

  1. Validate event name uniqueness
  2. Support multiple locales
  3. Use a more maintainable event structure
     const handleAddEvent = (params) => {
       const { eventName, eventDescription } = params
+      
+      if (renderEventList.value[eventName]) {
+        // Consider showing a warning to the user
+        return
+      }
 
       Object.assign(state.customEvents, {
         [eventName]: {
           label: {
-            zh_CN: eventDescription
+            [locale]: eventDescription
           },
           description: {
-            zh_CN: `${eventDescription}的回调函数`
+            [locale]: `${eventDescription}的回调函数`
           },
           type: 'event',
           functionInfo: {
             params: [],
             returns: {}
           },
           defaultValue: ''
         }
       })
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a9b5db2 and dc8dc91.

📒 Files selected for processing (1)
  • packages/settings/events/src/components/BindEvents.vue (7 hunks)
🔇 Additional comments (4)
packages/settings/events/src/components/BindEvents.vue (4)

20-25: LGTM: Event list rendering improvements

The changes correctly address the event list update issue by using the computed renderEventList property and adding proper locale support. The optional chaining operators (?.) appropriately handle potential undefined values.


Line range hint 143-177: LGTM: Improved event list synchronization

The watchEffect implementation correctly synchronizes the event list with the currently selected component, addressing the core issue from PR #747.


259-261: LGTM: Necessary exports added

The addition of renderEventList and locale to the component's exports is correct and necessary for the template functionality.


135-142: Verify the fix for component switching

The implementation looks correct, but let's verify that the event list properly updates when switching components.

✅ Verification successful

Component switching implementation verified successfully

The implementation in BindEvents.vue correctly handles component switching through a robust watchEffect that:

  1. Properly retrieves the new component's schema and events when component changes
  2. Safely handles undefined values with optional chaining
  3. Correctly merges component events with custom events via the renderEventList computed property
  4. Properly resets and rebuilds the bindActions state when switching components
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for other potential component switching issues in the codebase

# Look for similar patterns of component switching and event list updates
rg -l "currentSchema.*componentName" --type vue

# Check for any related issues or PRs
gh issue list --search "in:title event list component switch"
gh pr list --search "in:title event list component switch"

Length of output: 202


Script:

#!/bin/bash
# Search for component switching patterns using ripgrep without file type filter
rg -l "currentSchema.*componentName"

# Search for watchEffect usage with component switching
rg "watchEffect.*currentSchema" -A 5

# Look for event-related component switching logic
rg "componentEvent.*schema" -A 3

Length of output: 686


Script:

#!/bin/bash
# Check the implementation of BindEvents.vue to understand the component switching logic
cat packages/settings/events/src/components/BindEvents.vue

# Look for any related test files
fd "BindEvents.test" -t f
fd "BindEvents.spec" -t f

# Check for any material-related utility functions
rg "getMaterial" -A 3

Length of output: 21617

Copy link
Collaborator

@gene9831 gene9831 left a comment

Choose a reason for hiding this comment

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

LGTM

@kevinmoch kevinmoch merged commit 983b510 into opentiny:refactor/develop Dec 4, 2024
1 check passed
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.

8 participants