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 setValues not support dayjs and Date value #5064

Merged
merged 3 commits into from
Dec 7, 2024

Conversation

mynetfan
Copy link
Collaborator

@mynetfan mynetfan commented Dec 7, 2024

Description

修复setFormValues的值类型合并算法没有考虑dayjs对象类型值以及Date类型值的问题。antd的日期时间相关组件的值类型为dayjs对象,而ElementPlus的日期时间相关组件的值可能为Date类型

fix #5061

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 error handling for setting form values, improving stability.
    • Updated merging logic to better handle complex data types, specifically dayjs and Date objects.
    • Introduced new utility functions for improved type-checking: isDate and isDayjsObject.
  • Bug Fixes

    • Addressed limitations in the merging algorithm to prevent issues with dayjs and Date objects during value setting.

Copy link

changeset-bot bot commented Dec 7, 2024

⚠️ No Changeset found

Latest commit: 787083b

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 Dec 7, 2024

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.

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

Oops! Something went wrong! :(

ESLint: 9.16.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

The pull request modifies the FormApi class in form-api.ts, specifically enhancing the setValues method. Key changes include the addition of a comment regarding limitations with dayjs object handling, an updated merging logic that excludes dayjs and Date objects, and improved error handling. The updateState, getForm, and other methods remain unchanged, maintaining existing functionality while enhancing the robustness of the merging process for specific object types.

Changes

File Path Change Summary
packages/@core/ui-kit/form-ui/src/form-api.ts Modified setValues method: added error handling, updated merging logic for dayjs and Date objects, and included comments on limitations.
packages/@core/base/shared/src/utils/date.ts Added two new functions: isDate and isDayjsObject for type-checking capabilities.

Assessment against linked issues

Objective Addressed Explanation
Fix error when calling setValues with dayjs objects (5061)

Possibly related PRs

Suggested labels

bug

Suggested reviewers

  • vince292007
  • anncwb

Poem

In the meadow where forms do play,
A setValues fix brightens the day.
With dayjs now kept at bay,
Errors vanish, come what may!
Hops of joy, let’s leap and sway! 🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 463cfbe and 787083b.

📒 Files selected for processing (1)
  • packages/@core/ui-kit/form-ui/src/form-api.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/@core/ui-kit/form-ui/src/form-api.ts

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.

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

🧹 Outside diff range and nitpick comments (2)
packages/@core/ui-kit/form-ui/src/form-api.ts (2)

255-258: Enhance comment clarity regarding the dayjs object handling

While the comment explains the limitation, it could be more specific about the implemented solution. Consider updating it to explicitly mention that dayjs objects are excluded from deep merging via the $isDayjsObject check.

-    /**
-     * 合并算法有待改进,目前的算法不支持object类型的值。
-     * 但是Antd的日期时间类型的组件值为dayjs对象类型,也是一个object类型,这里将dayjs对象排除深度合并
-     */
+    /**
+     * The merge strategy has a limitation with object-type values.
+     * For Ant Design's date/time components that use dayjs objects,
+     * we explicitly exclude them from deep merging by checking the
+     * $isDayjsObject property to preserve their integrity.
+     */

255-275: Consider a more generic special object type handling mechanism

While the current solution fixes the dayjs object issue, consider implementing a more generic mechanism for handling special object types in the form values. This could be achieved through:

  1. A registry of special object types and their merge strategies
  2. A pluggable system for custom object type handlers
  3. Metadata-based merge strategy selection

This would make the form API more extensible for future special object types beyond dayjs.

Would you like me to propose a detailed design for this enhancement?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between d1862fb and 6abc2c7.

📒 Files selected for processing (1)
  • packages/@core/ui-kit/form-ui/src/form-api.ts (1 hunks)
🔇 Additional comments (1)
packages/@core/ui-kit/form-ui/src/form-api.ts (1)

258-270: Verify edge cases in the merge function

The merge function correctly handles dayjs objects, but consider these edge cases:

  1. Nested dayjs objects in arrays
  2. Null/undefined values that might have $isDayjsObject property
  3. Objects that might coincidentally have $isDayjsObject property but aren't dayjs objects

Let's verify the dayjs object handling:

✅ Verification successful

Based on the gathered evidence, I can now generate the final response:

The dayjs object handling in the merge function is appropriate and safe

The implementation correctly handles dayjs objects by checking the $isDayjsObject property before applying the merge. The codebase shows consistent handling of dayjs objects:

  1. Dayjs objects are primarily used in date picker form fields (as seen in playground examples)
  2. The form handles time-related values through dedicated transformation logic (handleRangeTimeValue)
  3. The merge function's edge cases are properly covered:
    • Objects are checked for $isDayjsObject before any merge attempts
    • Arrays are explicitly excluded from merging
    • The check is combined with isObject validation
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for dayjs object usage patterns in the codebase
# to ensure consistent handling

# Look for dayjs object assignments to form values
rg -l "setValues.*dayjs" 

# Look for other places where dayjs objects might be handled
ast-grep --pattern 'dayjs($$$)'

Length of output: 137


Script:

#!/bin/bash
# Let's search for more context about dayjs usage and form handling

# Look for dayjs type definitions or interfaces
rg -A 5 "type.*dayjs|interface.*dayjs"

# Search for form value handling patterns
rg -A 5 "form\.values|setValues"

# Look for tests involving dayjs and form values
rg -A 5 "test.*dayjs.*form|describe.*dayjs.*form"

# Search for any validation or type checking related to dayjs
ast-grep --pattern 'isDayjsObject|$isDayjsObject'

Length of output: 11037


Script:

#!/bin/bash
# Let's look for the actual implementation of dayjs object handling

# Search for dayjs object creation and type checking
rg -A 5 "\$isDayjsObject"

# Look for the createMerge utility implementation
ast-grep --pattern 'function createMerge'

# Search for any dayjs-related tests or validation
rg -A 5 "isDayjs|dayjs\(" packages/@core/ui-kit/form-ui/__tests__/

# Look for form value transformation logic
rg -A 5 "handleRangeTimeValue|transformDateValue"

Length of output: 1321

packages/@core/ui-kit/form-ui/src/form-api.ts Outdated Show resolved Hide resolved
@mynetfan mynetfan changed the title fix: setFormValues not support dayjs object value fix: form setValues not support dayjs and Date value Dec 7, 2024
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: 0

🧹 Outside diff range and nitpick comments (2)
packages/@core/ui-kit/form-ui/src/form-api.ts (2)

257-262: Enhance documentation with examples

While the comment explains the limitations well, it would be more helpful to include examples of the problematic cases and how they're now handled.

    /**
     * 合并算法有待改进,目前的算法不支持object类型的值。
     * antd的日期时间相关组件的值类型为dayjs对象
     * element-plus的日期时间相关组件的值类型可能为Date对象
     * 以上两种类型需要排除深度合并
+     * 
+     * Example:
+     * // Before (problematic):
+     * form.setValues({
+     *   date: dayjs('2023-12-25'),  // dayjs object
+     *   time: new Date()            // Date object
+     * });
+     * 
+     * // After (fixed):
+     * // These objects are now excluded from deep merging
     */

266-269: Add test coverage for date object handling

The new date object handling logic should be covered by unit tests to ensure it works correctly with both dayjs and Date objects.

Would you like me to help create unit tests for these scenarios:

  1. Setting form values with dayjs objects
  2. Setting form values with Date objects
  3. Setting form values with mixed object types
  4. Multiple setValues calls with date objects
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 6abc2c7 and 463cfbe.

📒 Files selected for processing (2)
  • packages/@core/base/shared/src/utils/date.ts (1 hunks)
  • packages/@core/ui-kit/form-ui/src/form-api.ts (2 hunks)
🔇 Additional comments (4)
packages/@core/base/shared/src/utils/date.ts (1)

20-26: LGTM! Well-implemented type guards

The new type guard functions are correctly implemented:

  • isDate: Proper use of instanceof for Date objects
  • isDayjsObject: Correct usage of dayjs.isDayjs() for type checking
  • Both use TypeScript type predicates appropriately
packages/@core/ui-kit/form-ui/src/form-api.ts (3)

17-18: LGTM! Appropriate imports added

The new type guard imports are correctly added and maintain the import order.


276-280: 🛠️ Refactor suggestion

Enhance error handling for better debugging

The current error handling could be improved to include more context and implement error recovery.

    try {
      form.setValues(filteredFields, shouldValidate);
    } catch (error) {
-      console.error('setValues error:', error);
+      console.error('Failed to set form values:', {
+        error,
+        fields: filteredFields,
+        shouldValidate,
+      });
+      throw new Error(`Failed to set form values: ${error.message}`);
    }

266-269: Verify form value handling across the codebase

Let's verify that this change doesn't affect other form value scenarios.

✅ Verification successful

Changes to date object handling are safe to proceed

The verification shows that:

  1. The date handling utilities (isDate and isDayjsObject) are properly implemented and used correctly in the form-api
  2. The test suite doesn't reveal any special cases for date handling that could be affected
  3. The form value merging logic correctly preserves both native Date and Dayjs objects by skipping deep merging for these types
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for potential impacts on form value handling

# Search for setValues usage with date/time related fields
echo "Checking setValues usage with date/time fields..."
rg -l "setValues.*date|time|moment|dayjs" --type ts

# Search for form components using date/time pickers
echo "Checking date/time picker component usage..."
rg -l "DatePicker|TimePicker|Calendar" --type vue --type tsx

Length of output: 1101


Script:

#!/bin/bash
# Let's analyze the form-api.ts implementation and its usage more precisely

# Check the implementation of form value handling in form-api.ts
echo "Checking form-api.ts implementation..."
rg -A 5 "setValues|isDate|isDayjsObject" packages/@core/ui-kit/form-ui/src/form-api.ts

# Look for tests related to form value handling
echo "Checking form-related tests..."
fd "form.*test" -e ts -x rg -l "date|dayjs|setValues"

# Search for direct imports of form-api
echo "Checking form-api imports..."
rg "from.*form-api" --type ts

Length of output: 1513


Script:

#!/bin/bash
# Let's check the test file to understand the expected behavior with dates

# Check form-api test implementation
echo "Checking form-api test cases..."
cat packages/@core/ui-kit/form-ui/__tests__/form-api.test.ts

# Look for the actual implementation of isDayjsObject and isDate utilities
echo "Checking utility functions implementation..."
rg -A 3 "export.*function.*isDayjsObject|export.*function.*isDate" packages/@core/base/shared/src/utils/

Length of output: 5920

@mynetfan mynetfan merged commit b75a8e6 into vbenjs:main Dec 7, 2024
13 checks passed
@mynetfan mynetfan deleted the fix/form-set-values branch December 7, 2024 03:09
@anncwb anncwb added the bug Something isn't working label Dec 11, 2024
@github-actions github-actions bot locked and limited conversation to collaborators Jan 11, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Bug: 表单连续两次setValues报错
2 participants