Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: fix materials panel #909

Merged

Conversation

yy-wow
Copy link
Collaborator

@yy-wow yy-wow commented Nov 26, 2024

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?

  1. 物料面板固定面板按钮点击无效
  2. 固定面板下次进入需要再次固定,没有持久化保存

Issue Number: N/A

What is the new behavior?

  1. 物料面板固定面板按钮点击固定或解除固定正常
  2. 持久化保存固定状态,提升体验

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

Summary by CodeRabbit

  • New Features
    • Enhanced header interactivity by adding an event emission for the fix-panel action, allowing better communication with parent components.
    • Introduced a computed property, panelFixed, to streamline the logic for determining the fixed state of panels in the header and tree components.
    • Implemented local storage functionality to remember fixed panels across sessions, ensuring user preferences persist after page refreshes.
  • Improvements
    • Cleaned up the code by removing unused sections and simplifying the logic for panel state representation.
    • Added error handling for local storage operations to enhance user experience.

Copy link
Contributor

coderabbitai bot commented Nov 26, 2024

Walkthrough

The changes in this pull request enhance the Main.vue components across multiple packages by adding event emissions and refining the logic for panel states. Specifically, the fix-panel event is emitted from the header component, allowing communication with the parent component. Additionally, the logic for determining the fixed state of panels is streamlined through the introduction of computed properties, improving readability and maintainability while keeping the overall structure of the components intact.

Changes

File Path Change Summary
packages/plugins/materials/src/meta/layout/src/Main.vue Added fix-panel event emission in the header component's emits option.
packages/plugins/materials/src/components/header/Main.vue Updated setup method to accept props, added panelFixed computed property, and modified template logic for button attributes.
packages/plugins/tree/src/Main.vue Removed commented code, updated setup method to define PLUGIN_NAME after destructuring props, added panelFixed computed property, and streamlined logic for UI elements based on panel state.
packages/layout/src/DesignPlugins.vue Initialized fixedPanels from localStorage and updated fixPanel method to save state in localStorage.
packages/utils/src/constants/index.js Added STORAGE_KEY_FIXED_PANELS constant for local storage operations.

Possibly related PRs

Suggested labels

enhancement

Suggested reviewers

  • hexqi

🐰 In the meadow where bunnies play,
A new event hops in today!
When panels fix, the header sings,
Communicating joyful things.
With every click, a tale unfolds,
In our code, new magic molds! 🌼


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 bug Something isn't working refactor-main refactor/develop branch feature labels Nov 26, 2024
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (1)
packages/plugins/materials/src/meta/layout/src/Main.vue (1)

4-8: LGTM! Consider moving event handler to methods section.

The implementation correctly adds the fix-panel functionality. However, for better maintainability, consider moving the event handler to the methods section.

<template>
  <component
    :is="headerComponent"
    :fixedPanels="fixedPanels"
-   @fix-panel="(id) => $emit('fix-panel', id)"
+   @fix-panel="handleFixPanel"
  ></component>
</template>

<script>
export default {
  // ... existing code ...
  methods: {
    handleFixPanel(id) {
      this.$emit('fix-panel', id)
    }
  }
}
</script>
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between bc501cf and f1f1a7e.

📒 Files selected for processing (1)
  • packages/plugins/materials/src/meta/layout/src/Main.vue (1 hunks)
🔇 Additional comments (1)
packages/plugins/materials/src/meta/layout/src/Main.vue (1)

4-8: Verify headerComponent implementation.

Let's verify that the headerComponent properly implements the fix-panel event.

✅ Verification successful

Header component implementation is correct

The header component properly implements the fix-panel event. The component:

  • Correctly emits the 'fix-panel' event with the Materials plugin name as payload
  • Accepts the required fixedPanels prop
  • Uses the event to toggle panel fixing functionality
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for headerComponent implementation and its fix-panel event
ast-grep --pattern 'export default {
  $$$
  emits: [$$$"fix-panel"$$$]
  $$$
}'

# Search for any fix-panel event emissions
rg "\\$emit\\(['\"]fix-panel['\"]" -g '!Main.vue'

Length of output: 205


Script:

#!/bin/bash
# Search for headerComponent definition/import
rg "headerComponent" -A 5 -B 5

# Search for fix-panel event handling with proper regex escaping
rg "\$emit\('fix-panel'" -g '!Main.vue'
rg "\$emit\(\"fix-panel\"" -g '!Main.vue'

# Find all Vue components that might be used as headerComponent
fd -e vue --exec grep -l "export default" {}

Length of output: 17026


Script:

#!/bin/bash
# Let's check the header component implementation
cat packages/plugins/materials/src/components/header/Main.vue

# Also check for any fix-panel event handling in the header component
rg -g "packages/plugins/materials/src/components/header/Main.vue" "fix-panel"

Length of output: 794

chilingling
chilingling previously approved these changes Nov 26, 2024
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (3)
packages/plugins/materials/src/components/header/Main.vue (2)

4-6: Consider internationalizing button tooltips

The button tooltips are currently hardcoded in Chinese. Consider using i18n for better internationalization support.

-    :tips="panelFixed ? '解除固定面板' : '固定面板'"
+    :tips="panelFixed ? t('unfixPanel') : t('fixPanel')"

Line range hint 20-23: Consider adding default value and type validation for fixedPanels prop

The prop definition could be more robust with a default value and validation.

    fixedPanels: {
-      type: Array
+      type: Array,
+      default: () => [],
+      validator: (value) => Array.isArray(value)
    }
packages/plugins/tree/src/Main.vue (1)

78-83: LGTM! Consider adding TypeScript type safety.

The implementation correctly handles panel state management and event emissions. The computed property is well-implemented with null-safe checks.

Consider adding TypeScript type safety to improve maintainability:

- props: {
-   fixedPanels: {
-     type: Array
-   }
- },
+ props: {
+   fixedPanels: {
+     type: Array as PropType<string[]>,
+     default: () => []
+   }
+ },
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f1f1a7e and a93cd1b.

⛔ Files ignored due to path filters (1)
  • packages/design-core/assets/fixed-solid.svg is excluded by !**/*.svg
📒 Files selected for processing (2)
  • packages/plugins/materials/src/components/header/Main.vue (2 hunks)
  • packages/plugins/tree/src/Main.vue (3 hunks)
🔇 Additional comments (2)
packages/plugins/materials/src/components/header/Main.vue (1)

25-32: LGTM! Clean implementation of panel state logic

The implementation is well-structured and follows Vue 3 composition API best practices:

  • Proper use of computed properties for reactive state
  • Clean separation of concerns
  • Correct handling of optional chaining for fixedPanels
packages/plugins/tree/src/Main.vue (1)

6-7: LGTM! Verify button state changes.

The button implementation correctly uses the computed panelFixed property to toggle between fixed/unfixed states, with appropriate visual feedback through icons and tooltips.

Let's verify the button state changes are working as expected:

✅ Verification successful

Button state changes are properly implemented and consistent

The implementation is verified to be working correctly:

  • The panelFixed computed property correctly derives its state from fixedPanels prop using the proper plugin identifier
  • The button click correctly emits the fixPanel event with the correct plugin name
  • The pattern is consistent with other plugins (e.g., Tutorial plugin) that use the same panel fixing mechanism
  • The visual feedback (icon and tooltip) properly reflects the panel's fixed state
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for consistent panel state handling across components

# Look for similar panel state implementations
rg -A 3 'panelFixed.*\?' --type vue

# Check for proper event handling
rg -A 3 '@fix-panel|fixPanel' --type vue

Length of output: 136


Script:

#!/bin/bash
# Description: Check for consistent panel state handling across components using different file extensions

# Look for similar panel state implementations
rg -A 3 'panelFixed.*\?' -t js -t jsx -t ts -t tsx -t html

# Check for proper event handling
rg -A 3 '@fix-panel|fixPanel' -t js -t jsx -t ts -t tsx -t html

# Find all Vue-like files to determine correct extension
fd -e vue

Length of output: 16957


Script:

#!/bin/bash
# Now that we know the Vue files exist, let's search with the correct pattern

# Search for panel fixed state implementations
rg -U 'panelFixed.*\?' packages/plugins/tree/src/Main.vue

# Search for fix panel event handling
rg -U '@fix-panel|fixPanel|emits.*fixPanel' packages/plugins/tree/src/Main.vue

# Look for similar implementations in other plugin panels
rg -U 'panelFixed|fixPanel' packages/plugins/*/src/Main.vue

Length of output: 1407

packages/plugins/materials/src/components/header/Main.vue Outdated Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (1)
packages/layout/src/DesignPlugins.vue (1)

157-162: Consider extracting panel state persistence logic into a dedicated composable

The current implementation mixes panel state persistence directly in the component. This could be improved by:

  1. Creating a dedicated composable for panel state management
  2. Implementing proper state persistence patterns
  3. Adding migration capabilities for future state structure changes

Consider creating a new composable like this:

// useFixedPanelsState.ts
import { ref, watch } from 'vue'

const STORAGE_KEY = 'tiny-engine-fixed-panels'

export function useFixedPanelsState() {
  const fixedPanels = ref<string[]>([])

  const loadState = () => {
    try {
      const stored = localStorage.getItem(STORAGE_KEY)
      const parsed = stored ? JSON.parse(stored) : []
      fixedPanels.value = Array.isArray(parsed) ? parsed : []
    } catch (error) {
      console.warn('Failed to restore fixed panels state:', error)
      fixedPanels.value = []
    }
  }

  const saveState = () => {
    try {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(fixedPanels.value))
    } catch (error) {
      console.warn('Failed to persist fixed panels state:', error)
    }
  }

  // Auto-save on changes
  watch(fixedPanels, saveState, { deep: true })

  // Load initial state
  loadState()

  return {
    fixedPanels,
    togglePanel: (pluginName: string) => {
      const index = fixedPanels.value.indexOf(pluginName)
      if (index === -1) {
        fixedPanels.value.push(pluginName)
      } else {
        fixedPanels.value.splice(index, 1)
      }
    }
  }
}

This would simplify the component code and improve maintainability.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a93cd1b and 1026852.

📒 Files selected for processing (1)
  • packages/layout/src/DesignPlugins.vue (1 hunks)

packages/layout/src/DesignPlugins.vue Outdated Show resolved Hide resolved
packages/layout/src/DesignPlugins.vue Outdated Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (1)
packages/layout/src/DesignPlugins.vue (1)

160-165: Consider handling concurrent localStorage updates

While the current implementation works well for single-instance scenarios, consider implementing a pub/sub mechanism or using a state management solution (like Vuex/Pinia) to handle potential race conditions when multiple instances of the application try to update the fixed panels state simultaneously.

Also applies to: 168-180

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 14f17b7 and 60dd530.

📒 Files selected for processing (1)
  • packages/layout/src/DesignPlugins.vue (3 hunks)
🔇 Additional comments (6)
packages/layout/src/DesignPlugins.vue (6)

77-77: LGTM: Import statement is correctly added

The addition of useModal import is appropriate for the new error handling functionality.


80-81: LGTM: Well-defined storage key constant

The constant is appropriately namespaced and follows naming conventions.


103-103: LGTM: Proper hook usage

Correctly destructured message from useModal hook following Vue Composition API practices.


182-182: LGTM: Proper initialization timing

The restoreFixedPanels method is correctly called during component setup.


160-165: ⚠️ Potential issue

Fix template literal syntax in error message

The error message has incorrect quote usage that could lead to malformed output.

Apply this fix:

-        message({ message: `'Failed to persist fixed panels state:'${error}`, status: 'error' })
+        message({ message: `Failed to persist fixed panels state: ${error}`, status: 'error' })

Note: The implementation correctly follows the recommended approach for localStorage operations with proper serialization and error handling.


168-180: ⚠️ Potential issue

Fix template literal syntax in error message

The error message has incorrect quote usage that could lead to malformed output.

Apply this fix:

-        message({ message: `'Failed to restore fixed panels state:'${error}`, status: 'error' })
+        message({ message: `Failed to restore fixed panels state: ${error}`, status: 'error' })

Note: The implementation correctly follows the recommended approach for localStorage initialization with proper parsing, type validation, and error handling.

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 (4)
packages/utils/src/constants/index.js (1)

96-97: Add JSDoc documentation for the new constant

Consider adding documentation to explain the purpose and usage of this constant.

+/**
+ * Storage key for persisting fixed panel states
+ * Used in conjunction with localStorage to maintain panel configurations across sessions
+ */
 export const STORAGE_KEY_FIXED_PANELS = `tiny-engine-fixed-panels-${CHANNEL_UID}`
packages/layout/src/DesignPlugins.vue (3)

161-166: Fix error message string formatting

The error message contains unnecessary quotes that will appear in the UI.

-        message({ message: `'存储固定面板数据失败:'${error}`, status: 'error' })
+        message({ message: `存储固定面板数据失败: ${error}`, status: 'error' })

169-181: Fix error message string formatting

The error message contains unnecessary quotes that will appear in the UI.

-        message({ message: `'读取固定面板数据失败:'${error}`, status: 'error' })
+        message({ message: `读取固定面板数据失败: ${error}`, status: 'error' })

183-183: Move localStorage initialization to onMounted hook

For better alignment with Vue's lifecycle hooks and to ensure proper handling of browser APIs, consider moving the initialization to onMounted:

+    import { reactive, ref, watch, onMounted } from 'vue'
     // ... other code ...
-    restoreFixedPanels()
+    onMounted(() => {
+      restoreFixedPanels()
+    })
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 60dd530 and fa089dc.

⛔ Files ignored due to path filters (1)
  • packages/design-core/assets/fixed-solid.svg is excluded by !**/*.svg
📒 Files selected for processing (2)
  • packages/layout/src/DesignPlugins.vue (3 hunks)
  • packages/utils/src/constants/index.js (1 hunks)
🔇 Additional comments (2)
packages/utils/src/constants/index.js (1)

96-97: LGTM! Verify usage in DesignPlugins.vue

The constant follows the established pattern of using CHANNEL_UID for unique storage keys.

Let's verify its usage in DesignPlugins.vue:

✅ Verification successful

LGTM! The constant is properly used in DesignPlugins.vue

The constant STORAGE_KEY_FIXED_PANELS is correctly imported and used in DesignPlugins.vue for:

  • Storing fixed panel states via localStorage.setItem
  • Retrieving stored panel states via localStorage.getItem
  • Proper error handling is implemented for storage operations
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of STORAGE_KEY_FIXED_PANELS constant
# Expected: Should find usage in DesignPlugins.vue for localStorage operations

# Search for the constant usage
rg "STORAGE_KEY_FIXED_PANELS" -A 3

# Search for related localStorage operations in DesignPlugins.vue
fd -e vue -x rg "localStorage" -l {} \; | rg "DesignPlugins"

Length of output: 1372

packages/layout/src/DesignPlugins.vue (1)

77-81: LGTM: Import changes are well-structured

The new imports are properly organized and follow Vue best practices.

@hexqi hexqi merged commit 49f68c3 into opentiny:refactor/develop Nov 28, 2024
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working refactor-main refactor/develop branch feature
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants