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: form fieldMappingTime improve and modelPropName support #5335

Merged
merged 2 commits into from
Jan 9, 2025

Conversation

mynetfan
Copy link
Collaborator

@mynetfan mynetfan commented Jan 9, 2025

Description

  1. 表单的fieldMappingTime支持将格式化掩码设为null以便原值映射,这样可以支持非日期时间类型的组件;
  2. 表单增加modelPropName设置组件的双向绑定属性名,用于支持未提前注册的双向绑定属性为非默认名称的组件。
  3. 增加一些经常会有人提到的组合字段演示,

close #5297
close #5290

Type of change

Please delete options that are not relevant.

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update
  • Please, don't make changes to pnpm-lock.yaml unless you introduce a new test example.

Checklist

ℹ️ Check all checkboxes - this will indicate that you have done everything in accordance with the rules in CONTRIBUTING.

  • If you introduce new functionality, document it. You can run documentation with pnpm run docs:dev command.
  • Run the tests with pnpm test.
  • Changes in changelog are generated from PR name. Please, make sure that it explains your changes in an understandable manner. Please, prefix changeset messages with feat:, fix:, perf:, docs:, or chore:.
  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes
  • Any dependent changes have been merged and published in downstream modules

Summary by CodeRabbit

  • Documentation

    • Updated documentation for Vben Form component's fieldMappingTime property
    • Clarified usage and added detailed explanation of property functionality
  • New Features

    • Introduced modelPropName property for more flexible form field configuration
    • Added new TwoFields component for enhanced form input handling
  • Improvements

    • Enhanced form validation logic
    • Refined form field event binding mechanism
    • Updated type definitions for improved type safety
  • Style Changes

    • Modified form validation styling for select and input components

@mynetfan mynetfan requested review from anncwb, vince292007 and a team as code owners January 9, 2025 13:46
Copy link

changeset-bot bot commented Jan 9, 2025

⚠️ No Changeset found

Latest commit: 8310e49

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link
Contributor

coderabbitai bot commented Jan 9, 2025

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.

playground/src/views/examples/form/custom.vue

Oops! Something went wrong! :(

ESLint: 9.17.0

Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/node_modules/@vben/eslint-config/dist/index.mjs' imported from /eslint.config.mjs
at finalizeResolution (node:internal/modules/esm/resolve:257:11)
at moduleResolve (node:internal/modules/esm/resolve:914:10)
at defaultResolve (node:internal/modules/esm/resolve:1038:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:557:12)
at ModuleLoader.resolve (node:internal/modules/esm/loader:525:25)
at ModuleLoader.getModuleJob (node:internal/modules/esm/loader:246:38)
at ModuleJob._link (node:internal/modules/esm/module_job:126:49)

Walkthrough

This pull request introduces enhancements to the Vben Form component's functionality and documentation. The changes focus on improving the fieldMappingTime property, adding a new modelPropName configuration option, and refining form validation and styling. The modifications span multiple files, including documentation, type definitions, form rendering components, and a playground example, aimed at providing more flexibility and clarity in form handling.

Changes

File Change Summary
docs/src/components/common-ui/vben-form.md Updated fieldMappingTime property description and added detailed documentation
packages/@core/ui-kit/form-ui/src/form-api.ts Modified handleRangeTimeValue method to handle null format more flexibly
packages/@core/ui-kit/form-ui/src/form-render/form-field.vue Added modelPropName prop and updated event binding logic
packages/@core/ui-kit/form-ui/src/form-render/form.vue Incorporated modelPropName in computed schema
packages/@core/ui-kit/form-ui/src/types.ts Updated type definitions for modelPropName and FieldMappingTime
packages/styles/src/antd/index.css Refined validation styles for select and input components
playground/src/views/examples/form/custom.vue Added fieldMappingTime and modelPropName configurations
playground/src/views/examples/form/modules/two-fields.vue New component for handling two-field input

Assessment against linked issues

Objective Addressed Explanation
Schema configuration for complex forms [#5297]
Handling composite form fields [#5290]

Possibly related issues

Possibly related PRs

Suggested labels

enhancement, bug

Suggested reviewers

  • anncwb
  • vince292007

Poem

🐰 Hop, hop, through the form's domain,
Where fields dance and validations reign,
modelPropName brings its might,
Mapping time with pure delight,
A rabbit's code, both smart and plain! 🌟

Finishing Touches

  • 📝 Generate Docstrings

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.

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)
playground/src/views/examples/form/modules/two-fields.vue (6)

1-2: Consider importing component types for better type safety.

Import the types from ant-design-vue to ensure proper type checking:

<script lang="ts" setup>
-import { Input, Select } from 'ant-design-vue';
+import type { InputProps, SelectProps } from 'ant-design-vue';
+import { Input, Select } from 'ant-design-vue';

6-8: Enhance type safety with string literal types for country codes.

Consider using more specific types for better type safety and validation:

-const modelValue = defineModel<[string, string]>({
+type CountryCode = '+82' | '+85' | '+86';
+const modelValue = defineModel<[CountryCode, string]>({
   default: ['+85', ''],
 });

10-12: Add validation before emitting the change event.

Consider validating the phone number format before emitting the change event:

 function onChange() {
+  const [countryCode, phone] = modelValue.value;
+  const isValid = phone.match(/^1[3-9]\d{9}$/);
+  if (!isValid) {
+    console.warn('Invalid phone number format');
+  }
   emit('change', modelValue.value);
 }

30-31: Consider implementing i18n for placeholder text.

The placeholder text is hardcoded in Chinese. Consider using i18n for better internationalization support.

-      placeholder="请输入11位手机号码"
+      :placeholder="t('form.phoneNumber.placeholder')"

32-38: Improve phone input validation and accessibility.

Several improvements can be made to enhance validation and accessibility:

  1. Extract the regex pattern to a constant
  2. Add pattern attribute for better mobile validation
  3. Add ARIA attributes for validation status
+const PHONE_PATTERN = /^1[3-9]\d{9}$/;
+const isValidPhone = computed(() => modelValue.value[1]?.match(PHONE_PATTERN));

 <Input
   placeholder="请输入11位手机号码"
   class="flex-1"
-  :class="{ 'valid-success': modelValue[1]?.match(/^1[3-9]\d{9}$/) }"
+  :class="{ 'valid-success': isValidPhone }"
   v-model:value="modelValue[1]"
   :maxlength="11"
   type="tel"
+  :pattern="PHONE_PATTERN.source"
+  :aria-invalid="!isValidPhone"
+  :aria-describedby="!isValidPhone ? 'phone-error' : undefined"
   @blur="emit('blur')"
   @change="onChange"
 />

1-40: Consider making the component more reusable.

To improve reusability, consider:

  1. Accepting props for validation patterns
  2. Allowing customization of country codes
  3. Supporting different phone number formats

This would make the component more flexible for different use cases and regions. Would you like me to provide an example implementation?

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 99c7fd7 and 8310e49.

📒 Files selected for processing (8)
  • docs/src/components/common-ui/vben-form.md (2 hunks)
  • packages/@core/ui-kit/form-ui/src/form-api.ts (1 hunks)
  • packages/@core/ui-kit/form-ui/src/form-render/form-field.vue (2 hunks)
  • packages/@core/ui-kit/form-ui/src/form-render/form.vue (2 hunks)
  • packages/@core/ui-kit/form-ui/src/types.ts (4 hunks)
  • packages/styles/src/antd/index.css (2 hunks)
  • playground/src/views/examples/form/custom.vue (4 hunks)
  • playground/src/views/examples/form/modules/two-fields.vue (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: Test (windows-latest)
  • GitHub Check: Check (windows-latest)
  • GitHub Check: Lint (windows-latest)
  • GitHub Check: Test (ubuntu-latest)
  • GitHub Check: post-update (windows-latest)
  • GitHub Check: post-update (ubuntu-latest)
  • GitHub Check: Check (ubuntu-latest)
  • GitHub Check: Lint (ubuntu-latest)
🔇 Additional comments (12)
playground/src/views/examples/form/custom.vue (3)

21-21: LGTM! Good use of fieldMappingTime with null format.

The configuration correctly demonstrates the new feature allowing original value mapping without formatting.


45-48: LGTM! Proper implementation of modelPropName.

The modelPropName: 'value' configuration correctly demonstrates the new two-way binding property feature.


57-74: Well-structured validation rules with clear error messages.

The Zod validation rules are well-implemented with:

  • Proper array length validation
  • Clear error messages
  • Smart use of full-width space for error message positioning
packages/@core/ui-kit/form-ui/src/types.ts (2)

200-204: Well-documented modelPropName property.

The type definition includes proper JSDoc documentation with default value information.


227-227: LGTM! Proper type support for null format in FieldMappingTime.

The type correctly uses Nullable<string> to support the new null format feature.

packages/@core/ui-kit/form-ui/src/form-render/form-field.vue (1)

206-208: LGTM! Proper fallback logic for modelPropName.

The implementation correctly prioritizes:

  1. Custom modelPropName
  2. Component-specific binding from map
packages/@core/ui-kit/form-ui/src/form-api.ts (1)

371-385: LGTM! Clean implementation of null format support.

The implementation:

  1. Properly handles null format case
  2. Maintains existing functionality for formatted cases
  3. Correctly supports array format for different start/end formats
packages/styles/src/antd/index.css (2)

24-24: Improved validation style specificity for select components

The selector now correctly excludes valid states by checking both the parent and selector elements for the .valid-success class.


43-45: Consistent validation styling for input components

The new rule for input validation follows the same pattern as select components, ensuring consistent visual feedback across form elements.

packages/@core/ui-kit/form-ui/src/form-render/form.vue (1)

101-101: LGTM: Well-implemented model property name support

The addition of modelPropName with proper defaults and merging behavior enables flexible two-way binding support for custom components.

Also applies to: 122-122

docs/src/components/common-ui/vben-form.md (2)

319-319: Well-documented fieldMappingTime enhancement

The documentation clearly explains the broadened scope and null format behavior, with a helpful example that illustrates the usage pattern.

Also applies to: 325-329


415-419: Clear modelPropName documentation

The documentation effectively explains the purpose and default behavior of the modelPropName property.

playground/src/views/examples/form/modules/two-fields.vue Outdated Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (4)
playground/src/views/examples/form/modules/two-fields.vue (3)

4-8: Consider adding runtime type validation for the model value.

While the TypeScript type is correct, consider adding runtime validation to ensure the tuple values are either undefined or strings.

+import type { PropType } from 'vue';
+
 const modelValue = defineModel<[string, string]>({
   default: () => [undefined, undefined],
+  validator: (value): value is [string | undefined, string | undefined] => {
+    return Array.isArray(value) && 
+           value.length === 2 && 
+           value.every(v => v === undefined || typeof v === 'string');
+  }
 });

34-34: Improve phone number validation pattern.

The current regex pattern ^1[3-9]\d{9}$ is specific to Chinese phone numbers. Consider making it more flexible or configurable for international phone numbers.

-:class="{ 'valid-success': modelValue[1]?.match(/^1[3-9]\d{9}$/) }"
+const phonePattern = computed(() => props.phonePattern || /^1[3-9]\d{9}$/);
+:class="{ 'valid-success': modelValue[1]?.match(phonePattern.value) }"

21-21: Consider using scoped CSS classes.

The valid-success class appears to be a global CSS class. Consider using scoped CSS or CSS modules to avoid potential naming conflicts.

+<style scoped>
+.field-valid {
+  border-color: #52c41a;
+}
+</style>

-:class="{ 'valid-success': !!modelValue[0] }"
+:class="{ 'field-valid': !!modelValue[0] }"

-:class="{ 'valid-success': modelValue[1]?.match(/^1[3-9]\d{9}$/) }"
+:class="{ 'field-valid': modelValue[1]?.match(/^1[3-9]\d{9}$/) }"

Also applies to: 34-34

playground/src/views/examples/form/custom.vue (1)

57-77: Consider improving error message alignment.

While the validation rules are well-structured, using full-width spaces ( ) for visual alignment is a fragile solution that may break with different fonts or screen sizes.

Consider using CSS for proper error message alignment:

-          message: '       输入手机号码',
+          message: '输入手机号码',

And add CSS classes to style the error messages:

.ant-form-item-explain-error {
  margin-left: 8em; /* Adjust based on your layout */
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8310e49 and dc7878f.

📒 Files selected for processing (2)
  • playground/src/views/examples/form/custom.vue (4 hunks)
  • playground/src/views/examples/form/modules/two-fields.vue (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: Test (windows-latest)
  • GitHub Check: Test (ubuntu-latest)
  • GitHub Check: Lint (windows-latest)
  • GitHub Check: post-update (windows-latest)
  • GitHub Check: Check (windows-latest)
  • GitHub Check: Lint (ubuntu-latest)
  • GitHub Check: post-update (ubuntu-latest)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Check (ubuntu-latest)
🔇 Additional comments (6)
playground/src/views/examples/form/modules/two-fields.vue (2)

1-2: LGTM! Clean imports and proper TypeScript setup.


10-12: LGTM! Clean event handling implementation.

playground/src/views/examples/form/custom.vue (4)

2-10: LGTM! Well-structured imports with performance optimization.

The addition of markRaw shows attention to performance, and the integration of Zod (z) for validation is a good choice for type-safe form validation.


45-50: LGTM! Proper implementation of modelPropName.

The addition of modelPropName: 'value' aligns with the PR objective of supporting custom two-way binding property names.


Line range hint 91-101: LGTM! Clean template implementation.

The template section properly uses slots and follows Vue best practices for component composition.


21-21: Verify the field mapping implementation.

The fieldMappingTime mapping with null formatter aligns with the PR objective of supporting non-datetime components. However, ensure that the mapped fields phoneType and phoneNumber are properly handled in the parent component.

Run this script to verify the field handling:

✅ Verification successful

Example implementation verified

The fieldMappingTime configuration in custom.vue is a valid example demonstrating how to map multiple fields with a null formatter. Since this is in the examples directory and serves as a demonstration, the implementation is appropriate for its purpose.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if the parent component properly handles these fields
ast-grep --pattern 'phoneType|phoneNumber' 

Length of output: 44


Script:

#!/bin/bash
# Search for phoneType and phoneNumber fields in Vue files
echo "=== Searching for field usage in Vue files ==="
rg -U "phoneType|phoneNumber" --type vue

# Search for specific field mapping patterns
echo -e "\n=== Searching for field mapping configurations ==="
ast-grep --pattern 'fieldMapping = $_'
ast-grep --pattern 'fieldMappingTime = $_'

# Check for related component definitions
echo -e "\n=== Searching for related component definitions ==="
rg -U "field4.*component" --type vue

Length of output: 562


Script:

#!/bin/bash
# Search in the specific directory and its parent
echo "=== Searching for field usage in the form directory ==="
rg -U "phoneType|phoneNumber" playground/src/views/examples/form/

# Search for field4 related configurations
echo -e "\n=== Searching for field4 configurations ==="
rg -U "field4" playground/src/views/examples/form/

# List all files in the form directory for context
echo -e "\n=== Files in the form directory ==="
ls -la playground/src/views/examples/form/

Length of output: 1855

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Bug: schema配置 FEATURE: 请教问题
1 participant