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(site): switch theme styles through routing #2574

Merged
merged 1 commit into from
Nov 29, 2024

Conversation

shenjunjian
Copy link
Collaborator

@shenjunjian shenjunjian commented Nov 28, 2024

PR

PR Checklist

Please check if your PR fulfills the following requirements:

  • The commit message follows our Commit Message Guidelines
  • Tests for the changes have been added (for bug fixes / features)
  • Docs have been added / updated (for bug fixes / features)

Other information

通过路由切换old-theme
1、每次修改旧主题,需要执行 pnpm build:theme, 以便重新生成old-theme.css
2、在路径上切换 old-theme即可。

Summary by CodeRabbit

  • New Features

    • Enhanced theme management logic with improved handling of old themes.
    • Introduced new CSS variables for a refreshed color scheme and styling attributes.
  • Bug Fixes

    • Streamlined control flow to prevent unnecessary theme change invocations.
  • Style

    • Updated visual design of the theme, including modifications to button sizes and UI elements.

Copy link

coderabbitai bot commented Nov 28, 2024

Walkthrough

The changes in this pull request focus on enhancing the theme management logic within the useTheme.js file and updating the CSS variables in the old-theme-index.js file. Modifications include streamlined imports, the introduction of a new state variable for theme loading, and updated CSS variable definitions that reflect a new visual design. The control flow for theme changes has been refined to prevent redundant executions, while the overall structure of the theme management has been simplified.

Changes

File Path Change Summary
examples/sites/src/tools/useTheme.js - Streamlined import statements.
- Removed themeMap object.
- Added let loadedTheme = false.
- Updated watchRoute function with new conditional check for old-theme.
- Modified invocation of watchRoute in useTheme function.
packages/theme/src/old-theme-index.js - Updated CSS variable definitions affecting brand, common, success, error, warn, and info categories.
- Introduced or modified additional CSS properties related to UI elements.

Possibly related PRs

Suggested labels

enhancement

Suggested reviewers

  • chenxi-20
  • zzcr

Poem

🐇 In the meadow where colors blend,
A theme anew, on which we depend.
With every hue, a story told,
A rabbit's joy in the colors bold.
Hop along, let the old ways fade,
For in this change, new dreams are made! 🌈


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 enhancement New feature or request and removed chore labels Nov 28, 2024
Copy link

[e2e-test-warn]
The component to be tested is missing.

The title of the Pull request should look like "fix(vue-renderless): [action-menu, alert] fix xxx bug".

Please make sure you've read our contributing guide

Copy link

@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 (5)
examples/sites/src/tools/useTheme.js (3)

6-6: Consider lazy loading theme assets for better performance.

The theme-related images are imported statically, which could impact the initial bundle size. Consider lazy loading these assets when they're needed, especially since theme switching is a dynamic operation.

Example approach:

- import glaciers from '@/assets/images/glaciers.png'
- import glaciersIcon from '@/assets/images/glaciers-icon.png'
+ const loadThemeAssets = async (theme) => {
+   const glaciers = await import('@/assets/images/glaciers.png')
+   const glaciersIcon = await import('@/assets/images/glaciers-icon.png')
+   return { image: glaciers.default, icon: glaciersIcon.default }
+ }

Also applies to: 18-18


Line range hint 90-103: Add error handling and support theme switching.

The current implementation has several potential issues:

  1. The loadedTheme flag prevents reloading the old theme if users switch back to it after changing to another theme
  2. Missing error handling for theme tool initialization
  3. No cleanup of watchers on component unmount

Consider this improved implementation:

- let loadedTheme = false
+ let currentLoadedTheme = null
  const watchRoute = () => {
    if (initWatchRoute) {
      return
    }
    initWatchRoute = true
-   watch(
+   const stopWatch = watch(
      () => router.currentRoute.value.params.theme,
      (val) => {
-       if (!loadedTheme && val === 'old-theme') {
+       if (val === 'old-theme' && currentLoadedTheme !== 'old-theme') {
          const themeTool = new TinyThemeTool()
+         try {
            themeTool.changeTheme(tinyOldTheme)
-           loadedTheme = true
+           currentLoadedTheme = 'old-theme'
+         } catch (error) {
+           console.error('Failed to load old theme:', error)
+         }
+       } else if (val !== 'old-theme') {
+         currentLoadedTheme = val
        }
      }
    )
+   // Cleanup watcher when component unmounts
+   if (import.meta.hot) {
+     import.meta.hot.dispose(() => {
+       stopWatch()
+     })
+   }
  }

Line range hint 109-116: Add input validation and documentation for the theme hook.

The theme switching implementation could benefit from additional safety checks and documentation.

Consider these improvements:

+ /**
+  * Hook for managing theme switching functionality
+  * @returns {Object} Theme management utilities
+  * @property {Function} getThemeData - Returns copy of available theme data
+  * @property {Function} changeTheme - Switches to specified theme
+  * @property {Ref<string>} currentThemeKey - Current theme key
+  * @property {Object} designConfig - Current theme design configuration
+  * @property {string} defaultTheme - Default theme route value
+  */
 export default function useTheme() {
   !initWatchRoute && watchRoute()
+  const validateTheme = (themeKey) => {
+    if (!THEME_ROUTE_MAP[themeKey]) {
+      console.warn(`Invalid theme key: ${themeKey}`)
+      return false
+    }
+    return true
+  }
+
+  const safeChangeTheme = (themeKey) => {
+    if (validateTheme(themeKey)) {
+      changeTheme(themeKey)
+    }
+  }
   return {
     getThemeData,
-    changeTheme,
+    changeTheme: safeChangeTheme,
     currentThemeKey,
     designConfig,
     defaultTheme: THEME_ROUTE_MAP[defaultThemeKey]
   }
 }
packages/theme/src/old-theme-index.js (2)

5-5: Consider documenting typography scale ratios.

The typography system uses fixed pixel values. Consider adding documentation about the scale ratio between different sizes (sm, md, lg, xl, xxl) to maintain consistency when updates are needed.


5-5: Consider extracting Button variables to a separate component theme file.

Currently, Button-specific variables are embedded in the main theme file. As more components are added, this approach might not scale well.

Consider:

  1. Creating a separate file for component-specific theme variables
  2. Implementing a modular theme system where components can define their theme variables
  3. Using a theme composition pattern to merge component themes with the base theme
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between d3fcc60 and 27b04d3.

📒 Files selected for processing (2)
  • examples/sites/src/tools/useTheme.js (4 hunks)
  • packages/theme/src/old-theme-index.js (1 hunks)
🔇 Additional comments (4)
examples/sites/src/tools/useTheme.js (1)

Line range hint 90-116: Add test coverage for theme switching logic.

To ensure the reliability of the theme switching functionality, consider adding tests for:

  • Route parameter changes triggering correct theme changes
  • Theme validation
  • Error handling during theme tool initialization

Let's check for existing test files:

Would you like me to help create a test suite for this functionality?

packages/theme/src/old-theme-index.js (3)

Line range hint 1-4: LGTM! Clear theme identification.

The theme is well-identified with both English and Chinese names, following a consistent naming pattern.


5-5: Verify color contrast ratios for accessibility.

The color system defines multiple shades for each color type (brand, success, error, warn, info). While the color palette is comprehensive, it's important to ensure that text-background combinations meet WCAG accessibility guidelines.


5-5: Verify shadow values for consistency across components.

The shadow system defines multiple levels (0-4) with different directions (up, down, left, right). Ensure these values provide consistent depth perception across different components.

✅ Verification successful

Shadow system is well-defined and consistent

The theme defines a comprehensive and consistent shadow system with 5 levels (0-4) and 4 directional variants (up, down, left, right) for each level. The values show a clear progression:

  • Level 0: Base shadow (0 4px 16px 0)
  • Level 1: Subtle shadow (0/±1px 4px 0)
  • Level 2: Medium shadow (0/±2px 8px 0)
  • Level 3: Pronounced shadow (0/±4px 16px 0)
  • Level 4: Strong shadow (0/±8px 40px 0)

Each level consistently doubles the offset and increases the blur radius, while maintaining appropriate opacity values (0.08 or 0.16) for depth perception.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for shadow usage across components to verify consistency

# Look for shadow variable usage
rg --type js --type vue "shadow-[0-4]-(up|down|left|right)" -A 2

Length of output: 94


Script:

#!/bin/bash
# Search for shadow CSS variable usage with ripgrep
rg --type js "shadow-[0-4]|--tv-shadow-[0-4]" -A 2

# Also search for shadow properties in CSS/SCSS files
rg --type css "shadow-[0-4]|--tv-shadow-[0-4]" -A 2

Length of output: 17331


Script:

#!/bin/bash
# Search for actual usage of shadow variables in component files
rg "var\(--tv-shadow-[0-4]" --type js --type css --type vue -A 1

# Search for box-shadow property usage
rg "box-shadow:" --type js --type css --type vue -A 1

Length of output: 176

@zzcr zzcr merged commit 487a38b into opentiny:dev Nov 29, 2024
6 checks passed
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.

2 participants