Skip to content

feat: 保存表单字段的blur状态 #5686

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

Closed
wants to merge 1 commit into from

Conversation

lu-yanpeng
Copy link

@lu-yanpeng lu-yanpeng commented Mar 8, 2025

Description

目前表单验证有一个问题,在自定义验证的时候校验方法会被多次调用( #5437),vee-validate的作者表示这是正常的(logaretm/vee-validate#4737),修改值的时候虽然不会显示错误信息,但是会调用校验方法。如果需要异步校验,这样会多次发送请求很浪费资源。

我通过组件的blur事件保存当前字段的blur状态到formApi中,这样自定义校验的时候通过formApi.getFieldBlurState可以拿到当前字段的blur状态,根据这个状态判断要不要发送请求校验数据,避免了多次请求的麻烦。

示例

const [Form, formApi] = useVbenForm({
  schema: [
    {
      fieldName: 'field1',
      formFieldProps: {
        // 必须要设置这两个状态,不设置表示不需要保存字段的blur状态
        validateOnModelUpdate: false,        
        validateOnBlur: true,
      },
      rules: z.string().refine(
        async (v: string | undefined) => {
          const blurState = formApi.getFieldBlurState('field1');
          // 判断当前字段的blur状态,避免修改值时多次触发校验
          if (blurState) {
            await new Promise((resolve) => {
              setTimeout(resolve, 1000);
            });
            return v === '123';
          }
          return true;
        },
        { message: '必须等于123' },
      ),
    },
  ],
});

使用

  1. 在表单中需要设置validateOnModelUpdate: falsevalidateOnBlur: true才能保存字段的blur状态,只有input可以保存,其他类型的字段设置没用
{
formFieldProps: {
        validateOnModelUpdate: false,
        validateOnBlur: true,
      }
}
  1. 在自定义校验的方法中使用const blurState = formApi.getFieldBlurState(fieldName);获取字段的blur状态,如果字段已经blur会返回true

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

  • New Features

    • Enhanced form interactions by tracking focus and blur events. This update improves field validations and user feedback during data entry.
  • Refactor

    • Expanded the form’s contextual capabilities to support extended functionality, ensuring a more robust and responsive user experience.

Copy link

changeset-bot bot commented Mar 8, 2025

⚠️ No Changeset found

Latest commit: cd437f0

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 Mar 8, 2025

Walkthrough

The changes add new functionality for managing form field blur states. A private property and two methods have been introduced to the form API to track and update the blur state of fields. The form field component is updated to trigger these methods on blur and focus events. The form context is extended with an additional type, and the provided form properties now include the form API. Overall, these modifications improve how user focus interactions are tracked and incorporated into form validation.

Changes

File(s) Change Summary
packages/@core/ui-kit/form-ui/src/form-api.ts Added a private fieldBlurState property and two methods (getFieldBlurState and setFieldBlurState) to manage field blur state; updated the unmount method to reset this state.
packages/@core/ui-kit/form-ui/src/form-render/form-field.vue Added an import for injectFormProps, updated fieldProps type, extracted setFieldBlurState from form props, and modified event handlers (onBlur and onFocus) to update the blur state.
packages/@core/ui-kit/form-ui/src/use-form-context.ts Updated the createContext signature to include a third type parameter (ExtendedFormApi), extending the context with additional form API capabilities.
packages/@core/ui-kit/form-ui/src/vben-use-form.vue Modified the call to provideFormProps to include an additional argument (props.formApi), ensuring the form API is provided in the context.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant FFC as Form Field Component
    participant FA as FormApi
    U->>FFC: Triggers onBlur event
    FFC->>FA: setFieldBlurState(fieldName, true)
    Note right of FA: Field blur state is set to true
    U->>FFC: Triggers onFocus event
    FFC->>FA: setFieldBlurState(fieldName, false)
    Note right of FA: Field blur state is reset to false
Loading
sequenceDiagram
    participant Comp as vben Use Form Component
    participant PF as provideFormProps
    participant Context as FormContext
    Comp->>PF: Call provideFormProps([forward, form, formApi])
    PF->>Context: Provides context with extended form API
Loading

Possibly related PRs

Suggested labels

feature

Suggested reviewers

  • vince292007
  • anncwb

Poem

I'm just a rabbit with a codey hop,
Tracking focus and blur, I never stop.
Fields dance on screen in a rhythmic beat,
With each change, my code is neat.
Hop along with logic and delight,
In a world where forms shine bright!
🐇✨


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e2a577d and cd437f0.

📒 Files selected for processing (4)
  • packages/@core/ui-kit/form-ui/src/form-api.ts (4 hunks)
  • packages/@core/ui-kit/form-ui/src/form-render/form-field.vue (4 hunks)
  • packages/@core/ui-kit/form-ui/src/use-form-context.ts (1 hunks)
  • packages/@core/ui-kit/form-ui/src/vben-use-form.vue (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: post-update (windows-latest)
  • GitHub Check: post-update (ubuntu-latest)
🔇 Additional comments (11)
packages/@core/ui-kit/form-ui/src/use-form-context.ts (1)

18-25: Type signature extended to support blur state tracking.

The context now includes ExtendedFormApi as the third element in the tuple, which is necessary to access the newly added blur state functionality.

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

34-34: Form API now provided to the context.

The form API is now passed as the third argument to provideFormProps, which makes the blur state management methods accessible to form fields.

packages/@core/ui-kit/form-ui/src/form-api.ts (4)

59-60: Added private property to track field blur states.

The fieldBlurState record maps field names to their blur states, enabling conditional validation based on user interaction.


91-93: Getter method to access field blur state.

This method allows custom validation logic to check if a field has been blurred before running expensive validation operations.


198-200: Setter method to update field blur state.

This method is used by the form field component to track when a field loses or gains focus.


281-281: Reset blur states on form unmount.

Clearing the blur states when unmounting the form prevents stale state from affecting new form instances.

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

21-21: Added import for accessing form context.

The imported injectFormProps function is necessary to access the form API and its blur state management methods.


193-193: Added explicit return type annotation.

The type annotation provides better type safety and IDE support for the computed property.


243-243: Extracted blur state setter from form context.

This line accesses the third element from the injected form props tuple, which contains the ExtendedFormApi with the blur state management methods.


248-260: Implemented blur state tracking for form fields.

The implementation correctly sets the blur state to true when a field loses focus and resets it to false when the field gains focus. This is only applied when the field is configured with validateOnBlur: true and validateOnModelUpdate: false, matching the requirements in the PR description.

The code also properly chains the original blur handler, ensuring existing functionality is preserved.


272-273: Added blur and focus handlers to component props.

These handlers are now passed to the form field component, enabling the blur state tracking functionality.

✨ Finishing Touches
  • 📝 Generate Docstrings

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai 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.

@lu-yanpeng lu-yanpeng changed the title feat: Added a method in formApi to get the blur state of fields feat: 保存表单字段的blur状态 Mar 9, 2025
@mynetfan
Copy link
Collaborator

mynetfan commented Mar 9, 2025

#5689 提供了新的表单api方法,无需额外保存blur状态

@mynetfan mynetfan closed this Mar 10, 2025
@lu-yanpeng lu-yanpeng deleted the form-2 branch March 10, 2025 09:31
@github-actions github-actions bot locked and limited conversation to collaborators Apr 10, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants