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

Feat router page embedded view toggle #1010

Merged

Conversation

rhlin
Copy link
Collaborator

@rhlin rhlin commented Jan 9, 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

允许用户切换 路由嵌套模式编辑或者单页模式编辑, 方便在父页面尚未编辑好的情况下进行局部编辑

What is the current behavior?

没有这个入口 ,需要父页面提供router-view组件才能编辑

Issue Number: N/A

What is the new behavior?

  1. 新增一个切换按钮 如图, 点击后能实现 嵌套视图和单页视图之间的切换, 并且做了localstorage缓存
    image
  2. 修复切换中英文无效
  3. 增加浏览器地址栏前进后退的监听

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

Summary by CodeRabbit

  • New Features

    • Added a View Setting toolbar that allows switching between embedded and standalone view modes
    • Introduced URL change handling in the design canvas
    • Enhanced routing and localization capabilities
  • Improvements

    • Updated toolbar configuration to include new View Setting option
    • Improved module resolution and import paths
    • Added broadcast channel for view mode synchronization
  • Technical Updates

    • Integrated new router view setting functionality
    • Added path mappings for easier module imports
    • Updated constants and utility functions to support new features

Copy link
Contributor

coderabbitai bot commented Jan 9, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

🗂️ Base branches to auto review (3)
  • refactor/develop
  • ospp-*
  • release/*

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This pull request introduces a new ViewSetting toolbar component to the TinyEngine framework. The changes span multiple files across the project, adding support for switching between embedded and standalone view modes. The implementation includes creating a new toolbar module, updating configuration files, modifying import paths, and integrating the new component into the existing layout and rendering systems. The changes enhance the application's flexibility by providing users with a way to toggle between different view perspectives.

Changes

File Change Summary
designer-demo/registry.js Added ViewSetting import and integrated into toolbar configuration
jsconfig.json Added path mappings for @opentiny/tiny-engine-toolbar-view-setting
packages/design-core/index.js New export for ViewSetting component
packages/design-core/package.json Added dependency for @opentiny/tiny-engine-toolbar-view-setting
packages/layout/index.js Updated toolbars.collapse configuration
packages/toolbars/view-setting/* New toolbar module with component, metadata, and configuration files
packages/utils/src/constants/index.js Added new constants for router view setting

Sequence Diagram

sequenceDiagram
    participant User
    participant Toolbar
    participant BroadcastChannel
    participant LocalStorage
    
    User->>Toolbar: Click View Mode Toggle
    Toolbar->>LocalStorage: Update View Mode
    Toolbar->>BroadcastChannel: Broadcast View Mode Change
    BroadcastChannel->>Toolbar: Confirm Mode Change
    Toolbar->>User: Update UI to Reflect New Mode
Loading

Possibly related PRs

Suggested labels

enhancement, ready_for_review

Suggested reviewers

  • hexqi

Poem

🐰 A rabbit's view of change so bright,
Embedded or standalone, take flight!
Toolbars dance with newfound grace,
Switching modes at gentle pace.
Code hops forward, clear and light! 🚀


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.

…add fallback for cache value getter in toolbar, fix typo mistake
@gene9831
Copy link
Collaborator

@coderabbitai review

Copy link
Contributor

coderabbitai bot commented Jan 10, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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: 4

🧹 Nitpick comments (3)
packages/toolbars/view-setting/meta.js (1)

1-12: Consider adding i18n support for the title.

The configuration looks good and follows the toolbar component structure. However, consider internationalizing the 'viewSetting' title to support multiple languages.

packages/canvas/render/src/canvas-function/router-view-setting.ts (1)

15-21: Add error logging for invalid view mode values.

While the validation logic is correct, consider logging invalid values to help with debugging.

 function getCacheValue() {
   const value = localStorage.getItem(CANVAS_ROUTER_VIEW_SETTING_VIEW_MODE_KEY)
   if (!(Object.values(ViewMode) as string[]).includes(value)) {
+    console.warn(`Invalid view mode value: ${value}, defaulting to EMBEDDED`)
     return ViewMode.EMBEDDED
   }
   return value as ViewMode
 }
packages/toolbars/view-setting/src/Main.vue (1)

20-29: Consider enhancing type safety and reusability.

The cache utility functions work correctly but could benefit from:

  1. Type safety using TypeScript or JSDoc type annotations
  2. Reusability by exporting them for use in other components

Example enhancement:

+/** @typedef {'embedded' | 'standalone'} ViewMode */

+/**
+ * @returns {ViewMode}
+ */
 function getCacheValue() {
   const value = localStorage.getItem(CANVAS_ROUTER_VIEW_SETTING_VIEW_MODE_KEY)
   if (!['embedded', 'standalone'].includes(value)) {
     return 'embedded'
   }
   return value
 }

+/**
+ * @param {ViewMode} value
+ */
 function setCacheValue(value) {
   localStorage.setItem(CANVAS_ROUTER_VIEW_SETTING_VIEW_MODE_KEY, value)
 }

+export { getCacheValue, setCacheValue }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between dceffa9 and ebba65a.

📒 Files selected for processing (17)
  • designer-demo/registry.js (3 hunks)
  • jsconfig.json (2 hunks)
  • packages/build/vite-config/src/vite-plugins/devAliasPlugin.js (1 hunks)
  • packages/canvas/DesignCanvas/src/DesignCanvas.vue (2 hunks)
  • packages/canvas/render/src/RenderMain.ts (4 hunks)
  • packages/canvas/render/src/canvas-function/index.ts (1 hunks)
  • packages/canvas/render/src/canvas-function/router-view-setting.ts (1 hunks)
  • packages/design-core/index.js (1 hunks)
  • packages/design-core/package.json (1 hunks)
  • packages/engine-cli/template/designer/registry.js (3 hunks)
  • packages/layout/index.js (1 hunks)
  • packages/toolbars/view-setting/index.js (1 hunks)
  • packages/toolbars/view-setting/meta.js (1 hunks)
  • packages/toolbars/view-setting/package.json (1 hunks)
  • packages/toolbars/view-setting/src/Main.vue (1 hunks)
  • packages/toolbars/view-setting/vite.config.js (1 hunks)
  • packages/utils/src/constants/index.js (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • packages/canvas/render/src/canvas-function/index.ts
  • packages/toolbars/view-setting/index.js
🔇 Additional comments (17)
packages/layout/index.js (1)

26-27: LGTM! Appropriate placement in the collapse section.

The viewSetting toolbar is correctly integrated into the collapse section, following the established pattern and positioned logically after the language selector.

packages/canvas/render/src/canvas-function/router-view-setting.ts (1)

7-13: LGTM! Well-structured type definitions.

The ViewMode enum and IRouterViewSetting interface provide good type safety and follow TypeScript best practices.

packages/toolbars/view-setting/vite.config.js (1)

20-38: LGTM! Well-configured Vite setup.

The Vite configuration is properly set up with:

  • Appropriate plugins for Vue and JSX
  • Correct library build configuration
  • Proper external dependency handling
packages/toolbars/view-setting/src/Main.vue (2)

1-9: LGTM! Clean template implementation with proper fallback.

The template effectively uses the ToolbarBase component with dynamic content and proper icon fallback handling.


11-18: LGTM! Well-organized imports and constants.

The imports are properly structured and the constants are appropriately destructured from the utils package.

packages/engine-cli/template/designer/registry.js (1)

17-17: LGTM! Proper integration of ViewSetting toolbar.

The ViewSetting component is correctly imported and integrated into both the toolbars array and collapse section, following the existing pattern.

Also applies to: 74-75, 101-102

designer-demo/registry.js (1)

17-17: LGTM! Consistent toolbar configuration.

The ViewSetting integration matches the configuration in packages/engine-cli/template/designer/registry.js, maintaining consistency across registry files.

Also applies to: 74-75, 101-102

packages/design-core/index.js (1)

7-7: LGTM! Proper export configuration.

The ViewSetting component is correctly exported following the existing pattern of on-demand exports.

packages/utils/src/constants/index.js (1)

96-97: LGTM! Constants follow the established patterns.

The new constants are well-structured and maintain consistency with existing patterns by using CHANNEL_UID for uniqueness.

Also applies to: 101-101

packages/build/vite-config/src/vite-plugins/devAliasPlugin.js (1)

39-39: LGTM! Alias follows the established pattern.

The new alias is properly structured and maintains alphabetical order among other toolbar aliases.

packages/canvas/DesignCanvas/src/DesignCanvas.vue (2)

15-16: LGTM! Template structure improved.

The addition of the proper closing tag enhances template readability and structure.


213-222: Consider moving URL change handling to getBaseInfo.

The URL change handling logic is well-implemented with proper lifecycle management, but as noted in the TODO comment, it should be moved to getBaseInfo.

Let's verify if getBaseInfo is the appropriate location:

✅ Verification successful

Moving URL change handling to getBaseInfo is the right approach

The review comment is correct. The URL change handling should be moved to getBaseInfo in packages/common/composable/defaultGlobalService.js because:

  • getBaseInfo is already the central place for URL parameter management
  • Other components rely on getBaseInfo for accessing URL parameters
  • Moving the logic there would ensure consistent URL handling across the application
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for getBaseInfo implementation and related URL handling
ast-grep --pattern 'function getBaseInfo() {
  $$$
}'

# Check for similar URL handling patterns
rg -A 5 'postLocationHistoryChanged'

Length of output: 3883


Script:

#!/bin/bash
# Search for baseInfo related files and implementations
fd -t f baseInfo
rg -i "baseinfo|base.info" --type vue --type js -A 5

# Look for similar URL parameter handling
rg "URLSearchParams|location.search" --type vue --type js

Length of output: 189


Script:

#!/bin/bash
# Search for baseInfo related files and implementations
fd baseInfo
rg -i "baseinfo|base.info" -A 5

# Look for similar URL parameter handling
rg "URLSearchParams|location.search"

Length of output: 22771

packages/canvas/render/src/RenderMain.ts (2)

14-22: LGTM! Enhanced routing and localization capabilities.

The addition of useRouterViewSetting and useLocale improves the component's functionality, and the renderer variable rename enhances code clarity.

Also applies to: 90-91


137-145: Well-structured page ancestor handling with view mode support.

The updatePageAncestor function properly handles the standalone mode case, and the watcher ensures updates when the view mode changes.

Let's verify the view mode handling:

Also applies to: 158-163

✅ Verification successful

View mode and ancestor handling implementation verified

The implementation correctly handles standalone mode and properly manages page ancestors with appropriate error handling and type safety.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for other view mode dependencies
rg -A 5 'viewMode.*standalone'

# Search for related ancestor handling
ast-grep --pattern 'function getPageAncestors($$$) {
  $$$
}'

Length of output: 1582

packages/toolbars/view-setting/package.json (1)

27-31: LGTM! Dependencies are well-structured

The dependencies are properly organized with workspace references for internal packages and specific versions for external ones. The peer dependencies correctly specify the required Vue version.

Also applies to: 38-41

jsconfig.json (1)

26-26: LGTM! Path mappings are correctly configured

The new path mappings for the view-setting toolbar follow the established pattern and are properly placed in alphabetical order among other toolbar mappings.

Also applies to: 55-55

packages/design-core/package.json (1)

79-79: LGTM! Dependency correctly added

The view-setting toolbar dependency is properly added using workspace reference and maintains the established ordering pattern.

Comment on lines +23 to +39
export function useRouterViewSetting() {
const routerViewSetting = reactive<IRouterViewSetting>({
viewMode: getCacheValue()
})

const { data } = useBroadcastChannel<IRouterViewSetting, IRouterViewSetting>({
name: BROADCAST_CHANNEL.CanvasRouterViewSetting
})

watch(data, () => {
routerViewSetting.viewMode = data.value.viewMode
})

return {
routerViewSetting
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider adding cleanup for broadcast channel subscription.

The implementation looks good, but the broadcast channel subscription should be cleaned up when the component is unmounted.

 export function useRouterViewSetting() {
   const routerViewSetting = reactive<IRouterViewSetting>({
     viewMode: getCacheValue()
   })

   const { data, cleanup } = useBroadcastChannel<IRouterViewSetting, IRouterViewSetting>({
     name: BROADCAST_CHANNEL.CanvasRouterViewSetting
   })

   watch(data, () => {
     routerViewSetting.viewMode = data.value.viewMode
   })

   return {
     routerViewSetting,
+    cleanup
   }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export function useRouterViewSetting() {
const routerViewSetting = reactive<IRouterViewSetting>({
viewMode: getCacheValue()
})
const { data } = useBroadcastChannel<IRouterViewSetting, IRouterViewSetting>({
name: BROADCAST_CHANNEL.CanvasRouterViewSetting
})
watch(data, () => {
routerViewSetting.viewMode = data.value.viewMode
})
return {
routerViewSetting
}
}
export function useRouterViewSetting() {
const routerViewSetting = reactive<IRouterViewSetting>({
viewMode: getCacheValue()
})
const { data, cleanup } = useBroadcastChannel<IRouterViewSetting, IRouterViewSetting>({
name: BROADCAST_CHANNEL.CanvasRouterViewSetting
})
watch(data, () => {
routerViewSetting.viewMode = data.value.viewMode
})
return {
routerViewSetting,
cleanup
}
}

packages/toolbars/view-setting/src/Main.vue Show resolved Hide resolved
Comment on lines +42 to +46
const viewMode = ref(getCacheValue())
const { post, data } = useBroadcastChannel({ name: BROADCAST_CHANNEL.CanvasRouterViewSetting })
watch(data, () => {
viewMode.value = data.value
})
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add cleanup for broadcast channel subscription.

The broadcast channel subscription should be cleaned up when the component is unmounted to prevent memory leaks.

 setup() {
   const viewMode = ref(getCacheValue())
   const { post, data } = useBroadcastChannel({ name: BROADCAST_CHANNEL.CanvasRouterViewSetting })
-  watch(data, () => {
+  const stopWatch = watch(data, () => {
     viewMode.value = data.value
   })
+  
+  onUnmounted(() => {
+    stopWatch()
+  })

Committable suggestion skipped: line range outside the PR's diff.

"repository": {
"type": "git",
"url": "https://github.com/opentiny/tiny-engine",
"directory": "packages/toolbars/lang"
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix incorrect repository directory path

The directory field in the repository configuration points to packages/toolbars/lang instead of packages/toolbars/view-setting.

-    "directory": "packages/toolbars/lang"
+    "directory": "packages/toolbars/view-setting"
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
"directory": "packages/toolbars/lang"
"directory": "packages/toolbars/view-setting"

@gene9831 gene9831 merged commit ab4e7dc into opentiny:feat/router-page Jan 10, 2025
@coderabbitai coderabbitai bot mentioned this pull request Jan 24, 2025
14 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants