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:add theme switching plugin #1070

Open
wants to merge 6 commits into
base: refactor/develop
Choose a base branch
from

Conversation

lichunn
Copy link
Contributor

@lichunn lichunn commented Jan 24, 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
image

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

Summary by CodeRabbit

Summary by CodeRabbit

Release Notes

  • New Features

    • Added a theme toolbar component that allows users to switch between light and dark themes.
    • Enhanced toolbar configuration with theme selection options.
    • Introduced a new CSS variable for consistent theming across the toolbar component.
  • Improvements

    • Introduced theme persistence via localStorage.
    • Updated toolbar layout to include theme selection in right and collapse toolbars.
  • Technical Updates

    • Integrated new @opentiny/tiny-engine-toolbar-theme package.
    • Updated configuration files to support theme functionality.

Copy link
Contributor

coderabbitai bot commented Jan 24, 2025

Walkthrough

This pull request introduces a comprehensive implementation of a theme toolbar functionality across multiple files in the TinyEngine project. The changes include adding a new theme toolbar component, updating configuration files to support theme selection, and modifying various layout and registry files to integrate the theme functionality. The implementation allows users to switch between light and dark themes, with persistent theme selection through local storage.

Changes

File Change Summary
designer-demo/engine.config.js Simplified theme configuration to static 'light' theme
designer-demo/registry.js Added Theme import and integrated theme toolbar
jsconfig.json Added path mapping for theme toolbar module
packages/build/vite-config/src/vite-plugins/devAliasPlugin.js Added alias for theme toolbar module
packages/common/component/ToolbarBase.vue Added position prop and visibility methods
packages/design-core/index.js Added export for Theme component
packages/design-core/package.json Added dependency for theme toolbar
packages/design-core/src/init.js Updated theme initialization with localStorage support
packages/layout/* Updated toolbar configurations to include theme
packages/toolbars/theme/* Created new theme toolbar module with components and logic

Possibly related PRs

Suggested Labels

enhancement, ospp-2024

Suggested Reviewers

  • hexqi

Poem

🐰 A Rabbit's Theme Song 🎨

In lines of code, a theme takes flight,
From dark to light, a coder's delight!
Switching hues with just a click,
Our toolbar's magic does the trick!
Hop along the color's embrace! 🌈

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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.

@github-actions github-actions bot added the refactor-main refactor/develop branch feature label Jan 24, 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: 1

🧹 Nitpick comments (15)
packages/toolbars/theme/meta.js (1)

1-12: Consider adding doc comments for metadata fields.
Adding explanatory doc comments (e.g., describing id, type, title, and each option) can improve maintainability and clarity for future contributors.

packages/toolbars/theme/index.js (1)

17-20: Rename entry for clarity.
Consider renaming the entry property to something like themeEntry or mainEntry to improve readability.

 export default {
   ...metaData,
-  entry
+  themeEntry: entry
 }
packages/toolbars/theme/vite.config.js (1)

13-35: Consider supporting more build formats.
The build config is straightforward. If supporting older environments or alternative module systems is needed, consider adding a UMD or CommonJS output.

 build: {
   lib: {
     entry: path.resolve(__dirname, './index.js'),
     name: 'toolbar-theme',
     fileName: () => 'index.js',
-    formats: ['es']
+    formats: ['es', 'cjs']
   },
   rollupOptions: {
     external: ['vue', /@opentiny\/tiny-engine.*/, /@opentiny\/vue.*/]
   }
 }
packages/toolbars/theme/src/Main.vue (4)

1-9: Consider gracefully handling empty or null options.
When options is empty or not provided, the toolbar-base props might still be passed in. Consider conditionally disabling the toolbar or providing a fallback UI to avoid confusion.


10-21: Extract display text (“主题”) for i18n flexibility.
Hardcoding text in Chinese might limit multilingual support. Consider passing a prop for the radio group title or integrating a localization plugin to keep it consistent with the rest of the application.


36-45: Validate the range of valid positions.
The position prop may accept both 'right' and 'collapse'. If these are the only valid values, consider using an explicit validator or an enum-style approach to enhance reliability and maintainability.


46-55: Reuse the composable instance.
You call useTheme() twice, once for initThemeState() and again for themeChange. For improved clarity, store the result in a variable and destructure both functions from a single call:

  setup() {
-   const state = useTheme().initThemeState()
-   const themeChange = useTheme().themeChange
+   const theme = useTheme()
+   const state = theme.initThemeState()
+   const { themeChange } = theme

    return {
      state,
      themeChange
    }
  }
packages/common/component/ToolbarBase.vue (3)

9-12: Avoid empty spans for spacing.
The empty <span> on line 11 might be purely for spacing. Prefer styling or margin to maintain layout, removing extra DOM nodes.


37-40: Prop definition for position is clear.
It correctly defaults to 'right'. A validator or enumerated options might further clarify acceptable values, but this is otherwise fine.


59-68: Return null instead of false for clarity.
Within Vue, using false to disable rendering is valid, but null is more explicit and makes the code slightly more readable. Consider returning null in getRender() as a minor improvement.

- return false
+ return null
packages/toolbars/theme/src/composable/useTheme.js (1)

47-60: Toggling logic is clear; consider edge cases.
The fallback toggling between light/dark covers two themes. If additional themes are introduced later, ensure this logic is extended accordingly. Otherwise, this approach is straightforward.

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

91-91: Placement of the Theme component in toolbars array.

The Theme component is placed first in the array; verify this ordering is intentional. If it should appear next to items like Lang or ViewSetting, consider reordering for a consistent user flow.

designer-demo/registry.js (2)

68-68: Add 'engine.toolbars.theme' to the right array.

Placing 'engine.toolbars.theme' in the right array is consistent with the new theming feature. Ensure the icon or label is intuitive for easy user discovery.


76-77: Avoid potential confusion when repeating the same toolbar item.

You've inserted 'engine.toolbars.theme' in both the right and collapse arrays. If this is intentional to make the Theme toolbar prominently accessible, that's fine, but be aware of possible UI duplication.

packages/design-core/src/init.js (1)

58-58: Leverage localStorage fallback for theme selection.

Using localStorage.getItem('tiny-engine-theme') ensures user preferences persist. Consider validating the stored value to avoid unexpected states if localStorage data is corrupted or invalid.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5b9d61a and 3ff1472.

⛔ Files ignored due to path filters (6)
  • packages/design-core/assets/cn.svg is excluded by !**/*.svg
  • packages/design-core/assets/dark.svg is excluded by !**/*.svg
  • packages/design-core/assets/en.svg is excluded by !**/*.svg
  • packages/design-core/assets/light.svg is excluded by !**/*.svg
  • packages/design-core/assets/nested-page.svg is excluded by !**/*.svg
  • packages/design-core/assets/single-page.svg is excluded by !**/*.svg
📒 Files selected for processing (22)
  • designer-demo/engine.config.js (1 hunks)
  • designer-demo/registry.js (3 hunks)
  • jsconfig.json (2 hunks)
  • packages/build/vite-config/src/vite-plugins/devAliasPlugin.js (1 hunks)
  • packages/common/component/ToolbarBase.vue (3 hunks)
  • packages/design-core/index.js (1 hunks)
  • packages/design-core/package.json (1 hunks)
  • packages/design-core/src/init.js (2 hunks)
  • packages/engine-cli/src/commands/generateConfig.js (1 hunks)
  • packages/engine-cli/template/designer/engine.config.js (1 hunks)
  • packages/engine-cli/template/designer/registry.js (3 hunks)
  • packages/layout/index.js (1 hunks)
  • packages/layout/src/DesignToolbars.vue (1 hunks)
  • packages/layout/src/ToolbarCollapse.vue (2 hunks)
  • packages/register/src/constants.js (1 hunks)
  • packages/toolbars/theme/index.js (1 hunks)
  • packages/toolbars/theme/meta.js (1 hunks)
  • packages/toolbars/theme/package.json (1 hunks)
  • packages/toolbars/theme/src/Main.vue (1 hunks)
  • packages/toolbars/theme/src/composable/useTheme.js (1 hunks)
  • packages/toolbars/theme/src/styles/vars.less (1 hunks)
  • packages/toolbars/theme/vite.config.js (1 hunks)
✅ Files skipped from review due to trivial changes (4)
  • designer-demo/engine.config.js
  • packages/toolbars/theme/src/styles/vars.less
  • packages/engine-cli/template/designer/engine.config.js
  • packages/toolbars/theme/package.json
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: push-check
🔇 Additional comments (29)
packages/engine-cli/src/commands/generateConfig.js (1)

11-11: Verify if '${theme}' is intended as a literal placeholder or dynamic interpolation.

Currently, '${theme}' will be rendered as a plain string in this generated code. If your goal is to inject the actual theme value, consider using JavaScript template interpolation (e.g., theme: \`${theme}\` ) or confirm that a build-time replacement step is substituting '${theme}' with the desired value. Otherwise, '${theme}' may remain as a literal placeholder and potentially cause confusion or broken theme logic in the resulting configuration file.

packages/toolbars/theme/meta.js (1)

1-12: Overall implementation looks solid.
No issues with object structure or property naming. This aligns well with the existing conventions in the project.

packages/toolbars/theme/index.js (1)

1-11: License header check.
The license and copyright statements appear correctly formatted and consistent with the project.

packages/layout/index.js (2)

19-19: Theme integration in right toolbar.
Adding engine.toolbars.theme helps ensure the user can quickly switch themes. Looks good.


28-28: Theme integration in collapse toolbar.
Providing the theme switch in the collapsed section is also helpful. No conflicts detected.

packages/toolbars/theme/vite.config.js (1)

1-11: License header confirmed.
Everything is consistent with the project’s license disclaimers.

packages/toolbars/theme/src/Main.vue (2)

26-35: Script and component imports look good!
The chosen imports and components appear consistent with the overall codebase style.


58-65: Scoped styles are well-scoped and consistent with theme.
No issues found here; using a CSS variable encourages theme consistency.

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

55-57: Helper methods cleanly separate logic.
The isShowMulti and isHideMulti methods provide clarity and readability for controlling collapsible states.


74-76: Final exports are neatly organized.
Exposing getRender, isShowMulti, and isHideMulti from the setup function is straightforward and helps reactivity.

packages/register/src/constants.js (1)

29-29: New Theme constant aligns well with existing naming.
This addition fits neatly among the other engine toolbar constants.

packages/toolbars/theme/src/composable/useTheme.js (3)

17-22: THEME_DATA structure is concise and clear.
Defining both name and label strings here keeps them well-organized for easy reference.


39-45: Handle invalid or unexpected theme values.
Currently, initThemeState defaults to 'light' if no stored theme is found. You may want to validate the stored or merged theme in case of third-party modifications or storage errors.


62-69: Neat export of composable functionality.
The composable returns all relevant objects and methods for theme management, keeping the code modular and maintainable.

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

24-24: Add import statement for Theme.

Nice addition of the Theme import from @opentiny/tiny-engine. This aligns well with the introduction of new theming capabilities.


68-68: Ensure toolbar references match existing aliases.

You added 'engine.toolbars.theme' to the right toolbar array. Make sure 'engine.toolbars.theme' is properly registered in the global config so it doesn't cause runtime errors.


76-77: Confirm duplication in collapsed toolbar.

The 'engine.toolbars.theme' entry also appears in the collapsed toolbar. Confirm whether you intend to display the same toolbar item in two places or if this is unintended duplication.

designer-demo/registry.js (2)

24-24: Add import statement for Theme.

Importing Theme from @opentiny/tiny-engine improves modularity and allows seamless integration of the theming functionality across the demo.


91-91: Include Theme in the main toolbars array.

Co-locating Theme with other entries ensures feature parity across various deployment scenarios. No major concerns here; just verify consistent ordering with the rest of the toolbars.

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

14-14: Export Theme for modular usage.

Exporting Theme from @opentiny/tiny-engine-toolbar-theme keeps the design-core consistent and extensible. Good job on ensuring this is easily importable elsewhere.

packages/design-core/src/init.js (1)

75-77: Set theme-based editor mode.

Fetching theme from localStorage in lines 75–77 is a smooth way to unify UI and editor theme. However, confirm that user-defined theme strings (like custom theme names) won't break the dark check. Consider a more robust approach if you plan to add advanced theming options in the future.

packages/layout/src/DesignToolbars.vue (2)

23-27: Ensure position prop is documented and handled.
The addition of position="right" here mirrors the usage in other components. Confirm that the component receiving this prop properly handles or documents position, so behavior is consistent across toolbars.


31-35: Maintain consistency for props in array-of-components scenario.
Applying position="right" to each nested component is a good approach, so that items are consistently displayed in the right toolbar. This appears correct and in line with the rest of the changes.

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

50-50: Validate new theme alias.
The alias @opentiny/tiny-engine-toolbar-theme is added correctly. Ensure that references elsewhere in the codebase match this alias to avoid resolution issues.

✅ Verification successful

Theme alias configuration is consistent
The alias @opentiny/tiny-engine-toolbar-theme is properly configured in all relevant files and used consistently across the codebase. The package is correctly referenced in dependencies and imports.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verifies usage of the new alias in codebase
rg '@opentiny/tiny-engine-toolbar-theme'

Length of output: 670

packages/layout/src/ToolbarCollapse.vue (2)

2-2: Confirm popover width change.
Changing the popover width from 140 to 248 might impact overall toolbar layout. Ensure there is enough space and that the new width does not cause overflow in smaller viewports.


19-23: Consistent usage of comp in array loop.
Here, comp is used correctly for items in an array. Make sure it remains consistent if the references are renamed in the block above.

jsconfig.json (2)

34-34: Added theme toolbar path alias.
The new path mapping for @opentiny/tiny-engine-toolbar-theme ensures easy imports of the theme entry point. It appears correctly aligned with the directory structure.


63-63: Wildcard alias for theme toolbar.
This wildcard alias supports imports of submodules within @opentiny/tiny-engine-toolbar-theme/*. It aligns well with the newly introduced theming architecture.

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

75-75: LGTM! The new theme toolbar dependency is properly added.

The dependency is correctly positioned among other toolbar-related dependencies and uses the consistent workspace:* version pattern.

Let's verify the integration with existing theme packages:

✅ Verification successful

Theme toolbar integration verified successfully

The new theme toolbar package is properly integrated with the existing theme system and follows the established patterns:

  • Correctly registered in toolbar configurations alongside other theme components
  • Properly implemented with theme switching UI and styling
  • Well integrated with the build system and package structure
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for potential conflicts or integration issues between the new theme toolbar and existing theme packages

# Search for theme-related imports and usage
echo "Checking theme-related imports and usage patterns:"
rg -A 3 "import.*theme|from.*theme" --type vue --type js

# Check for potential conflicts in theme configuration
echo "Checking theme configuration patterns:"
rg -A 3 "theme.*config|configureTheme|themeConfig" --type vue --type js

# Look for existing toolbar registrations to ensure proper integration
echo "Checking toolbar registration patterns:"
rg -A 3 "registerToolbar|toolbar.*config" --type vue --type js

Length of output: 568


Script:

#!/bin/bash
# Search for theme-related imports and configurations
echo "=== Theme-related patterns ==="
rg "from ['\"]\@opentiny/tiny-engine-theme" -A 2

echo -e "\n=== Theme configuration patterns ==="
rg "themeConfig|configureTheme" -A 2

echo -e "\n=== Toolbar registration and theme integration ==="
rg "registerToolbar|toolbarConfig|themeToolbar" -A 2

# Use ast-grep to find theme-related function calls and configurations
echo -e "\n=== Theme-related function calls ==="
ast-grep --pattern 'registerTheme($_)'

echo -e "\n=== Theme configuration objects ==="
ast-grep --pattern 'themeConfig = {
  $$$
}'

Length of output: 800


Script:

#!/bin/bash
# Check for imports and usage of the new theme toolbar package
echo "=== New theme toolbar package usage ==="
rg "@opentiny/tiny-engine-toolbar-theme" -A 2

# Search for theme-related imports with fixed regex
echo -e "\n=== Theme-related imports ==="
rg "from.*@opentiny/tiny-engine-theme" -A 2

# Look for theme and toolbar related patterns
echo -e "\n=== Theme and toolbar patterns ==="
rg "theme.*toolbar|toolbar.*theme" -A 2

# Check package.json files for related dependencies
echo -e "\n=== Related dependencies in package.json files ==="
fd "package.json" --exec grep -A 3 -B 3 "tiny-engine.*theme"

Length of output: 9389

packages/layout/src/ToolbarCollapse.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

🧹 Nitpick comments (3)
packages/toolbars/theme/src/composable/useTheme.js (2)

39-47: Local storage usage and fallback.
Initializing theme state from localStorage with fallback to engine.config.theme is robust. The function returns the reactive state as expected.

Consider verifying that localStorage is available in all environments where this code may run (for instance, server-side rendering or embedded frames).


49-63: Smart toggling and integration with editor theming.
The logic to determine whether to toggle or directly set the theme is intuitive. The default usage of 'vs-dark' vs 'vs' for the Monaco editor is also consistent.

If more themes are introduced in the future, consider expanding the logic beyond a simple 'includes("dark")' check for better scalability.

packages/design-core/src/init.js (1)

78-81: Potential duplication in retrieving app ID and theme.
You’ve duplicated the logic to retrieve theme from localStorage in both beforeAppCreate and appCreated.

Extracting a helper function or using the newly defined composable in future refactors could reduce repetition and help maintain consistency.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9186649 and 55d973f.

📒 Files selected for processing (2)
  • packages/design-core/src/init.js (4 hunks)
  • packages/toolbars/theme/src/composable/useTheme.js (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: push-check
🔇 Additional comments (7)
packages/toolbars/theme/src/composable/useTheme.js (5)

1-11: Header looks good.
These license and copyright notices appear consistent and comprehensive.


13-16: Imports correctly reference necessary APIs.
All imported functions (reactive, getMetaApi, getMergeMeta, META_SERVICE, setGlobalMonacoEditorTheme) are used. Everything looks fine.


17-22: Naming alignment for theme constants.
The theme constants (LIGHT, DARK) and their matching labels are well-structured. No immediate issues.


24-37: Reactive state approach is clear and extensible.
Defining themeState with Vue's reactive system is straightforward, and storing label-value pairs helps streamline usage.


65-72: Exporting composable with a default function.
Providing a custom composable return structure is a standard Vue 3 approach.

packages/design-core/src/init.js (2)

24-25: Imports from meta-register are used appropriately.
These references to getMetaApi, META_SERVICE look correct for retrieving base info. No issues found.


42-42: Reusing localStorage with dynamic keys.
You’re dynamically building the tiny-engine-theme-${appId} key, which is good for multiple apps in one environment. This ensures no collisions in localStorage.

Also applies to: 61-61

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.

2 participants