Thanks to visit codestin.com
Credit goes to github.com

Skip to content

refactor(theme-doc): add ThemeTools docs #2403

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

Merged
merged 7 commits into from
Oct 26, 2024

Conversation

shenjunjian
Copy link
Collaborator

@shenjunjian shenjunjian commented Oct 26, 2024

image
image
image
image

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Introduced a new section on theme customization, detailing the use of the TinyThemeTool class and the ThemeData interface.
    • Added guidance for customizing themes and handling styles in micro-frontend scenarios.
  • Documentation

    • Enhanced documentation on theme configuration, including support for versions starting from @opentiny/[email protected].
    • Expanded explanations of global and component-level CSS variables.
    • Added warnings regarding the limitations of the OLD theme and suggestions for reverting to earlier versions if needed.
    • Improved overall structure with new custom blocks for tips, information, and warnings.
  • Style

    • Updated CSS styles for lists within the .markdown-body class for improved visual spacing.
    • Adjusted padding for .custom-block elements to enhance visual spacing.

Copy link

coderabbitai bot commented Oct 26, 2024

Walkthrough

The changes primarily involve updates to the documentation related to theme configuration and customization for the TinyVue component library. Key modifications include the introduction of a new ThemeData interface, enhancements to existing sections on CSS variables, and guidance for theme customization using the TinyThemeTool. The documentation now emphasizes compatibility with specific versions and provides detailed instructions for users, particularly in the context of micro frontends. Additionally, CSS styles in the custom-block.less file have been refined to improve list presentation.

Changes

File Path Change Summary
examples/sites/demos/pc/webdoc/theme-en.md Updated section headers, added informational blocks, expanded CSS variables explanation, introduced "Custom theme" section, and added ThemeData interface.
examples/sites/demos/pc/webdoc/theme.md Similar updates as above, including new section on theme customization and ThemeData interface.
examples/sites/src/assets/custom-block.less Modified list styles and margins within the .markdown-body class for improved specificity.
packages/theme/src/theme-tool.d.ts Added optional properties (id, name, cnName) to ThemeData interface; no functional changes.
packages/theme/src/theme-tool.js Renamed variable from OldTheme to tinyOldTheme in import/export statements; no functional changes.

Possibly related PRs

Suggested labels

documentation

Suggested reviewers

  • zzcr

🐰 In the garden where themes bloom bright,
A rabbit hops with joy and delight.
With colors and styles, we now can play,
Custom themes to brighten our day!
From shadows to roots, let’s mount with glee,
In the world of TinyVue, come hop with me! 🌼


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 the refactoring Refactoring (重构) label Oct 26, 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: 3

🧹 Outside diff range and nitpick comments (10)
packages/theme/src/theme-tool.d.ts (1)

2-7: Consider adding English translations to property documentation.

While the new properties are well-structured, consider adding English translations to the JSDoc comments to maintain consistency with international development practices. This would improve accessibility for non-Chinese speaking developers.

-  /** 主题的ID */
+  /** Theme ID (主题的ID) */
   id?: string
-  /** 主题的名称 */
+  /** Theme name (主题的名称) */
   name?: string
-  /** 主题的中文名称 */
+  /** Theme Chinese name (主题的中文名称) */
   cnName?: string
examples/sites/src/assets/custom-block.less (2)

1-4: Consider simplifying selector specificity.

The double .markdown-body class selector (.markdown-body.markdown-body) seems unnecessary and could lead to specificity issues. A single class should be sufficient unless there's a specific reason for the increased specificity.

-.markdown-body.markdown-body ul,
-.markdown-body.markdown-body ol,
-.markdown-body.markdown-body li {
+.markdown-body ul,
+.markdown-body ol,
+.markdown-body li {
   list-style: disc;
}

41-41: Consider optimizing line height for readability.

The current line height of 30px with a 14px font size results in a relatively large spacing ratio (~2.14). Consider reducing it to improve readability of dense documentation.

-    line-height: 30px;
+    line-height: 1.6;

This change:

  • Uses a relative value instead of fixed pixels
  • Provides better readability with a more standard ratio
  • Maintains consistency across different font sizes
examples/sites/demos/pc/webdoc/theme.md (3)

21-38: Consider enhancing the ThemeData interface documentation.

While the interface is well-documented, consider adding:

  • Validation requirements for the id field (allowed characters, length)
  • Format requirements for the css property (valid CSS syntax)
  • Examples of valid data property values

43-69: Consider adding CSS specificity guidelines.

The example demonstrates theme customization well, but consider adding a note about CSS specificity when overriding styles, particularly for the .tiny-button selectors.


114-116: Enhance migration guidance for old themes.

Consider adding:

  • Specific steps for migrating from old themes to new themes
  • Common issues that might arise during migration
  • A troubleshooting guide for theme-related problems
examples/sites/demos/pc/webdoc/theme-en.md (4)

1-14: LGTM! Consider adding examples of global CSS variables.

The introduction and version compatibility notice are clear and well-structured. The links to source files are helpful for users who want to explore the CSS variables.

Consider adding a few common examples of global CSS variables (like colors or spacing) to give users a quick reference without having to navigate to the source files.


80-102: Consider adding error handling examples for micro frontends.

While the micro frontends section provides good guidance, it would be beneficial to include error handling examples for cases where the ShadowRoot might not be immediately available.

Add error handling example:

 const wujieDom = document.querySelector('wujie-app[data-wujie-id]')
+if (!wujieDom) {
+  console.warn('Wujie app container not found')
+  return
+}
 const target = wujieDom.shadowRoot
+if (!target) {
+  console.warn('ShadowRoot not available')
+  return
+}

Line range hint 120-231: Improve organization of historical documentation.

The historical version configuration section needs better organization:

  1. Some content is in Chinese while the document is primarily in English
  2. Code examples use inconsistent formatting
  3. The section could benefit from clearer version compatibility headers

Consider restructuring this section to:

  1. Clearly mark it as legacy documentation
  2. Maintain consistent language (English)
  3. Use consistent code formatting
  4. Add version compatibility notes at the start of each subsection

Line range hint 231-275: Enhance readability of special cases documentation.

While the variable standardization section is comprehensive, the special cases could be presented in a more structured format.

Consider using a table format for the special cases:

| Old Variable Pattern | New Variables | Example |
|---------------------|---------------|---------|
| *-padding | *-padding-vertical, *-padding-horizontal | `--ti-button-padding``--ti-button-padding-vertical`, `--ti-button-padding-horizontal` |
| *-primary-color | *-primary-bg-color, *-primary-text-color, *-primary-border-color | `--ti-pager-primary-color``--ti-pager-primary-bg-color`, etc. |
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 3920df1 and 51bb6b2.

📒 Files selected for processing (4)
  • examples/sites/demos/pc/webdoc/theme-en.md (5 hunks)
  • examples/sites/demos/pc/webdoc/theme.md (1 hunks)
  • examples/sites/src/assets/custom-block.less (2 hunks)
  • packages/theme/src/theme-tool.d.ts (1 hunks)
🔇 Additional comments (5)
packages/theme/src/theme-tool.d.ts (2)

Line range hint 1-35: Overall changes look good!

The additions to the ThemeData interface are well-structured and maintain backward compatibility. The interface provides good flexibility for theme customization while keeping all new fields optional.


8-17: Enhance documentation with English translations and validate example usage.

The documentation provides clear examples, but should include English translations for better accessibility.

   /**
-   * 需要追加的全局css变量的对象
-   * 比如: { 'tv-base-color-brand' : '#1476ff' } 会追加到 :root { --tv-base....... }
+   * Object containing global CSS variables to be appended
+   * (需要追加的全局css变量的对象)
+   * Example: { 'tv-base-color-brand' : '#1476ff' } will be appended to :root { --tv-base....... }
    */
   data?: Record<string, string>
   /**
-   * 需要追加的样式规则, 以覆盖或扩充组件的样式
-   * 比如: .tiny-button { border:none;  }
+   * CSS rules to be appended for overriding or extending component styles
+   * (需要追加的样式规则, 以覆盖或扩充组件的样式)
+   * Example: .tiny-button { border:none; }
    */
   css?: string

Let's verify the CSS variable naming convention usage across the codebase:

✅ Verification successful

Based on the output, I can see that the codebase extensively uses the tv- prefix for CSS variables, confirming that the example in the documentation is following the correct naming convention. Let me verify the specific variables mentioned in the example.

The example shows tv-base-color-brand being used, so let's verify this specific variable and its usage pattern. This will help ensure the example is accurate and consistent with the codebase.


Based on the search results, I can now provide a final response:

Documentation example is accurate and follows codebase conventions

The example { 'tv-base-color-brand' : '#1476ff' } shown in the documentation is valid and consistent with the codebase's CSS variable naming convention. The variable is:

  • Used extensively throughout the codebase
  • Defined in the theme system with the correct tv- prefix
  • Represents a core brand color variable that affects many derived variables

The documentation accurately demonstrates how users should format their CSS variable overrides.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify CSS variable naming convention and usage
# Expected: Should find consistent usage of 'tv-' prefix in CSS variables

# Check for CSS variable declarations with 'tv-' prefix
echo "Checking CSS variable declarations..."
rg --type css --type less "var\(--tv-[a-zA-Z0-9-]+\)"

# Check for direct CSS variable definitions
echo "Checking CSS variable definitions..."
rg --type css --type less ":root\s*{[^}]*--tv-[a-zA-Z0-9-]+"

Length of output: 496754


Script:

#!/bin/bash
# Search for specific CSS variable usage mentioned in the example
rg "tv-base-color-brand" packages/theme/src/

Length of output: 24575

examples/sites/src/assets/custom-block.less (1)

6-10: LGTM! Good spacing for lists.

The margin values provide good readability:

  • Consistent 8px vertical spacing
  • 18px left margin for proper indentation
examples/sites/demos/pc/webdoc/theme.md (1)

3-5: LGTM! Clear version compatibility notice.

Good practice to prominently display version requirements and provide links to archived information.

examples/sites/demos/pc/webdoc/theme-en.md (1)

23-40: LGTM! Well-documented interface definition.

The ThemeData interface is clearly documented with comprehensive descriptions for each property. The examples in the comments effectively illustrate the expected format.

Comment on lines 78 to 100
### 微前端场景

默认情况下,`themeTool.changeTheme` 方法,会将自定义样式挂载到当前`document`下。但是在微前端框架中,通常会有样式隔离的机制,比如无界微前端会封闭一个 `Web Component` 组件挂载子应用。如果自定义这种场景下的主题时,就必须将样式挂载到子应用的`ShadowRoot`上。

```ts
import TinyThemeTool from '@opentiny/vue-theme/theme-tool'

const wujieDom = document.querySelector('wujie-app[data-wujie-id]') //
const target = wujieDom.shadowRoot

const themeTool = new TinyThemeTool()

themeTool.changeTheme(
{
name: 'my-app-custom-styles',
data: {
// ....
},
css: `....`
},
target // ----- 挂载点
)
```
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider expanding micro-frontend documentation.

While the Wujie example is helpful, consider:

  • Adding examples for other popular micro-frontend frameworks (qiankun, single-spa)
  • Documenting potential pitfalls in different micro-frontend setups

Comment on lines 1 to 122
id?: string
/** 主题的名称 */
name?: string
/** 主题的中文名称 */
cnName?: string
/**
* 需要追加的全局css变量的对象
* 比如: { 'tv-base-color-brand' : '#1476ff' } 会追加到 :root { --tv-base....... }
* */
data?: Record<string, string>
/**
* 需要追加的样式规则, 以覆盖或扩充组件的样式
* 比如: .tiny-button { border:none; }
* */
css?: string
}
```

自定义主题的方式如下:

```ts
import TinyThemeTool from '@opentiny/vue-theme/theme-tool'

const themeTool = new TinyThemeTool()

themeTool.changeTheme({
name: 'my-app-custom-styles',
data: {
'tv-base-color-brand': '#1476ff',
'tv-font-size-md': '12px',
'tv-font-size-lg': '16px',
'tv-font-size-xxl': '20px'
},
css: `
.tiny-button {
--tv-Button-border-radius: 6px;

min-width: 80px;
border:none;
padding : 2px 20px;
}
.tiny-button.tiny-button--primary{
background-color: #508de3;
}
`
})
```

<div class="info custom-block">
在一些用户项目中,许多开发者会在编写组件和页面的样式时,通过<code>important</code> 和 <code>:deep()</code> 来覆盖某些组件库的样式。这些样式会散落在各个组件里。在组件库后续版本升级时,可能调整组件结构或类名,造成覆盖失效,不建议这样做。 <br><br>

我们建议用户使用 <code>TinyThemeTool</code> 的方法来覆盖组件样式,这样CSS规则会集中在一起,方便后续维护。用户还可以引入 `CSS文件` 来覆盖样式,但要保证其中的样式优先级高于组件库的优先级。

</div>

### 微前端场景

默认情况下,`themeTool.changeTheme` 方法,会将自定义样式挂载到当前`document`下。但是在微前端框架中,通常会有样式隔离的机制,比如无界微前端会封闭一个 `Web Component` 组件挂载子应用。如果自定义这种场景下的主题时,就必须将样式挂载到子应用的`ShadowRoot`上。

```ts
import TinyThemeTool from '@opentiny/vue-theme/theme-tool'

const wujieDom = document.querySelector('wujie-app[data-wujie-id]') //
const target = wujieDom.shadowRoot

const themeTool = new TinyThemeTool()

themeTool.changeTheme(
{
name: 'my-app-custom-styles',
data: {
// ....
},
css: `....`
},
target // ----- 挂载点
)
```

## OLD主题配置

我们不建议用户继续使用旧主题,但对于历史项目,我们提供一组旧主题的`CSS变量`,需要用户在工程中适配。

```ts
import TinyThemeTool, { OldTheme } from '@opentiny/vue-theme/theme-tool'

const themeTool = new TinyThemeTool(OldTheme)

// themeTool.changeTheme(OldTheme) // 效果同上
```

<div class="warning custom-block">
旧主题不能 100% 还原历史版本的所有细节,如果用户升级后有较大的影响,可以跟我们反馈,也可以回退使用<code> @opentiny/[email protected] </code> 版本,我们将继续维护一段时间。
</div>

## 历史版本的主题配置

<div class="danger custom-block">
本节文档仅支持 <code> @opentiny/[email protected] </code> 版本之前的主题定制
</div>
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Documentation consistency verified with minor discrepancies

The English version exists and largely mirrors the Chinese content, but there are some inconsistencies that should be addressed:

  • The "Historical version" section in English contains additional content about design website specifications that's not present in Chinese version
  • Some warning messages in the OLD theme configuration section remain untranslated
  • The special variables table in English version contains more detailed explanations and examples
  • Some technical terms and code comments are inconsistently translated
🔗 Analysis chain

Verify documentation consistency with English version.

Please ensure that:

  • All sections in this Chinese documentation have corresponding sections in the English version
  • Code examples are identical between versions
  • Warning messages convey the same level of urgency
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for corresponding English documentation file
rg -l "theme-en.md" --type md

Length of output: 29


Script:

#!/bin/bash
# Search for English documentation files in examples/sites/demos/pc/webdoc/
fd -t f -e md . examples/sites/demos/pc/webdoc/

# Search for any file containing "theme" in its name
fd -t f "theme" . examples/sites/demos/pc/webdoc/

# Search for content mentioning theme configuration in English
rg -i "theme configuration|theme customization" --type md

Length of output: 3850


Script:

#!/bin/bash
# Let's compare the content of both theme.md and theme-en.md files
echo "=== Chinese version ==="
cat examples/sites/demos/pc/webdoc/theme.md

echo -e "\n=== English version ==="
cat examples/sites/demos/pc/webdoc/theme-en.md

Length of output: 27137

```

<div class="warning custom-block">
旧主题不能 100% 还原历史版本的所有细节,如果用户升级后有较大的影响,可以跟我们反馈。也可以回退使用<code> @opentiny/[email protected] </code> 版本,我们将继续维护一段时间。
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Translate warning message to English for consistency.

The warning message is in Chinese while the rest of the document is in English. This breaks documentation consistency.

Replace with:

-旧主题不能 100% 还原历史版本的所有细节,如果用户升级后有较大的影响,可以跟我们反馈。也可以回退使用<code> @opentiny/[email protected] </code> 版本,我们将继续维护一段时间。
+The old theme cannot restore 100% of the historical version details. If the upgrade has a significant impact, please provide feedback. Alternatively, you can rollback to <code>@opentiny/[email protected]</code> version, which we will continue to maintain for some time.
📝 Committable suggestion

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

Suggested change
旧主题不能 100% 还原历史版本的所有细节,如果用户升级后有较大的影响,可以跟我们反馈。也可以回退使用<code> @opentiny/vue@3.18.0 </code> 版本,我们将继续维护一段时间。
The old theme cannot restore 100% of the historical version details. If the upgrade has a significant impact, please provide feedback. Alternatively, you can rollback to <code>@opentiny/vue@3.18.0</code> version, which we will continue to maintain for some time.

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 (3)
examples/sites/demos/pc/webdoc/theme.md (3)

20-39: Consider adding validation examples for ThemeData properties.

While the interface is well-documented, it would be helpful to include:

  • Example validation for color values in data property
  • Sample regex patterns for valid CSS in the css property
  • Common pitfalls to avoid

43-69: Consider documenting CSS specificity guidelines.

The example demonstrates theme customization well. Consider adding:

  • Notes about CSS specificity when overriding styles
  • Guidelines for when to use global variables vs component-specific styles
  • Best practices for managing style conflicts

114-116: Consider adding specific upgrade guidance.

While the warning is clear, consider adding:

  • Common issues encountered during upgrades
  • Step-by-step migration guide from old to new theme
  • Compatibility matrix showing which features might break
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 51bb6b2 and 5f0d9ab.

📒 Files selected for processing (1)
  • examples/sites/demos/pc/webdoc/theme.md (1 hunks)
🔇 Additional comments (3)
examples/sites/demos/pc/webdoc/theme.md (3)

3-5: LGTM! Clear version requirement notice.

The tip block effectively communicates version requirements and provides proper navigation to historical configuration.


78-100: LGTM! Clear micro-frontend integration example.

The Wujie integration example is clear and well-documented.


118-122: LGTM! Clear version limitation notice.

The danger block effectively emphasizes version limitations for historical configuration.

```ts
import TinyThemeTool, { OldTheme } from '@opentiny/vue-theme/theme-tool'

const themeTool = new TinyThemeTool(OldTheme)
Copy link
Member

@kagol kagol Oct 26, 2024

Choose a reason for hiding this comment

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

应该使用小驼峰命名,所有内置主题的命名使用统一的前缀 tiny

Suggested change
const themeTool = new TinyThemeTool(OldTheme)
const themeTool = new TinyThemeTool(tinyOldTheme)

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

🧹 Outside diff range and nitpick comments (3)
examples/sites/demos/pc/webdoc/theme.md (3)

3-7: Enhance version compatibility information.

Consider adding:

  • Release date of version 3.19.0
  • Migration guide link for users on older versions
  • Table comparing features between old and new theme systems

22-41: Add comprehensive examples for ThemeData interface.

Consider enhancing the interface documentation with:

  • Complete example showing all properties in use
  • Common use cases for each property
  • Validation rules or constraints for each field

104-118: Add version compatibility matrix for OLD theme configuration.

To help users make informed decisions, consider adding:

  • Version compatibility matrix
  • Known issues with each version
  • Timeline for OLD theme support end-of-life
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 5f0d9ab and 3299a8b.

📒 Files selected for processing (2)
  • examples/sites/demos/pc/webdoc/theme.md (1 hunks)
  • examples/sites/src/assets/custom-block.less (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • examples/sites/src/assets/custom-block.less

Comment on lines +45 to +71
```ts
import TinyThemeTool from '@opentiny/vue-theme/theme-tool'

const themeTool = new TinyThemeTool()

themeTool.changeTheme({
name: 'my-app-custom-styles',
data: {
'tv-base-color-brand': '#1476ff',
'tv-font-size-md': '12px',
'tv-font-size-lg': '16px',
'tv-font-size-xxl': '20px'
},
css: `
.tiny-button {
--tv-Button-border-radius: 6px;

min-width: 80px;
border:none;
padding : 2px 20px;
}
.tiny-button.tiny-button--primary{
background-color: #508de3;
}
`
})
```
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling to theme customization example.

The example should demonstrate:

  • Error handling for invalid CSS values
  • Validation of theme data
  • Cleanup/disposal of theme when no longer needed
const themeTool = new TinyThemeTool()

try {
  await themeTool.changeTheme({
    name: 'my-app-custom-styles',
    data: {
      'tv-base-color-brand': '#1476ff',
      // ... other properties
    },
    css: `...`
  })
} catch (error) {
  console.error('Failed to apply theme:', error)
}

// Cleanup example
onUnmounted(() => {
  themeTool.dispose()
})

Comment on lines +80 to +102
### 微前端场景

默认情况下,`themeTool.changeTheme` 方法,会将自定义样式挂载到当前`document`下。但是在微前端框架中,通常会有样式隔离的机制,比如无界微前端会封装一个 `Web Component` 组件挂载子应用。如果自定义这种场景下的主题时,就必须将样式挂载到子应用的`ShadowRoot`上,用法如下:

```ts
import TinyThemeTool from '@opentiny/vue-theme/theme-tool'

const wujieDom = document.querySelector('wujie-app[data-wujie-id]') //
const target = wujieDom.shadowRoot

const themeTool = new TinyThemeTool()

themeTool.changeTheme(
{
name: 'my-app-custom-styles',
data: {
// ....
},
css: `....`
},
target // ----- 挂载点
)
```
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

⚠️ Potential issue

Based on the implementation details gathered, I can now provide the final response:

Security improvements needed for micro-frontend theme implementation

The current theme implementation has several security considerations that need to be addressed:

  • The textContent assignment in changeTheme method lacks CSS value sanitization, making it vulnerable to CSS injection attacks
  • No cleanup mechanism exists for style elements when unmounting micro-applications
  • The implementation doesn't properly handle style isolation when the target is a shadowRoot

Recommended changes:

  • Add CSS value sanitization before setting textContent
  • Implement a destroy or cleanup method to remove style elements
  • Add shadowRoot-specific style scoping to prevent leaks
🔗 Analysis chain

Add security considerations for micro-frontend theme integration.

The current example should address:

  • Sanitization of CSS input to prevent CSS injection attacks
  • Scope isolation to prevent style leaks between applications
  • Proper cleanup when unmounting micro-applications

Let me gather more specific information about the theme implementation to verify the security concerns.


Let me check one more aspect regarding the cleanup and style handling in the micro-frontend context.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for potential CSS injection vulnerabilities in theme implementation
rg -l "innerHTML|insertRule|cssText" --type ts

Length of output: 530


Script:

#!/bin/bash
# Check theme-tool implementation
fd "theme-tool" --type f --exec rg -l "style|css|inject|append"

# Look for specific theme implementation details
ast-grep --pattern 'class TinyThemeTool {
  $$$
  changeTheme($_) {
    $$$
  }
  $$$
}'

Length of output: 7441


Script:

#!/bin/bash
# Check for cleanup and shadow DOM related handling
rg -A 5 "shadowRoot|cleanup|unmount|destroy" ./packages/theme/src/theme-tool.js ./packages/theme-saas/src/theme-tool.js

# Check CSS sanitization
rg -A 3 "sanitize|escape|validate" ./packages/theme/src/theme-tool.js ./packages/theme-saas/src/theme-tool.js

Length of output: 233

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 (4)
packages/theme/src/theme-tool.js (2)

Line range hint 6-38: Enhance documentation and type safety.

While the implementation is solid, consider the following improvements:

  1. Add JSDoc documentation for the class and methods
  2. Add type annotations for parameters
  3. Add validation for theme data structure

Here's a suggested improvement:

 /**
- * 动态切换文档或影子根节点的样式类
+ * A utility class for dynamically switching styles in documents or shadow roots.
+ * @class
+ * @classdesc Manages theme switching by manipulating CSS custom properties and stylesheets.
  */
 export default class TinyThemeTool {
+  /**
+   * @typedef {Object} Theme
+   * @property {Record<string, string>} [data] - CSS custom properties key-value pairs
+   * @property {string} [css] - Additional CSS rules
+   */
+
+  /**
+   * @param {Theme} [theme] - Initial theme configuration
+   */
   constructor(theme) {
     this.loaded = {} // Cache loaded styles
     if (theme) {
       this.changeTheme(theme)
     }
   }

+  /**
+   * Changes the theme by updating CSS custom properties and styles
+   * @param {Theme} theme - Theme configuration
+   * @param {Document|ShadowRoot} [target=document] - Target document or shadow root
+   * @throws {Error} If theme data is invalid
+   */
   changeTheme(theme, target = document) {
+    if (theme && typeof theme !== 'object') {
+      throw new Error('Theme must be an object')
+    }
+
     let loadedSheet = this.loaded[target]

Line range hint 24-38: Add error handling for theme data processing.

The theme data processing could benefit from additional validation and error handling.

Consider adding these safety checks:

     if (theme && (theme.data || theme.css)) {
       let cssContent = ''
       if (theme.data && typeof theme.data === 'object') {
+        // Validate CSS custom property names
+        const invalidKeys = Object.keys(theme.data).filter(key => !/^[a-zA-Z0-9-_]+$/.test(key))
+        if (invalidKeys.length > 0) {
+          throw new Error(`Invalid CSS custom property names: ${invalidKeys.join(', ')}`)
+        }
+
         cssContent = Object.keys(theme.data)
           .map((key) => `--${key}: ${theme.data[key]}; `)
           .join('')

         cssContent = `:root{${cssContent}}`
       }
       if (theme.css && typeof theme.css === 'string') {
+        // Basic CSS injection safety check
+        if (theme.css.includes('</style>')) {
+          throw new Error('Potential CSS injection detected')
+        }
         cssContent += theme.css
       }

       loadedSheet.replaceSync(cssContent)
     }
examples/sites/demos/pc/webdoc/theme.md (2)

3-14: Consider adding migration guidance for users upgrading from older versions.

While the version requirements and style changes are well documented, consider adding:

  • Step-by-step migration guide
  • Common pitfalls during upgrade
  • Compatibility matrix showing which features work with which versions

22-41: Consider documenting ThemeData validation rules.

The interface properties are well documented, but consider adding:

  • Valid value ranges/formats for each property
  • Required vs optional properties
  • Examples of valid and invalid values
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 3299a8b and 2c4aa9c.

📒 Files selected for processing (2)
  • examples/sites/demos/pc/webdoc/theme.md (1 hunks)
  • packages/theme/src/theme-tool.js (1 hunks)
🔇 Additional comments (1)
packages/theme/src/theme-tool.js (1)

1-1: Verify the impact of renamed export.

The renaming from OldTheme to tinyOldTheme follows the project's naming convention. However, we should verify that all consumers of this export have been updated.

Also applies to: 3-3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
refactoring Refactoring (重构)
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants