Skip to content

feat(config-provider): [config-provider] 支持合并主题配置 #3187

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

Open
wants to merge 1 commit into
base: dev
Choose a base branch
from

Conversation

hashiqi12138
Copy link
Contributor

@hashiqi12138 hashiqi12138 commented Mar 26, 2025

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)

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:

What is the current behavior?

Issue Number: #3086

What is the new behavior?

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

Summary by CodeRabbit

  • New Features
    • Introduced an interactive configuration interface that supports nested theme customization with dynamic form validation and enhanced design merging for a seamless user experience.
  • Tests
    • Added comprehensive UI tests to ensure reliable event handling, proper form interactions, and responsive button behavior.
  • Chores
    • Updated package metadata and dependency management for better module compatibility and streamlined integration.

Copy link

coderabbitai bot commented Mar 26, 2025

Walkthrough

The changes add new Vue components in the demos for a configuration provider that supports nested theme configurations using Tiny UI components. Both Composition API and classic export styles are introduced with reactive form handling and validation. A new Playwright test verifies custom events and UI behavior. The documentation is updated with a new demo entry, the utilities module now includes a deep merge function, and the Vue config-provider package metadata and design configuration logic are updated to merge parent and child design settings.

Changes

File(s) Change Summary
examples/sites/demos/pc/app/config-provider/merge-composition-api.vue,
examples/sites/demos/pc/app/config-provider/merge.vue
New Vue component(s) added for theme configuration. Both files implement nested tiny-config-provider usage with forms, reactive variables, and validation methods (handleSubmitPromise in the Composition API version and a similar method in the default export version).
examples/sites/demos/pc/app/config-provider/merge.spec.ts New Playwright test file added to verify custom events, modal content, form visibility, and button state management.
examples/sites/demos/pc/app/config-provider/webdoc/config-provider.js New demo entry added with demoId: 'merge' along with localized names and descriptions; references merge.vue in the codeFiles array.
packages/utils/src/index.ts,
packages/utils/src/object/index.ts
Updated the object module to export a new deepMerge function which performs recursive merging of objects, while preserving the existing shallow merge functionality.
packages/vue/src/config-provider/package.json Updated package metadata by adding "type": "module", "license": "MIT", and "sideEffects": false; added dependency on "@opentiny/utils" and reintroduced devDependencies.
packages/vue/src/config-provider/src/index.vue Modified design configuration handling: now injects a parent design using design as designSymbol and merges it with the component’s own design using deepMerge, then provides the merged design via provideDesignConfig.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant C as ConfigProviderComponent
    participant H as handleSubmitPromise
    participant V as Validator
    participant A as Alert Component

    U->>C: Fill in form fields (name, age)
    U->>C: Click Submit
    C->>H: Trigger form submission
    H->>V: Validate form data
    V-->>H: Return validation result
    H->>A: Trigger alert feedback
    A-->>U: Display notification
Loading
sequenceDiagram
    participant C as ConfigProvider Component
    participant I as Injector (hooks.inject)
    participant D as deepMerge Function
    participant P as provideDesignConfig

    C->>I: Inject parent design via designSymbol
    I-->>C: Return parentDesign (or empty object)
    C->>D: Merge parentDesign with child design prop
    D-->>C: Return merged currentDesign
    C->>P: Provide merged design configuration
Loading

Suggested labels

enhancement

Suggested reviewers

  • zzcr

Poem

I'm just a hopping rabbit, coding with delight,
Nesting themes and forms to keep the design bright.
I merge and validate with a twitch of my ear,
Deep merging objects, making intentions clear.
Hoppity-code, I celebrate these changes with cheer!

Warning

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

🔧 ESLint

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

examples/sites/demos/pc/app/config-provider/merge.spec.ts

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "eslint-plugin-vue".

(The package "eslint-plugin-vue" was not found when loaded as a Node module from the directory "".)

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

npm install eslint-plugin-vue@latest --save-dev

The plugin "eslint-plugin-vue" was referenced from the config file in ".eslintrc.js » @antfu/eslint-config » @antfu/eslint-config-vue".

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

examples/sites/demos/pc/app/config-provider/merge-composition-api.vue

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "eslint-plugin-vue".

(The package "eslint-plugin-vue" was not found when loaded as a Node module from the directory "".)

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

npm install eslint-plugin-vue@latest --save-dev

The plugin "eslint-plugin-vue" was referenced from the config file in ".eslintrc.js » @antfu/eslint-config » @antfu/eslint-config-vue".

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

examples/sites/demos/pc/app/config-provider/merge.vue

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "eslint-plugin-vue".

(The package "eslint-plugin-vue" was not found when loaded as a Node module from the directory "".)

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

npm install eslint-plugin-vue@latest --save-dev

The plugin "eslint-plugin-vue" was referenced from the config file in ".eslintrc.js » @antfu/eslint-config » @antfu/eslint-config-vue".

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

  • 4 others
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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 enhancement New feature or request (功能增强) labels Mar 26, 2025
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

@hashiqi12138 hashiqi12138 changed the title feat(config-provider): 支持合并主题配置 feat(config-provider): [config-provider] 支持合并主题配置 Mar 26, 2025
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

🧹 Nitpick comments (11)
examples/sites/demos/pc/app/config-provider/webdoc/config-provider.js (1)

21-33: The English translation could better reflect the nested usage concept.

The Chinese name "嵌套使用" correctly describes the nested usage functionality, but the English name "Merge" doesn't completely convey this concept. Additionally, the English description is reused from the base demo rather than being specific to nested configuration providers.

Consider improving the English translation:

      name: {
        'zh-CN': '嵌套使用',
-       'en-US': 'Merge'
+       'en-US': 'Nested Usage'
      },
      desc: {
        'zh-CN': '支持嵌套使用',
        'en-US':
-         'Icons and logic for different design specifications can be customized through the <code>design</code> attribute configuration.'
+         'Supports nested configuration providers where child providers can inherit and override parent configurations.'
      },
packages/utils/src/object/index.ts (1)

453-461: Consider using isPlainObject instead of isObject for safer recursion.

The current implementation uses isObject which may include arrays and other non-plain objects. For deep merging, it's safer to specifically check for plain objects to avoid issues with arrays or special objects.

-       if (isObject(sourceValue)) {
+       if (isPlainObject(sourceValue)) {
          if (isObject(targetValue)) {
-           // 递归合并对象
+           // 递归合并普通对象
            merge(targetValue, sourceValue)
          } else {
            // 目标属性不是对象,创建新对象并递归合并
            target[key] = {}
            merge(target[key], sourceValue)
          }
packages/vue/src/config-provider/src/index.vue (1)

72-77: Simplify parentDesign null checking expression.

The expression parentDesign?.value || parentDesign || {} is complex and tries to handle different possible types of the injected value. This could be simplified for better readability and maintainability.

    const currentDesign = hooks.computed(() => {
-     const parentValue = parentDesign?.value || parentDesign || {}
+     // Handle both reactive and non-reactive objects
+     const parentValue = (parentDesign && 'value' in parentDesign) ? parentDesign.value : (parentDesign || {})
      return deepMerge(parentValue, design.value)
    })
examples/sites/demos/pc/app/config-provider/merge.vue (3)

197-200: Form data is shared across all forms

All forms are using the same formData object, which means changing a value in one form will update all forms simultaneously. If this is not the intended behavior, consider creating separate form data objects.

Create separate form data objects for each form:

formData: {
  name: '',
  age: ''
},
+formData1: {
+  name: '',
+  age: ''
+},
+formData2: {
+  name: '',
+  age: ''
+}

Then update each form to use its respective data object.


158-196: Unused design configuration

The design object is defined but not used anywhere in the template.

You can remove this unused object or add a comment explaining why it's defined but not used.


204-207: Error suppression without handling

The validation method catches errors but does nothing with them, which might hide important validation failures.

Consider handling validation errors more explicitly:

handleSubmitPromise() {
-  this.$refs.ruleFormRef.validate().catch(() => {})
+  this.$refs.ruleFormRef.validate()
+    .then(() => {
+      // Handle success case
+    })
+    .catch((errors) => {
+      console.log('Validation failed:', errors)
+      // Handle validation failure
+    })
}
examples/sites/demos/pc/app/config-provider/merge.spec.ts (2)

4-4: Error handling might mask test failures

The current error handler suppresses all page errors by expecting them to be null, but this could hide legitimate issues during testing.

Consider a more specific error handling approach:

-page.on('pageerror', (exception) => expect(exception).toBeNull())
+page.on('pageerror', (exception) => {
+  console.error('Page error:', exception.message);
+  // Only fail the test for specific errors you care about
+  // expect(exception.message).not.toContain('Expected error phrase')
+})

24-24: Short timeout for button state verification

The 300ms timeout for verifying that the button is not disabled may be too short for slower environments, potentially causing flaky tests.

Consider increasing the timeout to a more reasonable value:

-await expect(demo.locator('.tiny-button')).not.toBeDisabled({ timeout: 300 })
+await expect(demo.locator('.tiny-button')).not.toBeDisabled({ timeout: 1000 })
examples/sites/demos/pc/app/config-provider/merge-composition-api.vue (3)

133-148: Inconsistent reactive state pattern

Most design configurations are defined as refs (using ref()), but noParentDesign is defined as a plain object. This inconsistency could lead to reactivity issues.

Make noParentDesign reactive for consistency:

-const noParentDesign = {
+const noParentDesign = ref({
  name: 'x-design-n', // 设计规范名称
  version: '1.0.0', // 设计规范版本号
  components: {
    Button: {
      props: {
        round: true
      }
    },
    Form: {
      props: {
        hideRequiredAsterisk: true
      }
    }
  }
-}
+})

Then update the binding in template:

-<tiny-config-provider :design="noParentDesign">
+<tiny-config-provider :design="noParentDesign.value">

150-188: Unused design configuration

The design object is defined but not used anywhere in the template, just like in the Options API version.

You can remove this unused object or add a comment explaining why it's defined but not used.


190-192: Error suppression without handling

The validation method catches errors but does nothing with them, which might hide important validation failures.

Consider handling validation errors more explicitly:

const handleSubmitPromise = () => {
-  ruleFormRef.value.validate().catch(() => {})
+  ruleFormRef.value.validate()
+    .then(() => {
+      // Handle success case
+    })
+    .catch((errors) => {
+      console.log('Validation failed:', errors)
+      // Handle validation failure
+    })
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fc3abeb and 13369d4.

📒 Files selected for processing (8)
  • examples/sites/demos/pc/app/config-provider/merge-composition-api.vue (1 hunks)
  • examples/sites/demos/pc/app/config-provider/merge.spec.ts (1 hunks)
  • examples/sites/demos/pc/app/config-provider/merge.vue (1 hunks)
  • examples/sites/demos/pc/app/config-provider/webdoc/config-provider.js (1 hunks)
  • packages/utils/src/index.ts (1 hunks)
  • packages/utils/src/object/index.ts (1 hunks)
  • packages/vue/src/config-provider/package.json (1 hunks)
  • packages/vue/src/config-provider/src/index.vue (2 hunks)
🔇 Additional comments (3)
packages/vue/src/config-provider/src/index.vue (1)

70-79: LGTM! The nested config provider implementation is well-structured.

The implementation correctly handles merging parent and child design configurations using Vue's provide/inject pattern. The computed property ensures reactivity when either parent or child design changes.

packages/utils/src/index.ts (1)

113-125: LGTM! Export statement correctly includes deepMerge function.

The multi-line export improves readability while properly including the new deepMerge function.

packages/vue/src/config-provider/package.json (1)

14-14:

✅ Verification successful

Added dependency needs to be utilized

You've added @opentiny/utils as a dependency, which is appropriate for the feature, but ensure it's properly imported and used in the config-provider component.


🏁 Script executed:

#!/bin/bash
# Check if the utils dependency is actually used in the config-provider module

echo "Searching for utils imports in config-provider files:"
rg -l "@opentiny/utils" packages/vue/src/config-provider/

Length of output: 267


Verified Dependency Usage: @opentiny/utils is Properly Utilized

The dependency is imported in the config-provider component (as seen in packages/vue/src/config-provider/src/index.vue), which confirms its utilization. No further changes are required regarding this dependency.

Comment on lines +437 to +476

/**
* 深度合并普通对象:递归合并所有普通对象的属性,嵌套对象也会被合并。
* 覆盖非对象值:数组、日期、函数等非普通对象值会被直接覆盖。
* 不修改原对象:所有合并操作都在新对象上进行,原对象保持不变。
* 处理null和undefined源:忽略null和undefined类型的源对象。
*/
export function deepMerge(...sources) {
function merge(target, source) {
if (!isObject(source)) {
return
}
Object.keys(source).forEach((key) => {
const sourceValue = source[key]
const targetValue = target[key]

if (isObject(sourceValue)) {
if (isObject(targetValue)) {
// 递归合并对象
merge(targetValue, sourceValue)
} else {
// 目标属性不是对象,创建新对象并递归合并
target[key] = {}
merge(target[key], sourceValue)
}
} else {
// 直接赋值非对象或数组等类型的值
target[key] = sourceValue
}
})
}

const target = {}
for (const source of sources) {
if (source !== null && source !== undefined) {
merge(target, source)
}
}
return 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

TypeScript type definitions missing in deepMerge function.

The deepMerge function is implemented without proper TypeScript type definitions, unlike other functions in this file. This could lead to type-checking issues and reduced code quality.

Add appropriate TypeScript type definitions:

- export function deepMerge(...sources) {
+ export function deepMerge(...sources: object[]): object {
-   function merge(target, source) {
+   function merge(target: object, source: object): void {
      if (!isObject(source)) {
        return
      }
      Object.keys(source).forEach((key) => {
-       const sourceValue = source[key]
-       const targetValue = target[key]
+       const sourceValue = source[key as keyof typeof source]
+       const targetValue = target[key as keyof typeof target]

        if (isObject(sourceValue)) {
          if (isObject(targetValue)) {
            // 递归合并对象
            merge(targetValue, sourceValue)
          } else {
            // 目标属性不是对象,创建新对象并递归合并
-           target[key] = {}
-           merge(target[key], sourceValue)
+           target[key as keyof typeof target] = {}
+           merge(target[key as keyof typeof target], sourceValue)
          }
        } else {
          // 直接赋值非对象或数组等类型的值
-         target[key] = sourceValue
+         target[key as keyof typeof target] = sourceValue
        }
      })
    }

    const target = {}
    for (const source of sources) {
      if (source !== null && source !== undefined) {
        merge(target, source)
      }
    }
    return target
  }
📝 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
/**
* 深度合并普通对象:递归合并所有普通对象的属性,嵌套对象也会被合并。
* 覆盖非对象值:数组、日期、函数等非普通对象值会被直接覆盖。
* 不修改原对象:所有合并操作都在新对象上进行,原对象保持不变。
* 处理null和undefined源:忽略null和undefined类型的源对象。
*/
export function deepMerge(...sources) {
function merge(target, source) {
if (!isObject(source)) {
return
}
Object.keys(source).forEach((key) => {
const sourceValue = source[key]
const targetValue = target[key]
if (isObject(sourceValue)) {
if (isObject(targetValue)) {
// 递归合并对象
merge(targetValue, sourceValue)
} else {
// 目标属性不是对象,创建新对象并递归合并
target[key] = {}
merge(target[key], sourceValue)
}
} else {
// 直接赋值非对象或数组等类型的值
target[key] = sourceValue
}
})
}
const target = {}
for (const source of sources) {
if (source !== null && source !== undefined) {
merge(target, source)
}
}
return target
}
/**
* 深度合并普通对象:递归合并所有普通对象的属性,嵌套对象也会被合并。
* 覆盖非对象值:数组、日期、函数等非普通对象值会被直接覆盖。
* 不修改原对象:所有合并操作都在新对象上进行,原对象保持不变。
* 处理null和undefined源:忽略null和undefined类型的源对象。
*/
export function deepMerge(...sources: object[]): object {
function merge(target: object, source: object): void {
if (!isObject(source)) {
return
}
Object.keys(source).forEach((key) => {
const sourceValue = source[key as keyof typeof source]
const targetValue = target[key as keyof typeof target]
if (isObject(sourceValue)) {
if (isObject(targetValue)) {
// 递归合并对象
merge(targetValue, sourceValue)
} else {
// 目标属性不是对象,创建新对象并递归合并
target[key as keyof typeof target] = {}
merge(target[key as keyof typeof target], sourceValue)
}
} else {
// 直接赋值非对象或数组等类型的值
target[key as keyof typeof target] = sourceValue
}
})
}
const target = {}
for (const source of sources) {
if (source !== null && source !== undefined) {
merge(target, source)
}
}
return target
}

<tiny-config-provider :design="childDesign1">
<div class="demo-form">
<tiny-alert type="warning" description="全局配置组件的默认行为"></tiny-alert>
<tiny-form ref="ruleFormRef" :model="formData">
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Multiple forms use the same ref identifier

All three forms use the same ref name ruleFormRef, but only one will be accessible in your methods. When you call this.$refs.ruleFormRef.validate(), it will only validate the last form that was rendered.

Fix this by giving each form a unique ref name:

-<tiny-form ref="ruleFormRef" :model="formData">
+<tiny-form ref="ruleFormRef1" :model="formData">

And similar changes for the other forms. Then update the method to target a specific form or validate all forms.

Also applies to: 27-27, 46-46

<tiny-config-provider :design="childDesign1">
<div class="demo-form">
<tiny-alert type="warning" description="全局配置组件的默认行为"></tiny-alert>
<tiny-form ref="ruleFormRef" :model="formData">

This comment was marked as duplicate.

@kagol kagol removed the bug Something isn't working label Mar 31, 2025
@zzcr
Copy link
Member

zzcr commented Apr 30, 2025

@hashiqi12138 代码有冲突哈

@Issues-translate-bot
Copy link

Bot detected the issue body's language is not English, translate it automatically.


@hashiqi12138 There is a conflict in the code

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.

✨ [Feature]: config-provider 主题配置支持多层级嵌套,自动合并
4 participants