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

refactor(form): [form] refactor form style #2196

Merged
merged 8 commits into from
Sep 27, 2024
Merged

refactor(form): [form] refactor form style #2196

merged 8 commits into from
Sep 27, 2024

Conversation

gimmyhehe
Copy link
Member

@gimmyhehe gimmyhehe commented Sep 26, 2024

PR

PR Checklist

Please check if your PR fulfills the following requirements:

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

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: N/A

What is the new behavior?

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced new configuration options for forms, including hideRequiredAsterisk, labelWidth, and expanded messageType.
    • Added a new property for icons to enhance visual feedback in forms.
  • Bug Fixes

    • Adjusted default values for various properties to improve form behavior and appearance.
  • Style

    • Updated styling for form components, including new variable declarations and a shift to a more streamlined design approach.
  • Chores

    • Removed outdated components and variables to enhance code maintainability.

Copy link

coderabbitai bot commented Sep 26, 2024

Walkthrough

The changes in this pull request encompass modifications to form configurations across multiple files, including updates to default values, the addition of new properties, and the removal of deprecated components. Key alterations involve the introduction of an icons property, adjustments to error handling mechanisms, and a restructuring of CSS variables for improved theming. The overall aim is to enhance the configuration capabilities and styling consistency of form components.

Changes

File Change Summary
examples/sites/demos/apis/form.js Updated default values for hide-required-asterisk, label-width, and message-type.
packages/design/aurora/src/form/index.ts, packages/design/saas/src/form/index.ts Added icons, hideRequiredAsterisk, and messageType properties to exported default objects.
packages/design/smb/index.ts Removed Form component from exports.
packages/design/smb/src/form/index.ts Deleted configuration object for form component.
packages/renderless/src/form/index.ts Modified computed properties: computedHideRequiredAsterisk, computedValidateIcon, computedIsErrorInline, and computedIsErrorBlock.
packages/renderless/src/form/vue.ts Updated default value for labelWidth.
packages/theme/src/form-item/index.less Simplified styles, removed prefix class variables, and consolidated validation styles.
packages/theme/src/form-item/old-theme.js, packages/theme/src/form/aurora-theme.js Modified naming convention of keys in theme objects.
packages/theme/src/form/vars.less Removed old CSS variables and introduced new ones for icon sizes and colors.
examples/sites/demos/pc/app/form/message-type-composition-api.vue, examples/sites/demos/pc/app/form/message-type.vue Updated messageType initialization and modified messageTypeList.
examples/sites/demos/pc/app/form/label-align-composition-api.vue, examples/sites/demos/pc/app/form/label-align.vue Added :hide-required-asterisk prop to <tiny-form> components.
examples/sites/demos/pc/app/form/message-type.spec.ts, examples/sites/demos/pc/app/form/size.spec.ts, examples/sites/demos/pc/app/form/slot-label.spec.ts, examples/sites/demos/pc/app/form/smb-required.spec.ts Various updates to test cases reflecting changes in form properties and expected outcomes.

Possibly related PRs

Suggested reviewers

  • zzcr

🐰 In the fields where bunnies play,
New forms are hopping in today.
With icons bright and styles so neat,
Our code's a treat, oh what a feat!
So let us cheer, with joy we sing,
For every change, new life they bring! 🥕✨


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 Sep 26, 2024
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: 7

🧹 Outside diff range and nitpick comments (14)
packages/design/aurora/src/form/index.ts (3)

2-4: LGTM! Consider updating documentation.

The addition of the icons object with a validateIcon property is a good enhancement for form styling configuration. This aligns well with the PR objective of refactoring form style.

Consider updating the component's documentation to explain the purpose and usage of the validateIcon property. This will help developers understand how to utilize this new configuration option effectively.


9-9: LGTM! Consider a minor naming improvement.

The addition of the hideRequiredAsterisk property enhances form styling flexibility, which aligns well with the PR objective.

Consider renaming this property to showRequiredAsterisk and setting its default value to true. This would make the property name more intuitive (affirmative rather than negative) and maintain the same default behavior. The new code would look like this:

- hideRequiredAsterisk: false,
+ showRequiredAsterisk: true,

This change would make the code more readable and maintain the current default behavior.


10-10: LGTM! Consider adding documentation and improving type safety.

The addition of the messageType property enhances form styling flexibility, which aligns well with the PR objective.

Consider the following improvements:

  1. Add documentation to explain the purpose of messageType and its possible values.
  2. Use a string literal type to improve type safety and developer experience. For example:
messageType: '' as '' | 'error' | 'warning' | 'success'

This change would provide better autocomplete suggestions and catch potential typos at compile-time.

packages/design/saas/src/form/index.ts (2)

9-9: LGTM. Consider updating documentation.

The addition of hideRequiredAsterisk with a default value of false is a good choice. It allows users to optionally hide the asterisks for required fields while keeping them visible by default.

Consider updating the component's documentation to reflect this new configuration option, explaining its purpose and usage.


2-10: Overall, good additions. Consider enhancing PR description.

The changes introduce new configuration options (icons, hideRequiredAsterisk, messageType) that enhance the form component's flexibility. These additions align with the PR objective of refactoring the form style by providing more control over the form's appearance.

To improve the PR's clarity and facilitate easier review:

  1. Consider updating the PR description to explain the specific improvements these new configuration options bring.
  2. Provide examples of how these new options can be used to enhance form styling or behavior.
  3. If applicable, include before/after screenshots to visually demonstrate the impact of these changes.
packages/renderless/src/form/index.ts (1)

Line range hint 1-80: Summary of form style refactoring changes

The changes in this file primarily focus on refactoring the default behaviors of various form properties:

  1. Required asterisks are now hidden by default.
  2. A default error icon is now set.
  3. The computedIsErrorInline function has been simplified.
  4. Error messages are now displayed as blocks by default.

While these changes align with the PR objective and generally improve the code, they may have significant impacts on existing form implementations. It's crucial to thoroughly test these changes across various scenarios to ensure they don't introduce unexpected visual or functional regressions.

Consider the following recommendations:

  1. Update the component documentation to reflect these new default behaviors.
  2. Create or update visual regression tests to capture any layout changes resulting from these modifications.
  3. Review and update any affected unit tests to account for the new default behaviors.
packages/vue/src/form-item/src/pc.vue (1)

41-42: LGTM: New component registered correctly.

The IconError component is properly registered using the imported iconError function. The naming convention follows Vue best practices.

Consider adding a comment explaining the purpose of the IconError component for better code readability:

 components: {
   LabelWrap,
   Tooltip,
+  // IconError: Used for displaying error icons in the form
   IconError: iconError()
 },
examples/sites/demos/apis/form.js (1)

Line range hint 1-624: Summary of Form API changes

The changes to the Form API documentation improve clarity, flexibility, and default behaviors. Key points:

  1. The hide-required-asterisk now defaults to true.
  2. The default label-width has been slightly increased to '84px'.
  3. The message-type option has been enhanced with more flexibility and a new default value.

These changes, while beneficial, may impact existing implementations.

The updates to the API documentation are generally improvements.

Please ensure that all these changes are properly documented in the changelog and that the main documentation is updated to reflect these new defaults and options.

packages/theme/src/form/index.less (1)

30-30: Inconsistent CSS variable prefixes.

There is an inconsistency in the prefixes of CSS variables used:

  • Line 30: --ti-Form-label-top-margin-bottom
  • Line 38: --tv-Form-icon-color-error
  • Line 40: --tv-Form-icon-size

For consistency and maintainability, consider standardizing the CSS variable prefixes to use either --ti- or --tv- throughout the file.

Also applies to: 38-38, 40-40

packages/theme/src/form-item/vars.less (1)

14-53: Consider using English for code comments to improve maintainability

The code comments are currently written in Chinese. To enhance readability and collaboration among international team members, it's recommended to use English for code comments.

packages/theme/src/form-item/index.less (4)

Line range hint 17-30: Ensure Consistent Variable Naming Conventions

The introduction of prefix variables like @form-prefix-cls, @input-prefix-cls, etc., is a good practice for maintaining consistency. Please verify that this naming convention aligns with the project's standards and is consistent across the codebase.


75-76: Address Pending TODO Comment

There's a TODO comment indicating that the font-family style should be removed after global font styles are added. To maintain code cleanliness, it's advisable to resolve TODOs promptly.

Would you like assistance in adding the global font styles so this inline style can be removed? I can help create a solution or open a GitHub issue to track this task.


127-129: Ensure Consistent Application of Font Sizes and Line Heights

Variables like --tv-FormItem-font-size and --tv-FormItem-line-height are used across multiple elements. Verify that these variables are consistently applied to maintain a uniform appearance throughout the form components.

Also applies to: 138-152, 169-169


259-263: Review Spacing for Extra Tip Section

The .form-item__extra-tip class has a margin-top: 8px. Confirm that this spacing aligns with the overall design system and doesn't introduce unintended gaps or misalignment.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between ca051e7 and 4219529.

📒 Files selected for processing (15)
  • examples/sites/demos/apis/form.js (3 hunks)
  • packages/design/aurora/src/form/index.ts (1 hunks)
  • packages/design/saas/src/form/index.ts (1 hunks)
  • packages/design/smb/index.ts (0 hunks)
  • packages/design/smb/src/form/index.ts (0 hunks)
  • packages/renderless/src/form/index.ts (3 hunks)
  • packages/renderless/src/form/vue.ts (1 hunks)
  • packages/theme/src/form-item/index.less (9 hunks)
  • packages/theme/src/form-item/old-theme.js (1 hunks)
  • packages/theme/src/form-item/vars.less (1 hunks)
  • packages/theme/src/form/aurora-theme.js (1 hunks)
  • packages/theme/src/form/index.less (1 hunks)
  • packages/theme/src/form/old-theme.js (1 hunks)
  • packages/theme/src/form/vars.less (1 hunks)
  • packages/vue/src/form-item/src/pc.vue (2 hunks)
💤 Files not reviewed due to no reviewable changes (2)
  • packages/design/smb/index.ts
  • packages/design/smb/src/form/index.ts
✅ Files skipped from review due to trivial changes (2)
  • packages/theme/src/form/aurora-theme.js
  • packages/theme/src/form/old-theme.js
🔇 Additional comments (17)
packages/design/aurora/src/form/index.ts (1)

1-11: Overall, good refactoring of form styling configuration.

The changes introduced in this file align well with the PR objective of refactoring form style. The new properties (icons, hideRequiredAsterisk, and messageType) enhance the form component's configurability, allowing for more flexible styling options.

A few minor suggestions have been made to improve naming, documentation, and type safety. These improvements would further enhance the developer experience and code maintainability.

Great work on this refactoring effort!

packages/design/saas/src/form/index.ts (2)

2-4: Clarify the purpose of validateIcon and consider a meaningful default.

The addition of the icons property with validateIcon is noted, but its purpose and usage are not clear from the context.

Could you provide more information on how validateIcon is used in the form component?

Also, consider setting a more meaningful default value for validateIcon instead of an empty string, if applicable. This could improve the out-of-the-box experience for developers using this configuration.


10-10: Clarify the purpose and consider a more specific type for messageType.

The addition of the messageType property is noted, but its purpose and possible values are not clear from the context.

Could you provide more information on how messageType is used in the form component and what values it can take?

Consider using a more specific type (like a string union type in TypeScript) or a meaningful default value instead of an empty string. This could improve type safety and make the intended use clearer.

packages/theme/src/form/vars.less (1)

14-17: 🛠️ Refactor suggestion

New icon-related variables added

The addition of --tv-Form-icon-size and --tv-Form-icon-color-error variables is a good step towards more consistent and maintainable icon styling in forms. These variables use predefined values, which promotes consistency across the theme.

However, I have a few observations:

  1. The naming convention has changed from --ti- to --tv-. Is this part of a larger refactoring effort? If so, ensure this change is consistent across all files and documented.

  2. Several variables related to form validation and layout have been removed. Please confirm that these are no longer needed and that their removal doesn't negatively impact the form's functionality or appearance.

  3. The comments are in Chinese. Consider using English comments for better international collaboration, or implement a localization strategy for comments if multilingual support is a project requirement.

Consider adding brief English translations alongside the Chinese comments:

-  // 表单图标大小
+  // 表单图标大小 (Form icon size)
   --tv-Form-icon-size: var(--tv-icon-size);
-  // 表单错误提示图标颜色
+  // 表单错误提示图标颜色 (Form error icon color)
   --tv-Form-icon-color-error: var(--tv-color-error-icon);

To ensure consistency in variable naming and usage across the project, run the following script:

packages/renderless/src/form/vue.ts (1)

84-84: Approved change, but clarification and documentation needed.

The update of the default labelWidth from '80px' to '84px' aligns with the PR objective of refactoring the form style. However, I have a few suggestions:

  1. Could you please clarify the reasoning behind changing the default width to 84px specifically? Understanding the motivation will help in reviewing the change more effectively.

  2. It's recommended to document this change in the component's documentation, as it might affect the layout of forms using the default label width.

  3. Please verify the impact of this change on existing forms that rely on the default label width. Consider adding before/after screenshots to the PR description to visualize the improvement.

To help assess the impact of this change, you can run the following script to find all usages of the Form component without an explicit labelWidth prop:

This will help identify forms that might be affected by the default labelWidth change.

packages/renderless/src/form/index.ts (3)

68-68: Simplification of computedIsErrorInline is correct.

The removal of || false is a good simplification. The function will still return false if designConfig?.messageType is not 'inline', maintaining the same behavior as before.


56-56: Verify the impact of changing the default validate icon.

The default value for validateIcon has been changed from null to 'icon-error'. This means that an error icon will be displayed by default unless explicitly set otherwise. Please ensure this aligns with the intended design and doesn't introduce unexpected visual changes in existing forms.

To check the impact, run the following script:

#!/bin/bash
# Search for usages of validateIcon prop
rg --type vue 'validateIcon'

77-80: Verify the impact of changing the default error display to block.

The computedIsErrorBlock function has been updated with two significant changes:

  1. It now uses Object.hasOwnProperty.call() to safely check for the existence of messageType in designConfig.
  2. The default return value has been changed to true, meaning error messages will be displayed as blocks by default.

These changes improve the safety of the property check and alter the default error message display behavior. Please ensure this aligns with the intended design and doesn't introduce unexpected layout changes in existing forms.

To check the impact, run the following script:

#!/bin/bash
# Search for usages of messageType prop or inlineMessage prop
rg --type vue 'messageType|inlineMessage'
packages/vue/src/form-item/src/pc.vue (2)

28-28: LGTM: New import statement added correctly.

The import of iconError from @opentiny/vue-icon is properly placed and follows the correct naming convention.


28-28: Verify the usage of the new IconError component.

The changes successfully add the IconError component to the form item, which aligns with the PR objective of refactoring the form style. The implementation is consistent with Vue best practices and doesn't introduce any breaking changes.

To ensure the IconError component is being used correctly, please run the following script:

If the script doesn't find any usage of IconError in the template, consider adding it to the appropriate place in the form item's render function.

Also applies to: 41-42

✅ Verification successful

Re-run the verification scripts without specifying the file type.

To address the previous errors with unrecognized file types, please execute the following script:


The usage of the IconError component has been successfully verified.

The IconError component is correctly integrated into the form item without any related TODOs. The implementation aligns with the PR objective and adheres to Vue best practices.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of IconError component in the form item template.

# Test: Search for IconError usage in the template. Expect: At least one occurrence.
rg --type vue 'IconError' packages/vue/src/form-item/src/pc.vue

# Test: Check if there are any TODO comments related to IconError. Expect: No occurrences.
rg --type vue 'TODO.*IconError' packages/vue/src/form-item/src/pc.vue

Length of output: 191


Script:

#!/bin/bash
# Description: Verify the usage of IconError component in the form item template without specifying file type.

# Test: Search for IconError usage in the template. Expect: At least one occurrence.
rg 'IconError' packages/vue/src/form-item/src/pc.vue

# Test: Check if there are any TODO comments related to IconError. Expect: No occurrences.
rg 'TODO.*IconError' packages/vue/src/form-item/src/pc.vue

Length of output: 140

examples/sites/demos/apis/form.js (2)

134-141: Enhancements to message-type option

  1. The message-type now includes 'absolute' as a valid type, providing more flexibility in positioning error messages.
  2. The default value has been changed from an empty string to 'block', making the behavior more predictable.
  3. The description has been updated to clarify the behavior when validate-type is set to text.

These changes improve the flexibility and clarity of the message-type option. The new default value of 'block' may affect existing implementations that relied on the previous default behavior.

Let's check for any existing usage of message-type that might be affected:

#!/bin/bash
# Search for existing usage of message-type
rg --type js --type vue 'message-type'

122-122: Minor adjustment to default label-width

The default value for label-width has been changed from '80px' to '84px'.

This change is likely for design consistency or to accommodate longer labels. However, it would be helpful to understand the reasoning behind this specific adjustment.

To ensure this change doesn't negatively impact existing forms, let's check for any hardcoded widths:

packages/theme/src/form/index.less (1)

34-44: Refactored validation styles enhance maintainability.

The consolidation of validation styles under .@{form-prefix-cls}__valid simplifies the stylesheet and improves readability. The use of nested selectors is effective and aligns with best practices.

packages/theme/src/form-item/vars.less (1)

52-53: Verify the margin-bottom value for the 'xs' size

The variable --tv-FormItem-margin-bottom-xs is set to 20px, while other sizes (md, lg, sm) have a margin-bottom of 24px. Please confirm if this difference is intentional.

packages/theme/src/form-item/index.less (3)

Line range hint 31-60: Review Line-Height and Height Alignment

In the .size-height(@height, @margin-bottom) mixin, line-height is set to @height for various elements. Ensure that using the same value for both height and line-height does not cause vertical alignment issues, especially with different font sizes or when content wraps.


198-206: Verify Error Styling Variables

The error styles now use variables such as var(--tv-FormItem-text-color-error) and var(--tv-FormItem-icon-color-error). Please confirm that these variables are defined and conform to the design specifications for error states.

Also applies to: 212-222


236-242: Ensure Error State Styles Meet Accessibility Standards

The updated error state styles for inputs and textareas change border-color and background-color. Verify that these color changes provide sufficient contrast ratios as per accessibility guidelines.

Also applies to: 254-255

Comment on lines +2 to +12
'ti-FormItem-margin-bottom-medium': 'var(--ti-common-space-5x, 20px)',
'ti-FormItem-margin-bottom-small': 'var(--ti-common-space-5x, 20px)',
'ti-FormItem-margin-bottom-mini': 'var(--ti-common-space-4x, 16px)',
'ti-FormItem-margin-bottom-default': 'var(--ti-common-space-5x, 20px)',
'ti-FormItem-input-medium-height': 'var(--ti-common-size-10x, 40px)',
'ti-FormItem-input-small-height': 'var(--ti-common-size-8x, 32px)',
'ti-FormItem-input-mini-height': 'var(--ti-common-size-6x, 24px)',
'ti-FormItem-label-padding-right': 'var(--ti-common-space-2x, 8px)',
'ti-FormItem-mini-line-height': 'var(--ti-common-line-height-5, 24px)',
'ti-FormItem-medium-line-height': 'calc(var(--ti-common-line-height-7, 36px) + 4px)',
'ti-FormItem-small-line-height': 'var(--ti-common-line-height-6, 32px)'
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Old CSS variable names still present in the codebase.

The search revealed that the following old CSS variable names are still in use:

  • ti-form-item-error-text-color in packages/theme/src/theme/infinity-theme/component-vars.js
  • ti-form-item-error-bg-color in packages/theme/src/theme/infinity-theme/component-vars.js

These instances indicate that not all old CSS variable names have been updated, which may lead to inconsistencies and potential styling issues.

🔗 Analysis chain

Consistent renaming of CSS variables improves code style.

The refactoring of CSS variable names from kebab-case to PascalCase for the component name part (e.g., form-item to FormItem) improves consistency with Vue component naming conventions. This change enhances code readability and maintainability.

To ensure that these changes don't break existing code, please run the following script to check for any remaining usage of the old variable names:

Consider adopting full PascalCase for the entire variable name, including the 'ti' prefix, for complete consistency. For example:

- 'ti-FormItem-margin-bottom-medium'
+ 'Ti-FormItem-margin-bottom-medium'

While this change improves consistency, it potentially introduces a breaking change for consumers of this theme. Consider the following:

  1. If this is a public API, ensure that this change is communicated clearly in the changelog and documentation.
  2. Consider providing a migration guide or deprecation warnings if backwards compatibility is a concern.
  3. Update any documentation that references these CSS variables to reflect the new naming convention.
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for usage of old CSS variable names

# Test: Search for old variable names. Expect: No results
rg --type css --type vue --type js 'ti-form-item-'

Length of output: 78


Script:

#!/bin/bash
# Description: Check for usage of old CSS variable names in .css, .js, and .vue files

# Search for old variable names. Expect: No results
rg 'ti-form-item-' --glob '*.css' --glob '*.js' --glob '*.vue'

Length of output: 289

@@ -47,13 +47,13 @@ export const computedAutoLabelWidth =
export const computedHideRequiredAsterisk =
({ props, designConfig }: Pick<IFormRenderlessParams, 'props' | 'designConfig'>) =>
(): boolean => {
return props.hideRequiredAsterisk ?? designConfig?.hideRequiredAsterisk ?? false
return props.hideRequiredAsterisk ?? designConfig?.hideRequiredAsterisk ?? true
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Impact of Changing Default Behavior for Hiding Required Asterisks

Changing the default value of hideRequiredAsterisk from false to true affects multiple components across different packages. This alteration will hide required field indicators by default unless explicitly overridden. Please review the following files to ensure this change aligns with the intended design and does not adversely affect form usability:

  • packages/vue/src/form/src/index.ts
  • packages/renderless/types/form-item.type.ts
  • packages/renderless/types/form.type.ts
  • packages/renderless/src/form/vue.ts
  • packages/renderless/src/form-item/vue.ts
  • packages/renderless/src/form/index.ts
  • packages/design/saas/src/form/index.ts
  • packages/design/aurora/src/form/index.ts
🔗 Analysis chain

Verify the impact of changing the default behavior for hiding required asterisks.

The default behavior for hideRequiredAsterisk has been changed from false to true. This means that required field indicators will be hidden by default unless explicitly set. Please ensure this aligns with the intended design and doesn't negatively impact form usability.

To check the impact, run the following script:



🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for usages of hideRequiredAsterisk prop
rg --type vue 'hideRequiredAsterisk'

Length of output: 71


Script:

#!/bin/bash
# Search for usages of hideRequiredAsterisk prop in TypeScript files
rg --type typescript 'hideRequiredAsterisk'

Length of output: 78


Script:

#!/bin/bash
# Search for usages of hideRequiredAsterisk prop in TypeScript files
rg 'hideRequiredAsterisk' --glob '*.ts' --glob '*.tsx'

Length of output: 770

Comment on lines +47 to +50
defaultValue: 'true',
desc: {
'zh-CN': '是否隐藏必填字段的标签旁边的红色星号,SMB 主题下默认值为true',
'en-US':
'Whether to hide the red asterisk next to the label of mandatory fields, The default value for SMB theme is true'
'zh-CN': '是否隐藏必填字段的标签旁边的红色星号',
'en-US': 'Whether to hide the red asterisk next to the label of mandatory fields'
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Significant change in default behavior for hide-required-asterisk

The default value for hide-required-asterisk has been changed from false to true. This means that by default, the red asterisk next to mandatory fields will now be hidden unless explicitly set to false.

The description update improves clarity and internationalization.

Please ensure that this change in default behavior is intentional and documented in the changelog, as it may affect existing implementations.

The updated description is clear and concise.

Comment on lines +62 to +68
.star-selector(@content) {
&.is-required:not(.is-no-asterisk) {
// 子选择器是避免影响嵌套表单场景
.@{form-item-prefix-cls}__label-wrap > .@{form-item-prefix-cls}__label:before,
& > .@{form-item-prefix-cls}__label:before {
@content();
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Assess Accessibility of .star-selector Mixin

The .star-selector(@content) mixin adds a visual indicator for required fields. Please ensure that this method does not impact accessibility, and consider whether additional ARIA attributes are needed for screen readers.

Comment on lines +87 to +90
.size-height(
var(--tv-FormItem-height),
var(--tv-FormItem-margin-bottom)
);
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 Simplifying Repetitive Mixin Calls

The .size-height mixin is repeatedly called with different parameters for various size modifiers (--medium, --small, --mini). To reduce repetition, consider parameterizing these calls or consolidating size variables.

Also applies to: 94-95, 101-102, 108-109

Comment on lines +226 to +231
.star-selector({
content: '*';
color: var(--tv-FormItem-text-color-error);
margin-right: 4px;
});

Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Enhance Accessibility for Required Field Indicators

The use of content: '*' in the .star-selector mixin visually denotes required fields. To improve accessibility, ensure that required fields are also programmatically indicated using attributes like aria-required="true".

Comment on lines +267 to +372
vertical-align: top;
margin-right: 24px;
}

.@{form-item-prefix-cls}__label {
float: none;
display: inline-block;
}

.@{form-item-prefix-cls}__content {
display: inline-block;
vertical-align: top;
}

// 嵌套表单场景
.@{form-prefix-cls}--label-top .@{form-item-prefix-cls}__content {
display: block;
}
}

&--label-left {
&.has-required {
.@{form-item-prefix-cls}__label {
padding-left: 12px;
}
}
.@{form-item-prefix-cls}__label {
text-align: left;
}

&.label-align {
.@{form-item-prefix-cls} {
&.is-required {
.@{form-item-prefix-cls}__label {
padding-left: 12px;
position: relative;

&::before {
position: absolute;
left: 0;
}
}
& ~ .@{form-item-prefix-cls} {
.@{form-item-prefix-cls}__label {
padding-left: 12px;
}
}
}
}
}
}

&--label-top {
.@{form-item-prefix-cls} {
margin-bottom: 16px;
}
.@{form-item-prefix-cls}__label {
float: none;
display: block;
text-align: left;
padding: 0 0 8px;
height: auto;
line-height: var(--tv-FormItem-line-height);
}
}

&.is-display-only {
.@{form-item-prefix-cls}__label {
line-height: var(--tv-FormItem-line-height);
height: auto;
vertical-align: inherit;
color: var(--tv-FormItem-text-color-weaken);
}

.@{form-item-prefix-cls}__content {
line-height: var(--tv-FormItem-line-height);
font-size: var(--tv-FormItem-font-size);
height: auto;
vertical-align: inherit;

// 一些组件的只读态实现方式怪异,需要一些修正样式来修复水平对齐问题
.@{switch-prefix-cls} {
margin-top: 0;
}

.@{css-prefix}numeric.is-display-only {
margin-top: 2px;
}
.@{input-prefix-cls} {
&.@{range-editor-prefix-cls}.@{input-prefix-cls}__inner {
height: 18px;
}
}
}

.@{form-item-prefix-cls} {
.star-selector({
content: '';
});
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Refactor Complex Nested Selectors for Better Maintainability

Within the .@{form-prefix-cls} block, there are deeply nested selectors for different form states (&--inline, &--label-left, &--label-top, etc.). Consider refactoring these into separate, more manageable blocks or using mixins to improve readability and maintainability.

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 (8)
examples/sites/demos/pc/app/form/message-type.spec.ts (1)

16-19: LGTM! Consider adding comments for improved readability.

The changes to the test case look good. The new order of button clicks and assertions covers all three types of error message positioning (block, inline, and absolute) in a logical sequence. The assertions correctly match the expected behavior for each button click.

To improve code readability, consider adding brief comments before each button click to explain the purpose of each test case. For example:

// Test block-level display
await getBtnByText('块级').click()
await expect(firstItemError).toHaveCSS('display', 'flex')

// Test inline display
await getBtnByText('行内').click()
await expect(firstItemError).toHaveCSS('display', 'inline-block')

// Test absolute positioning
await getBtnByText('绝对定位').click()
await expect(firstItemError).toHaveCSS('position', 'absolute')

This addition would make the test's structure and purpose even clearer at a glance.

examples/sites/demos/pc/app/form/label-align-composition-api.vue (3)

4-10: LGTM: Addition of :hide-required-asterisk="false" prop

The addition of the :hide-required-asterisk="false" prop to the <tiny-form> component is correct and consistent with the component's existing structure. This change explicitly sets the visibility of required field asterisks, which can improve form clarity for users.

A few observations:

  1. The new prop aligns well with the form's purpose of demonstrating label alignment options.
  2. The false value ensures that required field asterisks are shown, which is generally a good practice for form usability.
  3. The prop is correctly placed within the component's attribute list.

Consider adding a comment explaining the purpose of this prop, especially if it's not a commonly used option. For example:

<tiny-form
  ref="ruleFormRef"
  :model="createData"
  label-position="left"
  :label-align="isLabelAlign"
  :hide-required-asterisk="false" <!-- Ensures required field asterisks are visible -->
>

Line range hint 11-19: Enhance password field security and user experience

While the form structure looks good, consider improving the password fields for better security and user experience:

  1. Add autocomplete="new-password" to both password fields to prevent browsers from auto-filling them with saved passwords.
  2. Consider adding a password strength indicator for the main password field.
  3. For the "密钥" (password2) field, add a validation to ensure it matches the main password if it's intended as a confirmation field.

Here's an example of how you could enhance the password fields:

<tiny-form-item label="密码" prop="password" required>
  <tiny-input 
    v-model="createData.password" 
    type="password" 
    show-password 
    autocomplete="new-password"
  ></tiny-input>
  <!-- Add a password strength indicator component here -->
</tiny-form-item>
<tiny-form-item label="确认密码" prop="password2" required>
  <tiny-input 
    v-model="createData.password2" 
    type="password" 
    show-password 
    autocomplete="new-password"
  ></tiny-input>
</tiny-form-item>

Line range hint 4-23: Add form validation logic

The form currently lacks validation logic, which is crucial for ensuring data integrity and providing user feedback. Consider adding form validation rules and handling form submission.

Here's an example of how you could add basic form validation:

  1. Add validation rules in the <script setup> section:
import { reactive } from 'vue'

const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于 6 个字符', trigger: 'blur' }
  ],
  password2: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== createData.password) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})
  1. Add the :rules="rules" prop to the <tiny-form> component.

  2. Implement a submit method:

const submitForm = async () => {
  if (!ruleFormRef.value) return
  try {
    await ruleFormRef.value.validate()
    // Handle successful validation (e.g., API call)
    console.log('Form submitted successfully')
  } catch (error) {
    console.error('Form validation failed', error)
  }
}
  1. Add a submit button to the form:
<tiny-form-item>
  <tiny-button type="primary" @click="submitForm">提交</tiny-button>
</tiny-form-item>

These changes will significantly improve the form's functionality and user experience.

examples/sites/demos/pc/app/form/label-align.vue (1)

4-10: LGTM! Consider a minor improvement for clarity.

The addition of :hide-required-asterisk="false" to the <tiny-form> component is correct and aligns with the PR objective of refactoring the form style. This change explicitly ensures that required field indicators are shown.

For improved readability, consider using the positive form of the prop:

- :hide-required-asterisk="false"
+ :show-required-asterisk="true"

This change would make the intent clearer at a glance, assuming the tiny-form component supports this prop name.

examples/sites/demos/pc/app/form/message-type-composition-api.vue (2)

52-52: Improved clarity in messageTypeList options

The change from { text: '默认', value: '' } to { text: '块级', value: 'block' } is a good improvement. It removes the ambiguous empty string value and provides a more descriptive option that aligns with the actual behavior.

Consider using consistent naming between the text and value properties. For example:

{ text: 'Block', value: 'block' }

This would improve readability and maintain consistency across different language settings.


49-54: Summary of changes and suggestions

The changes in this file improve the form component's message type functionality by:

  1. Setting a default message type of 'block'.
  2. Clarifying the options in messageTypeList.
  3. Adding a new 'absolute' positioning option.

These changes enhance the component's usability and flexibility. To further improve the code:

  1. Consider adding comments explaining the purpose of each message type option.
  2. Update the component's documentation to reflect these changes, especially the new 'absolute' positioning option.
  3. If not already present, add unit tests to cover the different message type behaviors.

Consider extracting the messageTypeList to a separate constants file if it's used across multiple components. This would improve maintainability and ensure consistency across the application.

examples/sites/demos/pc/app/form/message-type.vue (1)

53-53: LGTM: Updated label for 'block' message type

The change from '默认' (default) to '块级' (block-level) for the 'block' value is more descriptive and aligns well with the new default messageType. This improves clarity for users.

Consider adding a comment explaining the meaning of each message type, especially for non-Chinese speakers who might maintain this code in the future. For example:

messageTypeList: [
  { text: '块级', value: 'block' }, // Block-level messages
  { text: '行内', value: 'inline' }, // Inline messages
  { text: '绝对定位', value: 'absolute' } // Absolutely positioned messages
],
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 4219529 and 386c418.

📒 Files selected for processing (11)
  • examples/sites/demos/pc/app/form/label-align-composition-api.vue (1 hunks)
  • examples/sites/demos/pc/app/form/label-align.vue (1 hunks)
  • examples/sites/demos/pc/app/form/message-type-composition-api.vue (1 hunks)
  • examples/sites/demos/pc/app/form/message-type.spec.ts (1 hunks)
  • examples/sites/demos/pc/app/form/message-type.vue (1 hunks)
  • examples/sites/demos/pc/app/form/size.spec.ts (1 hunks)
  • examples/sites/demos/pc/app/form/slot-label.spec.ts (1 hunks)
  • examples/sites/demos/pc/app/form/smb-required.spec.ts (0 hunks)
  • packages/design/aurora/src/form/index.ts (1 hunks)
  • packages/design/saas/src/form/index.ts (1 hunks)
  • packages/theme/src/form-item/index.less (9 hunks)
💤 Files not reviewed due to no reviewable changes (1)
  • examples/sites/demos/pc/app/form/smb-required.spec.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/design/aurora/src/form/index.ts
  • packages/design/saas/src/form/index.ts
  • packages/theme/src/form-item/index.less
🔇 Additional comments (9)
examples/sites/demos/pc/app/form/slot-label.spec.ts (1)

13-13: LGTM! Consider verifying visual appearance.

The change in the expected text for the third form item label aligns with the PR objective of refactoring the form style. The new text '超过两行文字,省略显示' (which translates to "More than two lines of text, ellipsis display") suggests an improvement in handling longer label text.

To ensure the visual changes meet expectations, please verify:

  1. The form correctly displays the new, longer label text.
  2. The ellipsis is applied appropriately when the text exceeds two lines.
  3. The overall layout of the form remains consistent and visually appealing with this change.

Consider adding a visual regression test if not already in place.

examples/sites/demos/pc/app/form/label-align.vue (1)

Line range hint 1-55: Summary: Successful refactoring of form style

The changes in this file successfully implement the PR objective of refactoring the form style. The addition of the :hide-required-asterisk="false" prop to the <tiny-form> component enhances the form's configuration options by explicitly showing required field indicators.

Key points:

  1. The change is minimal and focused, affecting only the template section.
  2. No modifications were needed in the script or style sections.
  3. The change is consistent with the AI-generated summary and doesn't introduce any breaking changes.

Overall, this refactoring improves the clarity of the form's behavior regarding required fields.

examples/sites/demos/pc/app/form/message-type-composition-api.vue (2)

49-49: Improved default state for messageType

The initialization of messageType with 'block' is a good change. It ensures that the form always has a valid message type, even before user interaction. This aligns well with the updates in the messageTypeList and provides a better default state for the component.


54-54: New option for absolute positioning of error messages

The addition of { text: '绝对定位', value: 'absolute' } to messageTypeList is a good enhancement. It expands the functionality of the form component by allowing more flexible error message placement.

To ensure this new option is properly documented and implemented, please run the following script:

Please ensure that the new 'absolute' option is properly documented and implemented in the form component. If necessary, update the documentation and add appropriate test cases for this new functionality.

examples/sites/demos/pc/app/form/size.spec.ts (2)

Line range hint 1-52: Overall assessment: LGTM with minor verification needed.

The change in this file is consistent with the PR objective of refactoring the form style. The modification of the 'small' form element height from 32px to 28px maintains a logical progression of sizes (medium: 40px, small: 28px, mini: 24px).

The test case structure remains intact, and the change is applied consistently within the file. However, it's important to ensure this change is reflected across the entire codebase and documentation.


26-26: Verify the new 'small' form element height.

The height for 'small' form elements has been changed from 32px to 28px. This adjustment affects the expected height for the submit button, input field, and label when the 'small' size is selected.

  1. Please confirm that this change accurately reflects the new design specifications for 'small' form elements.
  2. Ensure that this change is consistent across all components that use the 'small' size.
  3. Update any related documentation or design guidelines to reflect this new height value for 'small' form elements.

To verify this change across the codebase, you can run the following script:

This script will help identify any inconsistencies or places where the old value might still be used.

✅ Verification successful

'small' form element height change verified successfully.

No inconsistencies found with the new height value of 28px for 'small' form elements across the codebase. All references have been updated accordingly.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for other occurrences of form element heights
# and verify consistency with the new 'small' size value.

echo "Searching for 'small' size definitions in .vue and .ts files:"
rg --type vue --type typescript -i 'small.*height.*32px' -g '!examples/'

echo "Searching for form item height definitions:"
rg --type vue --type typescript -i 'form-item.*height' -g '!examples/'

Length of output: 439


Script:

#!/bin/bash
# Description: Search for other occurrences of form element heights
# and verify consistency with the new 'small' size value by targeting specific file extensions.

echo "Searching for 'small' size definitions in .vue and .ts files:"
rg -i 'small.*height.*32px' --glob '*.vue' --glob '*.ts' -g '!examples/'

echo "Searching for form item height definitions in .vue and .ts files:"
rg -i 'form-item.*height' --glob '*.vue' --glob '*.ts' -g '!examples/'

Length of output: 427

examples/sites/demos/pc/app/form/message-type.vue (3)

50-50: LGTM: Default message type set to 'block'

Setting a default value for messageType is a good practice. It ensures that the form always has a defined message type, improving predictability and potentially avoiding undefined behavior.


50-55: Overall assessment: Good refactoring of form styles

The changes made to this file improve the form component by:

  1. Setting a clear default message type.
  2. Providing more descriptive labels for message type options.
  3. Adding a new 'absolute' positioning option for increased flexibility.

These modifications enhance both the usability and maintainability of the form component. Good job on this refactoring effort!


55-55: LGTM: Added 'absolute' positioning option for messages

The addition of an 'absolute' positioning option for messages increases the flexibility of the form component. This is a good enhancement that allows for more diverse layouts.

To ensure this new option is properly implemented, please verify:

  1. The form component correctly handles the 'absolute' value for message-type.
  2. There's appropriate CSS to style absolutely positioned messages.
  3. The documentation is updated to reflect this new option.

You can use the following script to check for related CSS and documentation updates:

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.

2 participants