Skip to content

feat: RouteView support switching preview#1117

Merged
hexqi merged 9 commits intoopentiny:refactor/developfrom
gene9831:feat/routerview-switch-preview
Feb 18, 2025
Merged

feat: RouteView support switching preview#1117
hexqi merged 9 commits intoopentiny:refactor/developfrom
gene9831:feat/routerview-switch-preview

Conversation

@gene9831
Copy link
Collaborator

@gene9831 gene9831 commented Feb 13, 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?

Issue Number: N/A

What is the new behavior?

路由视图组件支持切换显示页面

image

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

Summary by CodeRabbit

  • New Features

    • Introduced an interactive viewer switcher that provides a new popover interface for choosing canvas preview modes.
    • Added a new component, CanvasViewerSwitcher, to enhance canvas interactivity.
    • Implemented new functions for improved page management and navigation.
  • Refactor

    • Enhanced page navigation with improved confirmation prompts and preview management.
    • Upgraded canvas rendering to support dynamic page-specific attributes.
    • Optimized URL parameter handling and streamlined page hierarchy management for a more consistent navigation experience.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 13, 2025

Walkthrough

This pull request integrates a new component, CanvasViewerSwitcher, into the canvas container and updates related components to adjust page-switching behaviors. The CanvasViewerSwitcher provides a popover interface for preview mode selection. Additionally, method calls in CanvasMenu.vue and CanvasRouterJumper.vue have been updated to include a boolean flag for controlling preview clearing. Changes in the render modules propagate a new pageId property, while URL parameter management has been consolidated into a single updateParams function. New utility functions enhance control over folder flattening and child page retrieval.

Changes

Files Change Summary
packages/canvas/container/src/CanvasContainer.vue
packages/canvas/container/src/components/CanvasMenu.vue
packages/canvas/container/src/components/CanvasRouterJumper.vue
packages/canvas/container/src/components/CanvasViewerSwitcher.vue
packages/canvas/container/src/container.js
- Added new component CanvasViewerSwitcher (import and registration in CanvasContainer.vue).
- Updated page switch calls in CanvasMenu.vue and CanvasRouterJumper.vue to include a boolean flag (true).
- Modified inactive element logic in container.js to require NODE_UID along with NODE_TAG.
packages/canvas/render/src/builtin/CanvasRouterView.vue
packages/canvas/render/src/render.ts
- Injected and passed new reactive pageId property in CanvasRouterView.vue.
- Added data-te-page-id binding in render.ts to propagate page context.
packages/common/composable/defaultGlobalService.js - Consolidated URL parameter updates with a new updateParams function.
- Updated update functions for pageId, blockId, and previewId to use updateParams.
packages/plugins/page/src/composable/usePage.js - Introduced flatternFolder and getPageChildren functions.
- Updated switchPage and switchPageWithConfirm methods to include a clearPreview parameter.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant CVS as CanvasViewerSwitcher
    participant PS as Preview Service
    U->>CVS: Click viewer switch control
    CVS->>CVS: Execute handleClick and display popover
    U->>CVS: Select a preview option
    CVS->>PS: Invoke handleSwitchPreview to update preview ID
Loading
sequenceDiagram
    participant U as User
    participant CM as CanvasMenu/CanvasRouterJumper
    participant UP as usePage Module
    participant GS as Global Service
    U->>CM: Initiate page switch action
    CM->>UP: Call switchPageWithConfirm(pageId, true)
    UP->>GS: Update URL parameters via updateParams
Loading

Possibly related PRs

  • Feat router page embedded view toggle #1010: The changes in the main PR, which introduce the CanvasViewerSwitcher component in CanvasContainer.vue, are related to the retrieved PR that adds a toggle functionality for view modes, as both involve managing view states and user interactions within the canvas application.
  • feat: add canvas route bar #967: The changes in the main PR, which introduce the CanvasViewerSwitcher component in CanvasContainer.vue, are related to the modifications in the retrieved PR that also involve routing and page-switching functionalities, particularly through the switchPage and switchPageWithConfirm methods, as both PRs enhance the interactive capabilities of the canvas application.
  • feat(canvas, plugin, toolbars, generte-code, preview): add router page support #1011: The changes in the main PR, which introduce the CanvasViewerSwitcher component and modify the CanvasContainer.vue, are related to the retrieved PR as both involve the addition of new components (CanvasRouterJumper and CanvasViewerSwitcher) and enhancements to the routing functionality within the canvas application.

Suggested reviewers

  • hexqi
  • rhlin

Poem

I'm a happy rabbit hopping in the code,
With new viewer switches lighting up the node.
Popovers pop while pages gracefully switch,
Parameter updates clear each glitch.
I munch on carrots and cheer every commit,
Hopping through changes with a joyful little skip!
🥕🐇

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

packages/canvas/container/src/components/CanvasViewerSwitcher.vue

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "@typescript-eslint/eslint-plugin".

(The package "@typescript-eslint/eslint-plugin" was not found when loaded as a Node module from the directory "/packages/canvas".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install @typescript-eslint/eslint-plugin@latest --save-dev

The plugin "@typescript-eslint/eslint-plugin" was referenced from the config file in "packages/canvas/.eslintrc.cjs » @vue/eslint-config-typescript".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.


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.

@gene9831 gene9831 changed the title Feat/routerview switch preview feat:RouteView support switching preview Feb 17, 2025
@gene9831 gene9831 changed the title feat:RouteView support switching preview feat: RouteView support switching preview Feb 17, 2025
@github-actions github-actions bot added the enhancement New feature or request label Feb 17, 2025
@gene9831 gene9831 marked this pull request as ready for review February 17, 2025 03:28
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (8)
packages/canvas/render/src/builtin/CanvasRouterView.vue (2)

2-2: Consider internationalizing the placeholder text.

The placeholder text "路由子页面显示位置占位符" is in Chinese. Consider using an internationalization system for better global accessibility.


5-23: LGTM! Clean implementation of page context injection.

The setup function cleanly injects the pageContext and exposes the pageId for template usage. The optional chaining on pageContext access provides good null safety.

However, consider adding TypeScript type annotations for better type safety and documentation:

-  setup() {
+  setup(): { pageId: string | undefined } {
     const pageContext = inject('pageContext')?.pageId
     
     return { pageId }
   }
packages/canvas/container/src/components/CanvasViewerSwitcher.vue (3)

69-75: Consider extracting view mode constants.

The view mode values ('embedded', 'standalone') are hardcoded. Consider extracting these to constants for better maintainability.

+const VIEW_MODES = {
+  EMBEDDED: 'embedded',
+  STANDALONE: 'standalone'
+} as const;

 function getCacheValue() {
   const value = localStorage.getItem(CANVAS_ROUTER_VIEW_SETTING_VIEW_MODE_KEY)
-  if (!['embedded', 'standalone'].includes(value)) {
-    return 'embedded'
+  if (!Object.values(VIEW_MODES).includes(value)) {
+    return VIEW_MODES.EMBEDDED
   }
   return value
 }

98-120: Consider debouncing the handleClick function.

The setTimeout usage for showing the popover could be replaced with a debounced function to handle rapid clicks more elegantly.

+import { debounce } from 'lodash-es'

+const debouncedShow = debounce((popover) => {
+  popover?.doShow()
+}, 0)

 const handleClick = async () => {
   if (state.disabled) {
     return
   }

   const pageId = state.usedHoverState.element.getAttribute('data-te-page-id')
   const children = await usePage().getPageChildren(pageId)

   state.previewOptions = [{ id: pageId, label: '路由子页面占位符', icon: 'box' }].concat(
     children.map(({ id, name }) => ({
       id: String(id),
       label: name,
       icon: 'text-page-common'
     }))
   )

   key.value++

-  setTimeout(() => {
-    popoverRef.value?.doShow()
-  }, 0)
+  debouncedShow(popoverRef.value)
 }

131-136: Consider extracting complex condition to a computed property.

The hover state filtering logic is complex and could be more readable as a computed property.

+const isValidHoverState = ({ componentName, element }) => 
+  COMPONENT_WHITELIST.includes(componentName) &&
+  element.ownerDocument.querySelector('div[data-page-active="true"]')?.contains(element) &&
+  element.getAttribute('data-page-active') !== 'true'

 watch(
   () => [props.hoverState, props.inactiveHoverState],
   ([hoverState, inactiveHoverState]) => {
-    state.usedHoverState = [inactiveHoverState, hoverState].find(
-      ({ componentName, element }) =>
-        COMPONENT_WHITELIST.includes(componentName) &&
-        element.ownerDocument.querySelector('div[data-page-active="true"]')?.contains(element) &&
-        element.getAttribute('data-page-active') !== 'true'
-    )
+    state.usedHoverState = [inactiveHoverState, hoverState].find(isValidHoverState)
packages/plugins/page/src/composable/usePage.js (3)

310-335: LGTM! The flatternFolder function is well-implemented.

The recursive implementation effectively flattens nested folder structures while maintaining route paths.

Consider adding more detailed JSDoc type information for the return value:

/**
 * 打平数组内的文件夹,确保返回的数组每个都是页面而不是文件夹
 * @param {Array<{isPage: boolean, children?: any[]} & Record<string, any>} pagesOrFolders 页面或者文件夹数组
+ * @returns {Array<{isPage: boolean} & Record<string, any>>} 扁平化后的页面数组
 */

337-354: Add error handling for invalid page nodes.

The function should handle cases where the page node is not found in the mapping.

Apply this diff to improve error handling:

 const getPageChildren = async (id) => {
   if (pageSettingState.pages.length === 0) {
     await getPageList()
   }

   const pageNode = pageSettingState.treeDataMapping[id]
+  if (!pageNode) {
+    throw new Error(`Page node with id ${id} not found`)
+  }

   if (!Array.isArray(pageNode?.children)) {
     return []
   }

   return flatternFolder(pageNode.children)
 }

365-408: Consider adding error handling for the page switch operation.

While the function works correctly, it would be beneficial to handle potential edge cases during the page switch operation.

 const switchPage = (pageId, clearPreview = false) => {
+  try {
     // 切换页面时清空 选中节点信息状态
     clearCurrentState()
 
     // pageId !== 0 防止 pageId 为 0 的时候判断不出来
     if (pageId !== 0 && !pageId) {
       if (clearPreview) {
         getMetaApi(META_SERVICE.GlobalService).updateParams({ pageId: '', previewId: '' })
       } else {
         getMetaApi(META_SERVICE.GlobalService).updatePageId('')
       }
       useCanvas().initData({ componentName: COMPONENT_NAME.Page }, {})
       useLayout().layoutState.pageStatus = {
         state: 'empty',
         data: {}
       }
 
       return
     }
 
     return http
       .fetchPageDetail(pageId)
       .then((data) => {
         if (data.isPage) {
           // 应该改成让 Breadcrumb 插件去监听变化
           useBreadcrumb().setBreadcrumbPage([data.name])
         }
 
         if (clearPreview) {
           getMetaApi(META_SERVICE.GlobalService).updateParams({ pageId, previewId: '' })
         } else {
           getMetaApi(META_SERVICE.GlobalService).updatePageId(pageId)
         }
         useLayout().closePlugin()
         useLayout().layoutState.pageStatus = getCanvasStatus(data.occupier)
         useCanvas().initData(data['page_content'], data)
       })
       .catch(() => {
         useNotify({
           type: 'error',
           message: '切换页面失败,目标页面不存在'
         })
       })
+  } catch (error) {
+    useNotify({
+      type: 'error',
+      message: `页面切换时发生错误: ${error.message}`
+    })
+    return Promise.reject(error)
+  }
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4429189 and 486a763.

📒 Files selected for processing (9)
  • packages/canvas/container/src/CanvasContainer.vue (3 hunks)
  • packages/canvas/container/src/components/CanvasMenu.vue (1 hunks)
  • packages/canvas/container/src/components/CanvasRouterJumper.vue (1 hunks)
  • packages/canvas/container/src/components/CanvasViewerSwitcher.vue (1 hunks)
  • packages/canvas/container/src/container.js (1 hunks)
  • packages/canvas/render/src/builtin/CanvasRouterView.vue (2 hunks)
  • packages/canvas/render/src/render.ts (1 hunks)
  • packages/common/composable/defaultGlobalService.js (2 hunks)
  • packages/plugins/page/src/composable/usePage.js (6 hunks)
🧰 Additional context used
🧠 Learnings (2)
packages/canvas/container/src/components/CanvasMenu.vue (1)
Learnt from: rhlin
PR: opentiny/tiny-engine#1011
File: packages/canvas/container/src/components/CanvasMenu.vue:228-232
Timestamp: 2025-01-14T04:29:26.886Z
Learning: Error handling for page switching is centralized in the `switchPageWithConfirm` method of the page service, rather than being duplicated in UI handlers like menu actions.
packages/canvas/container/src/components/CanvasRouterJumper.vue (1)
Learnt from: rhlin
PR: opentiny/tiny-engine#1001
File: packages/canvas/container/src/components/CanvasRouterJumper.vue:43-47
Timestamp: 2025-01-10T02:09:37.792Z
Learning: In the tiny-engine codebase, the `switchPage` function from `@opentiny/tiny-engine-meta-register` already implements validation at the source, so additional error handling is not needed when calling this function.
🪛 Biome (1.9.4)
packages/common/composable/defaultGlobalService.js

[error] 96-97: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

🔇 Additional comments (17)
packages/canvas/render/src/render.ts (1)

262-262: LGTM! Consistent page identification implementation.

The addition of data-te-page-id attribute aligns with the changes in CanvasRouterView.vue, providing consistent page identification throughout the rendering system.

packages/canvas/container/src/components/CanvasRouterJumper.vue (1)

43-47: LGTM! Clear preview state on page jump.

The addition of the true parameter to switchPage ensures the preview state is cleared when jumping to a new page, which is the correct behavior.

packages/common/composable/defaultGlobalService.js (3)

64-92: Well-structured parameter filtering logic.

The filterParams function effectively handles mutual exclusivity between pageId and blockId, and only returns parameters that have actually changed.


94-135: Comprehensive URL parameter management.

The updateParams function provides a robust solution for managing URL parameters with proper handling of parameter conflicts and state updates.

🧰 Tools
🪛 Biome (1.9.4)

[error] 96-97: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


137-147: Clean API for parameter updates.

The simplified parameter update functions provide a clear and consistent interface while leveraging the consolidated logic.

packages/canvas/container/src/components/CanvasMenu.vue (1)

228-232: LGTM! Consistent page switching behavior.

The addition of the true parameter to switchPageWithConfirm maintains consistency with other components' page switching behavior.

packages/canvas/container/src/CanvasContainer.vue (4)

13-13: LGTM! The CanvasViewerSwitcher component is well integrated.

The component is properly positioned in the template and receives consistent props (hoverState and inactiveHoverState) matching the pattern of other similar components.


43-43: LGTM! Component registration is properly handled.

The import statement and component registration in the components object follow the established patterns.

Also applies to: 69-77


13-13: LGTM! The CanvasViewerSwitcher component is properly integrated.

The component is correctly positioned in the template and follows the same pattern as other canvas components by receiving the hover state props.


43-43: LGTM! The component is properly imported and registered.

The import statement and component registration follow the project's conventions.

Also applies to: 69-77

packages/plugins/page/src/composable/usePage.js (5)

365-408: LGTM! The switchPage function update is well-implemented.

The addition of the clearPreview parameter provides good control over preview state management while maintaining backward compatibility with the default value.


410-438: LGTM! The switchPageWithConfirm function update is consistent.

The function properly propagates the clearPreview parameter to switchPage while maintaining the confirmation logic.


310-335: LGTM! The flatternFolder function is well-implemented.

The recursive implementation correctly handles nested folder structures while preserving route path hierarchy. The early return optimization for arrays without folders is a nice touch.


337-354: LGTM! The getPageChildren function is properly implemented.

The function correctly retrieves and flattens child pages, with proper null checks and array handling.


410-438: LGTM! The switchPageWithConfirm function handles unsaved changes properly.

The function correctly prompts for confirmation when there are unsaved changes and properly propagates the clearPreview parameter.

packages/canvas/container/src/container.js (2)

243-243: LGTM! The condition for RouterView elements is more precise.

The updated condition correctly identifies RouterView elements by checking both the NODE_TAG and NODE_UID attributes, preventing false positives in inactive element detection.


243-243: LGTM! The RouterView element check is improved.

The additional check for NODE_UID attribute ensures that RouterView elements are correctly identified as active or inactive elements.

@gene9831
Copy link
Collaborator Author

@coderabbitai review all code

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 17, 2025

@gene9831 I'll review all the code changes in detail.

✅ 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.

@gene9831 gene9831 added this to the v2.3.0 milestone Feb 17, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (6)
packages/canvas/container/src/components/CanvasViewerSwitcher.vue (6)

17-17: Internationalize hard-coded text strings.

The text strings "显示为" are hard-coded in Chinese. Consider using an i18n solution for better internationalization support.

Also applies to: 28-28


11-25: Enhance accessibility support.

The component lacks proper accessibility attributes:

  1. Add role="button" to the clickable div
  2. Add aria-label for the icon button
  3. Add role="menu" to the options container
  4. Add role="menuitem" to each option
       <div
         v-show="state.show"
         :class="{
           'action-wrapper': true,
           disabled: state.disabled
         }"
         title="显示为"
+        role="button"
+        aria-label="Switch preview mode"
         @click="handleClick"
       >
         <div class="action">
           <slot>
             <svg-icon name="eye"></svg-icon>
           </slot>
         </div>
       </div>
     </template>
-    <div class="options">
+    <div class="options" role="menu">
       <div class="title">显示为</div>
       <div
         class="option"
         v-for="option in state.previewOptions"
         :key="option.id"
+        role="menuitem"
         @click="handleSwitchPreview(option.id)"
       >

Also applies to: 27-38


51-51: Consider making the component whitelist configurable.

The COMPONENT_WHITELIST is hard-coded. Consider making it configurable through props or environment variables for better flexibility.


57-66: Enhance prop definitions with validation and documentation.

Add type validation and JSDoc comments for props to improve maintainability:

+  /**
+   * @typedef {Object} HoverState
+   * @property {string} componentName - Name of the hovered component
+   * @property {HTMLElement} element - Reference to the hovered element
+   * @property {number} width - Width of the hovered element
+   * @property {number} left - Left position of the hovered element
+   * @property {number} top - Top position of the hovered element
+   */
   props: {
     hoverState: {
       type: Object,
+      required: true,
+      validator(value) {
+        return value && typeof value.componentName === 'string' && value.element instanceof HTMLElement
+      },
       default: () => ({})
     },
     inactiveHoverState: {
       type: Object,
+      required: true,
+      validator(value) {
+        return value && typeof value.componentName === 'string' && value.element instanceof HTMLElement
+      },
       default: () => ({})
     }
   },

125-144: Debounce position updates for better performance.

The position updates in the watcher could be debounced to improve performance when hover states change rapidly.

+  import { debounce } from 'lodash-es'

+  const updatePosition = debounce(({ width, left, top }) => {
+    state.left = `${left + width}px`
+    state.top = `${top}px`
+  }, 16) // Debounce for one frame at 60fps

   watch(
     () => [props.hoverState, props.inactiveHoverState],
     ([hoverState, inactiveHoverState]) => {
       state.usedHoverState = [inactiveHoverState, hoverState].find(
         ({ componentName, element }) =>
           COMPONENT_WHITELIST.includes(componentName) &&
           element.ownerDocument.querySelector('div[data-page-active="true"]')?.contains(element) &&
           element.getAttribute('data-page-active') !== 'true'
       )

       if (!state.usedHoverState) {
         return
       }

-      const { width, left, top } = state.usedHoverState
-      state.left = `${left + width}px`
-      state.top = `${top}px`
+      updatePosition(state.usedHoverState)
     },
     { deep: true }
   )

162-225: Enhance style maintainability and accessibility.

Consider the following improvements to the styles:

  1. Add hover and focus styles for keyboard navigation
  2. Add transition animations for smoother UX
  3. Use CSS custom properties for magic numbers
 <style lang="less" scoped>
+:root {
+  --switcher-size: 24px;
+  --switcher-icon-size: 16px;
+  --switcher-transform-x: -80%;
+  --switcher-transform-y: -20%;
+}

 .action-wrapper {
   position: absolute;
   display: flex;
   align-items: center;
   justify-content: center;
-  width: 24px;
-  height: 24px;
+  width: var(--switcher-size);
+  height: var(--switcher-size);
   border-radius: 50%;
   background-color: var(--te-common-bg-default);
   cursor: pointer;
   z-index: 3;
-  transform: translateX(-80%) translateY(-20%);
+  transform: translateX(var(--switcher-transform-x)) translateY(var(--switcher-transform-y));
   top: v-bind('state.top');
   left: v-bind('state.left');
   border: 1px solid var(--te-common-border-hover);
+  transition: all 0.2s ease;

   &.disabled {
     opacity: 0.3;
   }
-  &:not(.disabled):hover {
+  &:not(.disabled):hover,
+  &:not(.disabled):focus-visible {
     border-color: var(--te-common-bg-primary-checked);
     background-color: var(--te-common-bg-primary-checked);
     .action {
       color: var(--te-common-text-dark-inverse);
     }
   }
   .action {
-    width: 16px;
-    height: 16px;
+    width: var(--switcher-icon-size);
+    height: var(--switcher-icon-size);
+    transition: color 0.2s ease;
   }
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 486a763 and 12ca2a5.

📒 Files selected for processing (1)
  • packages/canvas/container/src/components/CanvasViewerSwitcher.vue (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: push-check

@hexqi hexqi merged commit 13dec1c into opentiny:refactor/develop Feb 18, 2025
2 checks passed
@gene9831 gene9831 deleted the feat/routerview-switch-preview branch February 19, 2025 01:32
@coderabbitai coderabbitai bot mentioned this pull request Feb 20, 2025
14 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants