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

Illiar/fix/v2 bugfixes #3016

Merged
merged 5 commits into from
Feb 4, 2025
Merged

Illiar/fix/v2 bugfixes #3016

merged 5 commits into from
Feb 4, 2025

Conversation

chesterkmr
Copy link
Collaborator

@chesterkmr chesterkmr commented Jan 31, 2025

  • Reworked validation
  • Adjusted KYB validation settings
  • Fixed Focus/Blur events across all inputs(except multiselect)
  • Updated styorbook
  • Fixed bug when old context was sent onSubmit instead of updated context recieved from tasks.

Summary by CodeRabbit

Based on the comprehensive summary of changes, here are the release notes:

Release Notes

  • Validation Enhancements

    • Improved form validation with more granular control over validation behavior
    • Added ability to stop validation after first error
    • Enhanced validation timing and feedback mechanisms
  • Accessibility Improvements

    • Added focus and blur event handling for form components
    • Improved keyboard navigation support across form elements
  • Form Submission

    • Updated form submission logic to handle values more dynamically
    • Simplified submit method signatures
  • Performance Optimizations

    • Streamlined validation hooks
    • Reduced validation delay from 500ms to 300ms
    • Improved memoization of validation functions
  • Type Safety

    • Enhanced TypeScript type definitions for form and validation components
    • More precise typing for event handlers and validation parameters

Copy link

changeset-bot bot commented Jan 31, 2025

⚠️ No Changeset found

Latest commit: 6859cf5

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 31, 2025

Walkthrough

This pull request introduces comprehensive changes to form validation and input handling across multiple components in the UI package. The modifications focus on enhancing validation behavior, improving type safety, and refactoring validation-related hooks and utilities. Key changes include updating validation parameters, adding focus and blur event handling, and streamlining the validation process by consolidating multiple validation methods into a more unified approach.

Changes

File Change Summary
packages/ui/src/components/organisms/Form/Validator/hooks/internal/useValidate/useValidate.ts Centralized validation logic, removed multiple validation methods, added abortAfterFirstError parameter
packages/ui/src/components/organisms/Form/Validator/utils/validate/validate.ts Added abortAfterFirstError parameter, enhanced validation flow with new error handling
Multiple form-related components Added focus/blur event handling, improved accessibility with tabIndex
packages/ui/src/components/organisms/Form/DynamicForm/hooks/external/useSubmit/useSubmit.ts Modified submission logic to accept values as an argument

Sequence Diagram

sequenceDiagram
    participant User
    participant Form
    participant Validator
    participant SubmitHandler

    User->>Form: Interact with form
    Form->>Validator: Validate input
    alt Validation on change/blur enabled
        Validator-->>Form: Return validation errors
    end
    User->>Form: Submit form
    Form->>Validator: Validate all fields
    alt Abort after first error
        Validator-->>Form: Stop at first error
    else Validate all fields
        Validator-->>Form: Collect all errors
    end
    Form->>SubmitHandler: Submit with validated values
Loading

Possibly related PRs

Suggested Labels

bug_fix, enhancement, Review effort [1-5]: 3, Bug fix

Suggested Reviewers

  • Omri-Levy
  • alonp99

Poem

🐰 Validation's dance, a rabbit's delight,
Errors caught swiftly, with focus so bright
Hooks refactored, types aligned just right
Form's journey smoother, a technological might
Hop, hop, hooray for code that's tight! 🌟

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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: 4

🧹 Nitpick comments (15)
packages/ui/src/components/organisms/Form/DynamicForm/fields/DocumentField/DocumentField.tsx (2)

72-78: Consider enhancing the file handling logic.

Creating an empty File with just a name might lead to issues during upload or processing. Consider adding MIME type information and handling the case where the file content is needed.

Here's a suggested improvement:

-    if (typeof value === 'string') {
-      return new File([], value);
-    }
+    if (typeof value === 'string') {
+      // Create a File with a default MIME type and empty content
+      return new File([], value, { type: 'application/octet-stream' });
+      // Or consider fetching the actual file content if value is a file ID/URL
+    }

112-114: Enhance accessibility with ARIA attributes.

While the keyboard accessibility improvements are good, consider adding ARIA attributes to provide better context for screen reader users.

Add these ARIA attributes to the container div:

 <div
   className={ctw(
     'relative flex h-[56px] flex-row items-center gap-3 rounded-[16px] border bg-white px-4',
     { 'pointer-events-none opacity-50': disabled || disabledWhileUploading },
   )}
   onClick={focusInputOnContainerClick}
   data-testid={createTestId(element, stack)}
   tabIndex={0}
   onFocus={onFocus}
   onBlur={onBlur}
+  role="button"
+  aria-label={`Upload ${placeholder}`}
+  aria-disabled={disabled || disabledWhileUploading}
 >
packages/ui/src/components/molecules/inputs/DropdownInput/DropdownInput.tsx (1)

111-113: Consider refining the focus handling implementation.

While the focus/blur event handling improvements are good, there are two suggestions for enhancement:

  1. The tabIndex={0} prop is redundant as buttons are focusable by default.
  2. Consider avoiding type casting with as by properly typing the component props.

Apply this diff to remove the redundant tabIndex and improve type safety:

-          tabIndex={0}
-          onFocus={onFocus as FocusEventHandler<HTMLButtonElement>}
-          onBlur={onBlur as FocusEventHandler<HTMLButtonElement>}
+          onFocus={event => onFocus?.(event as unknown as FocusEvent<HTMLInputElement>)}
+          onBlur={event => onBlur?.(event as unknown as FocusEvent<HTMLInputElement>)}

This approach:

  • Removes the redundant tabIndex
  • Makes the type conversion explicit in the callback
  • Preserves the expected HTMLInputElement event type for consumers
packages/ui/src/components/organisms/Form/Validator/hooks/internal/useValidate/useValidate.ts (1)

49-60: Review artificial async delay
A 10ms delay is introduced by setTimeout, presumably to simulate an async process. If not strictly required, consider removing or making it adjustable. This can reduce confusion and avoid needless event-loop scheduling.

-        setTimeout(() => {
+        // setTimeout(() => {
           resolve(errors);
-        }, 10);
+        // }, 10);
packages/ui/src/components/organisms/Form/Validator/utils/validate/exceptions.ts (1)

1-5: Consider setting the error name
Defining AbortAfterFirstErrorException clarifies the nature of a termination. However, setting an explicit this.name provides clearer stack traces and debugging insights.

export class AbortAfterFirstErrorException extends Error {
  constructor() {
    super('Abort after first error');
+    this.name = 'AbortAfterFirstErrorException';
  }
}
packages/ui/src/components/organisms/Form/Validator/ValidatorProvider.tsx (1)

7-7: LGTM! Enhanced type organization and validation control.

Good improvement in type organization by extending IValidateParams. Consider adding JSDoc comments to document the validation behavior, particularly around the abortAfterFirstError functionality.

Add documentation for the interface:

+/**
+ * Parameters for configuring form validation behavior.
+ * @extends IValidateParams Base validation parameters
+ */
 export interface IValidationParams extends IValidateParams {

Also applies to: 9-9

packages/ui/src/components/organisms/Form/Validator/types/index.ts (1)

1-2: LGTM! Improved type organization with central type alias.

Good addition of a central type alias for validation parameters. Consider adding documentation to explain its purpose and usage.

Add documentation for the type alias:

+/**
+ * Central type definition for validation parameters.
+ * Used to maintain consistent validation configuration across components.
+ */
 export type TValidationParams = IUseValidateParams;

Also applies to: 58-59

packages/ui/src/components/organisms/Form/DynamicForm/controls/SubmitButton/SubmitButton.tsx (1)

43-48: Improve error handling in validation result.

The validation result handling could be more robust by adding type checking and error details.

-    const validationResult = await validate();
-    const isValid = validationResult?.length === 0;
-
-    if (!isValid) {
-      console.log(`Submit button clicked but form is invalid`);
-      console.log('Validation errors', validationResult);
+    const validationResult = await validate();
+    const isValid = Array.isArray(validationResult) && validationResult.length === 0;
+
+    if (!isValid) {
+      console.warn('Form validation failed:', {
+        errors: validationResult,
+        timestamp: new Date().toISOString(),
+      });
packages/ui/src/components/organisms/Form/Validator/utils/validate/validate.ts (1)

41-74: Consider optimizing nested try-catch blocks.

The nested try-catch blocks could be simplified to improve readability while maintaining the same functionality.

-      try {
-        for (const validator of validators) {
-          if (
-            validator.applyWhen &&
-            !isShouldApplyValidation(
-              replaceTagsWithIndexesInRule([validator.applyWhen], stack)[0],
-              context,
-            )
-          ) {
-            continue;
-          }
-
-          const validate = getValidator(validator);
-
-          try {
-            validate(value, validator as unknown as ICommonValidator);
-          } catch (exception) {
-            const error = createValidationError({
-              id,
-              invalidValue: value,
-              message: (exception as Error).message,
-              stack,
-            });
-
-            validationErrors.push(error);
-
-            if (abortAfterFirstError) {
-              throw new AbortAfterFirstErrorException();
-            }
-
-            // Validation of all schema will be stopped if at least one error is found
-            if (abortEarly) {
-              throw validationErrors;
-            }
-          }
-        }
+      try {
+        await Promise.all(validators.map(async validator => {
+          if (
+            validator.applyWhen &&
+            !isShouldApplyValidation(
+              replaceTagsWithIndexesInRule([validator.applyWhen], stack)[0],
+              context,
+            )
+          ) {
+            return;
+          }
+
+          const validate = getValidator(validator);
+          
+          try {
+            await validate(value, validator as unknown as ICommonValidator);
+          } catch (exception) {
+            const error = createValidationError({
+              id,
+              invalidValue: value,
+              message: (exception as Error).message,
+              stack,
+            });
+
+            validationErrors.push(error);
+
+            if (abortAfterFirstError) {
+              throw new AbortAfterFirstErrorException();
+            }
+
+            if (abortEarly) {
+              throw validationErrors;
+            }
+          }
+        }));
packages/ui/src/components/organisms/Form/DynamicForm/controls/SubmitButton/SubmitButton.unit.test.tsx (1)

82-82: LGTM! Consider adding test cases for validation failure scenarios.

The mock implementation of validate consistently returns a resolved promise with an empty array, which is good for testing successful validation scenarios. However, consider adding test cases where validation fails to ensure the component handles validation errors correctly.

Add test cases for validation failure scenarios:

it('handles validation failure', async () => {
  vi.mocked(useValidator).mockReturnValue({
    isValid: true,
    errors: {},
    values: {},
    validate: vi.fn().mockResolvedValue([{ id: 'test', message: ['Error'] }]),
  });
  
  // Test implementation
});

Also applies to: 152-152, 247-247

packages/ui/src/components/organisms/Form/DynamicForm/DynamicForm.unit.test.tsx (1)

280-285: LGTM! Consider adding error handling test cases.

The test verifies that the submit method is called with the correct values. However, it would be beneficial to add test cases for error scenarios.

Add test cases for error handling:

it('should handle submit errors gracefully', () => {
  const mockError = new Error('Submit failed');
  const ref = { current: null as IFormRef<any> | null };
  submitMock.submit.mockRejectedValue(mockError);
  
  render(<DynamicFormV2 {...mockProps} ref={ref} />);
  
  expect(async () => {
    await ref.current?.submit();
  }).rejects.toThrow(mockError);
});
packages/ui/src/components/organisms/Form/DynamicForm/hooks/external/useField/useField.unit.test.ts (2)

Line range hint 182-197: LGTM! Consider adding race condition test cases.

The test correctly verifies the validation behavior when validateOnBlur is false. However, it would be beneficial to add test cases for potential race conditions.

Add test cases for race conditions:

it('should handle multiple rapid blur events correctly', async () => {
  const { result } = renderHook(() => useField(mockElement, mockStack));
  
  // Simulate multiple rapid blur events
  const promises = [
    result.current.onBlur(),
    result.current.onBlur(),
    result.current.onBlur()
  ];
  
  await Promise.all(promises);
  
  // Verify that validation was called only once
  expect(mockValidate).toHaveBeenCalledTimes(1);
});

Line range hint 200-220: LGTM! Consider adding edge case test for validation delay.

The test correctly verifies the validation delay behavior. Consider adding test cases for edge cases.

Add test cases for edge cases:

it('should handle validation delay interruption', async () => {
  const { result } = renderHook(() => useField(mockElement, mockStack));
  
  await result.current.onBlur();
  
  // Advance time partially
  vi.advanceTimersByTime(50);
  
  // Trigger another blur
  await result.current.onBlur();
  
  // Verify intermediate state
  expect(mockSetTouched).not.toHaveBeenCalled();
  
  // Complete the delay
  vi.advanceTimersByTime(70);
  
  // Verify final state
  expect(mockSetTouched).toHaveBeenCalledTimes(1);
});
packages/ui/src/components/organisms/Form/Validator/utils/validate/validate.unit.test.ts (1)

911-913: LGTM! Consider adding type validation test cases.

The type check in evenNumberValidator is a good addition. Consider adding specific test cases for type validation.

Add test cases for type validation:

it('should handle non-number values correctly', () => {
  const data = {
    notANumber: '19',
    nullValue: null,
    undefinedValue: undefined
  };
  
  const schema = [
    {
      id: 'notANumber',
      valueDestination: 'notANumber',
      validators: [{ type: 'evenNumber', value: {} }]
    },
    // Add similar schema entries for nullValue and undefinedValue
  ];
  
  const errors = validate(data, schema);
  expect(errors).toEqual([]);
});
packages/ui/src/components/organisms/Form/DynamicForm/hooks/external/useField/useField.ts (1)

51-59: LGTM! Consider adding error handling.

The async implementation aligns well with the PR objectives to fix blur events. However, consider adding error handling for the async operations.

Consider this improvement:

   const onBlur = useCallback(async () => {
-    sendEvent('onBlur');
+    try {
+      sendEvent('onBlur');
 
-    if (validationParams.validateOnBlur) {
-      validate();
-    }
+      if (validationParams.validateOnBlur) {
+        validate();
+      }
 
-    await setTouched(fieldId, true);
+      await setTouched(fieldId, true);
+    } catch (error) {
+      console.error('Error in onBlur:', error);
+      // Consider how to handle validation/UI feedback on error
+    }
   }, [sendEvent, validationParams.validateOnBlur, validate, fieldId, setTouched]);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c44a8ec and 4462e6a.

📒 Files selected for processing (34)
  • apps/kyb-app/src/pages/CollectionFlow/versions/v2/components/organisms/CollectionFlowUI/CollectionFlowUI.tsx (2 hunks)
  • packages/ui/src/components/molecules/inputs/DropdownInput/DropdownInput.tsx (2 hunks)
  • packages/ui/src/components/molecules/inputs/MultiSelect/MultiSelect.tsx (4 hunks)
  • packages/ui/src/components/organisms/Form/DynamicForm/DynamicForm.tsx (1 hunks)
  • packages/ui/src/components/organisms/Form/DynamicForm/DynamicForm.unit.test.tsx (1 hunks)
  • packages/ui/src/components/organisms/Form/DynamicForm/_stories/InputsShowcase/InputsShowcase.tsx (16 hunks)
  • packages/ui/src/components/organisms/Form/DynamicForm/_stories/ValidationShowcase/ValidationShowcase.tsx (1 hunks)
  • packages/ui/src/components/organisms/Form/DynamicForm/context/dynamic-form.context.ts (1 hunks)
  • packages/ui/src/components/organisms/Form/DynamicForm/context/types.ts (1 hunks)
  • packages/ui/src/components/organisms/Form/DynamicForm/controls/SubmitButton/SubmitButton.tsx (3 hunks)
  • packages/ui/src/components/organisms/Form/DynamicForm/controls/SubmitButton/SubmitButton.unit.test.tsx (3 hunks)
  • packages/ui/src/components/organisms/Form/DynamicForm/fields/DocumentField/DocumentField.tsx (2 hunks)
  • packages/ui/src/components/organisms/Form/DynamicForm/fields/FieldList/FieldList.tsx (2 hunks)
  • packages/ui/src/components/organisms/Form/DynamicForm/fields/FileField/FileField.tsx (2 hunks)
  • packages/ui/src/components/organisms/Form/DynamicForm/hooks/external/useField/useField.ts (1 hunks)
  • packages/ui/src/components/organisms/Form/DynamicForm/hooks/external/useField/useField.unit.test.ts (3 hunks)
  • packages/ui/src/components/organisms/Form/DynamicForm/hooks/external/useSubmit/useSubmit.ts (1 hunks)
  • packages/ui/src/components/organisms/Form/DynamicForm/hooks/external/useSubmit/useSubmit.unit.test.ts (2 hunks)
  • packages/ui/src/components/organisms/Form/Validator/ValidatorProvider.tsx (2 hunks)
  • packages/ui/src/components/organisms/Form/Validator/context/types.ts (1 hunks)
  • packages/ui/src/components/organisms/Form/Validator/hooks/internal/useValidate/useAsyncValidate.ts (0 hunks)
  • packages/ui/src/components/organisms/Form/Validator/hooks/internal/useValidate/useAsyncValidate.unit.test.ts (0 hunks)
  • packages/ui/src/components/organisms/Form/Validator/hooks/internal/useValidate/useManualValidate.ts (0 hunks)
  • packages/ui/src/components/organisms/Form/Validator/hooks/internal/useValidate/useManualValidate.unit.test.ts (0 hunks)
  • packages/ui/src/components/organisms/Form/Validator/hooks/internal/useValidate/useSyncValidate.ts (0 hunks)
  • packages/ui/src/components/organisms/Form/Validator/hooks/internal/useValidate/useSyncValidate.unit.test.ts (0 hunks)
  • packages/ui/src/components/organisms/Form/Validator/hooks/internal/useValidate/useValidate.ts (2 hunks)
  • packages/ui/src/components/organisms/Form/Validator/hooks/internal/useValidate/useValidate.unit.test.ts (1 hunks)
  • packages/ui/src/components/organisms/Form/Validator/types/index.ts (2 hunks)
  • packages/ui/src/components/organisms/Form/Validator/utils/validate/exceptions.ts (1 hunks)
  • packages/ui/src/components/organisms/Form/Validator/utils/validate/types.ts (1 hunks)
  • packages/ui/src/components/organisms/Form/Validator/utils/validate/validate.ts (2 hunks)
  • packages/ui/src/components/organisms/Form/Validator/utils/validate/validate.unit.test.ts (2 hunks)
  • packages/ui/src/components/organisms/Form/hooks/useRuleEngine/useRuleEngine.unit.test.ts (1 hunks)
💤 Files with no reviewable changes (6)
  • packages/ui/src/components/organisms/Form/Validator/hooks/internal/useValidate/useAsyncValidate.unit.test.ts
  • packages/ui/src/components/organisms/Form/Validator/hooks/internal/useValidate/useManualValidate.unit.test.ts
  • packages/ui/src/components/organisms/Form/Validator/hooks/internal/useValidate/useAsyncValidate.ts
  • packages/ui/src/components/organisms/Form/Validator/hooks/internal/useValidate/useSyncValidate.ts
  • packages/ui/src/components/organisms/Form/Validator/hooks/internal/useValidate/useSyncValidate.unit.test.ts
  • packages/ui/src/components/organisms/Form/Validator/hooks/internal/useValidate/useManualValidate.ts
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: Analyze (javascript)
  • GitHub Check: test_windows
  • GitHub Check: test_linux
  • GitHub Check: build (windows-latest)
  • GitHub Check: lint
  • GitHub Check: build (ubuntu-latest)
🔇 Additional comments (35)
packages/ui/src/components/molecules/inputs/DropdownInput/DropdownInput.tsx (1)

4-11: LGTM! Import changes align with focus/blur event handling improvements.

The addition of FocusEventHandler type is appropriate for the focus/blur event handler implementations.

packages/ui/src/components/organisms/Form/DynamicForm/fields/FieldList/FieldList.tsx (4)

3-3: LGTM!

The import of FocusEventHandler is necessary for proper type-checking of the focus and blur event handlers.


32-32: LGTM!

The addition of onFocus and onBlur handlers from the useField hook aligns with the PR objectives of fixing Focus and Blur events.


36-38: LGTM!

The addition of braces improves code clarity while maintaining the same logic.


41-47: Verify keyboard navigation behavior.

The implementation of focus and blur events is correct. However, since the container div is now focusable and contains interactive elements (buttons), please verify that:

  1. Keyboard navigation (Tab key) works as expected through all interactive elements.
  2. The container's focus/blur events don't interfere with child element events.
packages/ui/src/components/molecules/inputs/MultiSelect/MultiSelect.tsx (3)

8-8: LGTM!

The addition of FocusEventHandler import is appropriate for the new focus/blur event handling.


53-55: LGTM!

The addition of braces improves code readability while maintaining the same logic.


129-131: LGTM!

The addition of braces improves code readability while maintaining the same logic.

packages/ui/src/components/organisms/Form/Validator/hooks/internal/useValidate/useValidate.ts (6)

1-4: New imports and interface parameter
The addition of abortAfterFirstError in the interface, along with the concise imports, looks clean and well-organized.

Also applies to: 10-10


20-20: Default parameter assignment
Using validationDelay = undefined as a signal to skip debouncing is a neat approach, and ensuring abortAfterFirstError defaults to false is sensible.

Also applies to: 22-22


25-30: Immediate validation logic
Initializing validationErrors with a direct call to validate when validationDelay === undefined and validateOnChange is enabled is consistent. This ensures synchronous validation from the outset.


41-47: Synchronous validation callback
Centralizing synchronous validation via validateSyncCallback is straightforward and correctly updates state with new errors.


62-66: Synchronous validation in layout effect
Using useLayoutEffect for immediate validation when validationDelay is undefined ensures the DOM remains in sync with real-time validation.


80-80: Final return
Exposing externalValidate as validate neatly completes the hook’s external API, providing a promise-based validation method.

packages/ui/src/components/organisms/Form/Validator/utils/validate/types.ts (1)

3-3: Extended validation parameter
Adding abortAfterFirstError?: boolean is a clear way to allow immediate termination of validation upon encountering the first error.

packages/ui/src/components/organisms/Form/Validator/context/types.ts (1)

7-7: LGTM! Good improvement to validation handling.

Making validation asynchronous and returning validation errors improves error handling capabilities and allows for more complex validation rules.

packages/ui/src/components/organisms/Form/DynamicForm/hooks/external/useSubmit/useSubmit.ts (1)

7-13: LGTM! Good improvement to submission handling.

The changes improve flexibility by allowing values to be passed at submission time rather than being fixed when the hook is initialized. The dependency array is correctly updated.

packages/ui/src/components/organisms/Form/DynamicForm/context/types.ts (1)

20-20: LGTM! Good consistency with useSubmit changes.

The submit method signature change maintains type safety and aligns well with the changes in the useSubmit hook.

packages/ui/src/components/organisms/Form/DynamicForm/_stories/ValidationShowcase/ValidationShowcase.tsx (1)

9-10: LGTM! Improved validation timing for better UX.

The changes to validation timing (validating on blur instead of change) will provide a better user experience by not showing validation errors while users are still typing.

packages/ui/src/components/organisms/Form/DynamicForm/hooks/external/useSubmit/useSubmit.unit.test.ts (1)

36-36: LGTM! Enhanced test coverage with explicit value testing.

The tests now properly verify the submit function's behavior with actual values, making them more robust and reflective of real usage patterns.

Also applies to: 45-45

packages/ui/src/components/organisms/Form/Validator/ValidatorProvider.tsx (1)

30-30: LGTM! Consistent parameter passing.

The abortAfterFirstError parameter is correctly passed through to the useValidate hook.

Also applies to: 38-38

packages/ui/src/components/organisms/Form/DynamicForm/controls/SubmitButton/SubmitButton.tsx (1)

59-61: LGTM! Event handling is properly sequenced.

The submit and event dispatch sequence is correct, with the form submission preceding the event dispatch.

packages/ui/src/components/organisms/Form/Validator/utils/validate/validate.ts (1)

77-82: LGTM! Exception handling is properly implemented.

The exception handling for AbortAfterFirstErrorException is correctly implemented, allowing for graceful continuation of validation.

apps/kyb-app/src/pages/CollectionFlow/versions/v2/components/organisms/CollectionFlowUI/CollectionFlowUI.tsx (1)

23-29: Consider the performance impact of immediate validation.

The current validation parameters enable both onChange and onBlur validation with a short delay, which might cause performance issues with complex forms.

Consider these optimizations:

  1. Increase validationDelay for better performance
  2. Use validateOnChange selectively for specific fields
  3. Implement debouncing for validation calls
packages/ui/src/components/organisms/Form/DynamicForm/DynamicForm.tsx (1)

42-42: LGTM! Submit handling is properly implemented.

The changes to the submit handling are well-structured:

  1. The useSubmit hook now correctly receives only the necessary parameters
  2. The submit method properly passes the current form values

Also applies to: 45-45

packages/ui/src/components/organisms/Form/hooks/useRuleEngine/useRuleEngine.unit.test.ts (1)

49-49: Verify the timing adjustment impact.

The timer delay has been reduced from 600ms to 500ms. While this change is valid, we should verify that 500ms provides sufficient time for rule execution in real-world scenarios.

✅ Verification successful

Test timing adjustment is appropriate

The 500ms delay is consistent with other form-related timings in the codebase, particularly in test scenarios. This change aligns with established patterns and won't impact production behavior.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other timer-related configurations in the codebase
rg -A 2 'advanceTimersByTime|setTimeout|setInterval' --type ts

Length of output: 10815

packages/ui/src/components/organisms/Form/DynamicForm/fields/FileField/FileField.tsx (2)

51-57: LGTM! Code structure improvement.

The added braces enhance readability and maintainability of the conditional checks.


78-80: Good accessibility enhancement!

Adding tabIndex and focus/blur event handlers improves keyboard navigation and accessibility.

packages/ui/src/components/organisms/Form/Validator/hooks/internal/useValidate/useValidate.unit.test.ts (3)

8-15: Well-structured test setup!

Good practice using proper mocking setup for both debounce and validate functions.


46-127: Comprehensive test coverage for validation scenarios.

The test structure effectively covers:

  • Immediate validation
  • Delayed validation
  • Context change handling
  • Multiple validation cycles

This thorough coverage will help maintain validation reliability.


132-161: Good separation of validation method tests.

Clear separation of validation method tests improves maintainability and readability.

packages/ui/src/components/organisms/Form/DynamicForm/_stories/InputsShowcase/InputsShowcase.tsx (3)

17-25: Good validation configuration for TextField.

The combination of required and minLength validations provides good user guidance.


Line range hint 41-236: Consistent validation approach across all fields.

Good practice applying required validation consistently across all form fields.


253-253: Consider validationParams impact.

The abortAfterFirstError: true setting will stop validation after the first error. While this can improve performance, ensure this behavior meets user experience requirements, especially for forms where users might want to see all validation errors at once.

packages/ui/src/components/organisms/Form/Validator/utils/validate/validate.unit.test.ts (1)

77-166: LGTM! Comprehensive test coverage for abort behavior.

The test cases thoroughly verify the abortAfterFirstError functionality with multiple validators. The test data structure is well-organized and covers both positive and negative scenarios.

@chesterkmr chesterkmr merged commit e17db25 into dev Feb 4, 2025
18 checks passed
@chesterkmr chesterkmr deleted the illiar/fix/v2-bugfixes branch February 4, 2025 11:11
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.

3 participants