Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

fix: buildinCompStyle compact nested scenario #1090

Draft
wants to merge 1 commit into
base: develop
Choose a base branch
from

Conversation

chilingling
Copy link
Member

@chilingling chilingling commented Feb 5, 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

修复内置 Canvas行列容器组件在嵌套场景下,样式会发生透传的 bug

What is the current behavior?

Issue Number: N/A

What is the new behavior?

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

Summary by CodeRabbit

  • New Features

    • Enabled enhanced layout customization with dynamic styling options across components.
    • Introduced a configurable option for adjusting row spacing in container elements.
  • Refactor

    • Streamlined styling by shifting from static to inline dynamic style bindings, improving responsiveness and flexibility.

修复内置 Canvas行列容器组件在嵌套场景下,样式会发生透传的 bug
Copy link
Contributor

coderabbitai bot commented Feb 5, 2025

Walkthrough

The changes update several Vue components to apply dynamic styling directly within the template rather than relying on static CSS in the <style> section. Each component now computes style properties from its props and binds them inline. One component additionally introduces a new prop (rowGap) to allow reactive updates of the row-gap style. No modifications have been made to the exported or public entities.

Changes

File(s) Change Summary
packages/builtinComponent/src/components/CanvasCol.vue, packages/builtinComponent/src/components/CanvasFlexBox.vue, packages/builtinComponent/src/components/CanvasRow.vue Updated templates to bind dynamic styles using computed properties derived from props; removed corresponding static CSS style bindings from the <style> sections.
packages/builtinComponent/src/components/CanvasRowColContainer.vue Introduced dynamic binding for the row-gap style via Vue binding and added a new rowGap prop (type [String, Number], default ''), replacing the previous static assignment.

Sequence Diagram(s)

sequenceDiagram
    participant Parent
    participant Component
    participant Template
    Parent->>Component: Pass style-related props
    Component->>Component: Compute dynamic style object
    Component->>Template: Bind computed styles inline (via :style or :styles)
    Template->>Browser: Render element with updated styles
Loading

Possibly related PRs

Suggested labels

bug, refactor-main

Suggested reviewers

  • hexqi
  • gene9831

Poem

In the meadow of code I hop with delight,
Dynamic styles gleam in the soft Vue light.
Flex, gap, and align now dance in tune,
A transformation beneath a binary moon.
CodeRabbit cheers—hop on, keep shining bright! 🐇

Tip

🌐 Web search-backed reviews and chat
  • We have enabled web search-based reviews and chat for all users. This feature allows CodeRabbit to access the latest documentation and information on the web.
  • You can disable this feature by setting web_search: false in the knowledge_base settings.
  • Please share any feedback in the Discord discussion.

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 bug Something isn't working refactor-main refactor/develop branch feature labels Feb 5, 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 (6)
packages/builtinComponent/src/components/CanvasCol.vue (2)

21-54: Consider enhancing prop validation and documentation.

While the props are well-structured, consider these improvements:

  1. Add validator functions for align and justAlign to ensure only valid values from alignMap and justAlignMap are accepted.
  2. Add JSDoc comments to document the expected values and usage of each prop.

Example enhancement:

 const props = defineProps({
   flexBasis: {
     type: String,
+    /** CSS value for flex-basis (e.g., '100px', '50%') */
     default: '0px'
   },
   align: {
     type: [String, Number],
+    /** @type {keyof typeof alignMap} Alignment value */
     default: '',
+    validator: (value) => !value || value in alignMap
   },
   // ... similar improvements for other props
 })

66-72: Consider memoizing the getFlex function.

The getFlex function is called on every computation of the styles object. Consider memoizing it or moving it into the computed property to prevent unnecessary recalculations.

-const getFlex = () => {
+const computedFlex = computed(() => {
   const { flexBasis, grow, shrink, widthType } = props
 
   if (widthType === 'fixed') {
     return `0 0 ${getStyleValue(flexBasis)}`
   }
 
   return `${Number(grow)} ${Number(shrink)} ${getStyleValue(flexBasis)}`
-}
+})

 const styles = computed(() => ({
-  flex: getFlex(props.flexBasis),
+  flex: computedFlex.value,
   rowGap: getStyleValue(props.rowGap),
   // ...
 }))
packages/builtinComponent/src/components/CanvasRow.vue (3)

2-11: Consider extracting complex inline styles to a class-based approach.

While the dynamic styles effectively solve the nested style transmission issue, consider using Vue's class bindings for better maintainability. This could be achieved by defining base styles in CSS and using dynamic classes for variations.

Example approach:

-  <div
-    class="canvas-row"
-    :style="{
-      'min-height': styles.minHeight,
-      'row-gap': styles.rowGap,
-      'column-gap': styles.colGap,
-      'align-items': styles.align,
-      'justify-content': styles.justAlign
-    }"
-  >
+  <div
+    class="canvas-row"
+    :class="styleClasses"
+    :style="{ 'min-height': styles.minHeight }"
+  >

20-41: Add prop documentation and validation.

The props would benefit from:

  1. JSDoc comments explaining each prop's purpose and expected values
  2. Validation for alignment values
  3. More specific default values where applicable

Example enhancement:

 const props = defineProps({
   minHeight: {
     type: [String, Number],
+    validator: (value) => !value || typeof value === 'string' || typeof value === 'number',
     default: ''
   },
   align: {
     type: [String, Number],
+    validator: (value) => !value || Object.keys(alignMap).includes(String(value)),
     default: 'stretch'
   },
   // ... similar changes for other props
 })

1-59: Overall implementation effectively solves the nested style transmission issue.

The transition to dynamic styles successfully addresses the core issue while maintaining component flexibility. The implementation is solid, though there's room for improvement in documentation and maintainability.

Consider documenting the rationale for choosing dynamic inline styles over other approaches in the component's documentation, as this architectural decision impacts the entire component system.

packages/builtinComponent/src/components/CanvasRowColContainer.vue (1)

16-21: Consider adding prop validation.

The rowGap prop accepts both string and number types with an empty string default. Consider adding validation to ensure valid CSS values:

 rowGap: {
   type: [String, Number],
   default: '',
+  validator: (value) => {
+    if (typeof value === 'number') return true
+    if (typeof value === 'string') {
+      return value === '' || /^-?\d*\.?\d+(px|rem|em|%|vh|vw)$/.test(value)
+    }
+    return false
+  }
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a2883f1 and 451863d.

📒 Files selected for processing (4)
  • packages/builtinComponent/src/components/CanvasCol.vue (1 hunks)
  • packages/builtinComponent/src/components/CanvasFlexBox.vue (1 hunks)
  • packages/builtinComponent/src/components/CanvasRow.vue (1 hunks)
  • packages/builtinComponent/src/components/CanvasRowColContainer.vue (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: push-check
🔇 Additional comments (10)
packages/builtinComponent/src/components/CanvasCol.vue (2)

2-12: LGTM! Moving styles to inline bindings helps prevent style inheritance issues.

The transition from CSS variables to inline style bindings is a good approach for fixing the style transmission issues in nested scenarios. The style properties are properly bound and follow Vue.js best practices.


75-81: LGTM! Clean separation of static and dynamic styles.

The style section appropriately retains only the essential flex container properties while moving all dynamic styles to inline bindings. This separation helps prevent style inheritance issues in nested scenarios.

packages/builtinComponent/src/components/CanvasFlexBox.vue (3)

16-50: LGTM! Clean implementation following Vue 3 best practices.

The script setup implementation is well-structured with:

  • Proper prop definitions with types and defaults
  • Efficient use of computed properties
  • Helper function for consistent style value formatting

51-59: LGTM! Style implementation aligns with PR objectives.

The style section effectively addresses the nested component style transmission issue by:

  • Using scoped styles with proper deep selectors
  • Setting appropriate flex properties
  • Ensuring nested containers receive correct width

1-60: Verify the fix in nested component scenarios.

While the implementation looks correct, please ensure thorough testing of:

  1. Style transmission in deeply nested scenarios
  2. Dynamic style updates when props change
  3. Interaction with other canvas components in the hierarchy
packages/builtinComponent/src/components/CanvasRow.vue (2)

52-58: LGTM! Core flex container setup is well-defined.

The static styles appropriately handle the essential flex container properties that don't need to be dynamic.


43-49: Verify helper function implementation.

The computed styles rely on external helper functions. Let's verify their implementation:

✅ Verification successful

🏁 Script executed:

#!/bin/bash
# Search for helper function implementations
echo "Searching for helper.js/ts file..."
fd -e js -e ts -e vue helper
cat $(fd -e js -e ts -e vue helper | head -n 1)

echo "Searching for getStyleValue usage..."
rg "getStyleValue" -A 2

Length of output: 6011


Helper functions verified and working as expected.

  • The getStyleValue function appends "px" for numbers or numeric strings and passes through values with valid CSS units, returning an empty string otherwise.
  • Both alignMap and justAlignMap include appropriate values with fallback defaults in the computed property.
packages/builtinComponent/src/components/CanvasRowColContainer.vue (3)

28-33: LGTM! Clean and focused styles.

The styles are minimal and appropriately focused on layout. The removal of static row-gap in favor of dynamic binding is a good improvement.


2-7: LGTM! Verify nested component behavior.

The dynamic style binding implementation follows Vue's best practices. Since this PR aims to fix style transmission in nested scenarios, let's verify the component's behavior when nested.

Let's check how this component is used in nested scenarios:


14-14: Verify the helper function implementation.

Let's check the implementation of getStyleValue to ensure consistent style value formatting:

✅ Verification successful

🏁 Script executed:

#!/bin/bash
# Search for getStyleValue implementation
ast-grep --pattern 'function getStyleValue($_) {
  $$$
}'

Length of output: 59


Let's run a new shell script to locate the helper file and inspect its contents, especially focusing on the getStyleValue implementation. This will help us verify if the helper function is implemented as expected.


🏁 Script executed:

#!/bin/bash
# Locate the helper file within packages/builtinComponent/src/components
fd "helper\\.(js|ts)$" packages/builtinComponent/src/components

# If the file is found, print its contents for manual inspection.
# Assuming the file is packages/builtinComponent/src/components/helper.js, display its content:
cat packages/builtinComponent/src/components/helper.js || true

Length of output: 1333


Helper function getStyleValue correctly implements style formatting.

  • The function appends "px" to numeric values (both numbers and numeric strings without units), ensuring consistent styling.
  • It passes through values that already include valid units.
  • The fallback to an empty string when the value does not match any criteria is appropriate for avoiding invalid style declarations.

Comment on lines +2 to +11
<div
class="canvas-flex-box"
:styles="{
'flex-direction': styles.flexDirection,
gap: styles.gap,
padding: styles.padding,
'align-items': styles.alignItems,
'justify-content': styles.justifyContent
}"
>
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix incorrect style binding directive.

The template uses :styles which is incorrect. Vue.js uses :style (singular) for style binding.

Apply this diff to fix the style binding:

  <div
    class="canvas-flex-box"
-   :styles="{
+   :style="{
      'flex-direction': styles.flexDirection,
      gap: styles.gap,
      padding: styles.padding,
      'align-items': styles.alignItems,
      'justify-content': styles.justifyContent
    }"
  >
📝 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
<div
class="canvas-flex-box"
:styles="{
'flex-direction': styles.flexDirection,
gap: styles.gap,
padding: styles.padding,
'align-items': styles.alignItems,
'justify-content': styles.justifyContent
}"
>
<div
class="canvas-flex-box"
:style="{
'flex-direction': styles.flexDirection,
gap: styles.gap,
padding: styles.padding,
'align-items': styles.alignItems,
'justify-content': styles.justifyContent
}"
>

<div class="canvas-flex-box">
<div
class="canvas-flex-box"
:styles="{
Copy link
Collaborator

Choose a reason for hiding this comment

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

:styles --> :style

@hexqi hexqi marked this pull request as draft February 14, 2025 03:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working refactor-main refactor/develop branch feature
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants