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(web): toggle ok button on modal for updating field #1252

Merged
merged 5 commits into from
Oct 17, 2024

Conversation

caichi-t
Copy link
Contributor

@caichi-t caichi-t commented Oct 8, 2024

Overview

This PR fixes the ok button on modal for updating field to toggle depending on the value.

Summary by CodeRabbit

  • New Features

    • Enhanced error handling and validation in the GeometryItem component.
    • Added feedback mechanism for item deletions in the MultiValueGeometry component.
    • Improved form responsiveness and state management in the FieldModal component.
  • Bug Fixes

    • Refined logic for handling default values and form submissions in the FieldModal component.
  • Documentation

    • Updated type definitions for better clarity and consistency regarding tags and supported types.

Copy link

netlify bot commented Oct 8, 2024

Deploy Preview for reearth-cms ready!

Name Link
🔨 Latest commit c53db71
🔍 Latest deploy log https://app.netlify.com/sites/reearth-cms/deploys/671090b0b2c76d0008ae320c
😎 Deploy Preview https://deploy-preview-1252--reearth-cms.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

@github-actions github-actions bot added the web label Oct 8, 2024
Co-authored-by: Nour Balaha <nourbalaha0@gmail.com>
Copy link

coderabbitai bot commented Oct 16, 2024

Walkthrough

The pull request introduces several enhancements across multiple components, primarily focusing on error handling, validation, and state management. The GeometryItem component now has improved error handling in the typeCheck function and refined state management for displaying errors. The MultiValueGeometry component adds error handling for item deletions. The FieldModal component's hooks are updated for better form value management, including a new handleValuesChange function. Additionally, type definitions in types.ts are standardized for consistency. Overall, these changes enhance the reliability and interactivity of the components.

Changes

File Change Summary
web/src/components/molecules/Common/Form/GeometryItem/index.tsx Updated typeCheck for robust error handling, modified logic for valid geometry types, refined handleEditorOnChange, and improved state management for error tracking. Enhanced sketch function for map layers and optimized useEffect hooks.
web/src/components/molecules/Common/MultiValueField/MultiValueGeometry/index.tsx Added error handling for item deletion in handleInputDelete, updated dependency array to include errorDelete.
web/src/components/molecules/Schema/FieldModal/hooks.ts Introduced utility functions for managing default values, updated useEffect for handling defaultValue, modified handleMultipleChange, added handleValuesChange for tracking form changes, and refined logic for enabling/disabling the submit button.
web/src/components/molecules/Schema/FieldModal/index.tsx Added onValuesChange prop to Form component to enhance interactivity, passing handleValuesChange function for dynamic value handling.
web/src/components/molecules/Schema/types.ts Updated tags property in FieldTypePropertyInput and FormTypes to use Tag[], modified supportedTypes to accept `ObjectSupportedType[]

Possibly related PRs

  • fix(web): add some missing styling #1257: The changes in the FieldModal component in the main PR involve the addition of the onValuesChange prop, which enhances form interactivity, while the retrieved PR also modifies the FieldModal component, focusing on styling improvements. Both PRs are related to the same component, indicating potential overlapping areas of functionality and user experience enhancements.

Suggested reviewers

  • nourbalaha

Poem

🐇 In the meadow where changes bloom,
Geometry dances, dispelling gloom.
Errors handled with a gentle touch,
Forms now lively, they mean so much.
With tags aligned, our code's a delight,
Hop along, dear friends, in coding's light! 🌼


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

@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

🧹 Outside diff range and nitpick comments (3)
web/src/components/molecules/Common/MultiValueField/MultiValueGeometry/index.tsx (1)

Line range hint 28-33: Consider memoizing the handleInput function

While the current changes look good, there's an opportunity to improve the component's performance. The handleInput function is recreated on every render because its dependency array includes value. Consider memoizing this function using useCallback and including only onChange in its dependency array. You can then use the functional update form of onChange to ensure you're always working with the latest value.

Here's a suggested refactor:

const handleInput = useCallback(
  (e: string, id: number) => {
    onChange?.(prevValue => prevValue?.map((valueItem, index) => (index === id ? e : valueItem)));
  },
  [onChange]
);

This change would reduce unnecessary re-creations of the handleInput function, potentially improving performance in scenarios with frequent re-renders.

web/src/components/molecules/Schema/FieldModal/index.tsx (2)

131-131: LGTM! Consider adding a comment for clarity.

The addition of handleValuesChange and onValuesChange prop to the Form component enhances the form's interactivity, allowing it to respond to user input in real-time. This change aligns well with the PR objective of toggling the "ok" button based on the value being updated.

Consider adding a brief comment above the Form component to explain the purpose of onValuesChange, which could help other developers understand its role in toggling the "ok" button:

// Handle form value changes to toggle the "ok" button state
<Form
  form={form}
  layout="vertical"
  initialValues={initialValues}
  requiredMark={requiredMark}
  onValuesChange={handleValuesChange}>

Also applies to: 180-185


Line range hint 1-424: Overall, the changes look good. Consider adding unit tests.

The changes to the FieldModal component are minimal and focused on enhancing the form's interactivity. They are well-integrated and don't introduce any obvious issues. The component's overall structure and logic remain intact.

To ensure the new functionality works as expected, consider adding unit tests for the handleValuesChange function and its integration with the form. This will help maintain the reliability of the component as it evolves. Would you like assistance in creating these unit tests?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between cde9840 and c53db71.

📒 Files selected for processing (5)
  • web/src/components/molecules/Common/Form/GeometryItem/index.tsx (1 hunks)
  • web/src/components/molecules/Common/MultiValueField/MultiValueGeometry/index.tsx (1 hunks)
  • web/src/components/molecules/Schema/FieldModal/hooks.ts (5 hunks)
  • web/src/components/molecules/Schema/FieldModal/index.tsx (2 hunks)
  • web/src/components/molecules/Schema/types.ts (2 hunks)
🧰 Additional context used
🔇 Additional comments (9)
web/src/components/molecules/Common/MultiValueField/MultiValueGeometry/index.tsx (2)

53-53: LGTM: Enhanced error handling for item deletion

The addition of errorDelete?.(key); improves the component's error handling capabilities. It notifies about item deletions, which can be useful for parent components to react to these events.


55-55: LGTM: Correct update to useCallback dependencies

The addition of errorDelete to the dependency array of useCallback is correct and necessary. This ensures that the handleInputDelete function always has the latest version of the errorDelete callback, preventing issues with stale closures.

web/src/components/molecules/Schema/types.ts (3)

103-103: Approved: Standardized tags property type

The change from an inline object type to Tag[] for the tags property in FieldTypePropertyInput is a good improvement. It enhances type consistency and leverages the existing Tag type definition, which will make the code more maintainable and less prone to errors.


165-165: Approved: Consistent use of Tag type

The modification of the tags property in FormTypes to use Tag[] is consistent with the earlier change and further improves type consistency across the codebase. This change will help maintain a uniform structure for tag-related data.


Line range hint 1-170: Summary: Improved type definitions with minor suggestion

Overall, the changes in this file significantly improve type safety and consistency, particularly in the handling of tags and supported types. These improvements align well with the PR objectives of enhancing field updates and validations.

Key improvements:

  1. Standardized use of the Tag type for better consistency.
  2. More specific typing for supportedTypes to ensure only valid types are used.

There's one minor suggestion to consider:

  • Ensure EditorSupportedType is used as an array type in the supportedTypes property of FormTypes.

These changes will contribute to a more robust and maintainable codebase.

web/src/components/molecules/Schema/FieldModal/hooks.ts (2)

243-243: Optimize validation frequency in useEffect

The useEffect hook triggers form.validateFields() on every change to values, which may lead to performance issues, especially with larger forms. Consider debouncing the validation or specifying more granular dependencies to reduce unnecessary validations.

[performance]

Suggested approach:

  • Implement a debounce mechanism using lodash.debounce or similar.
import { useCallback, useEffect, useMemo, useState, useRef } from "react";
+ import debounce from "lodash/debounce";
...
- useEffect(() => {
+ const validateForm = useCallback(
+   debounce(() => {
      if (form.getFieldValue("title") && form.getFieldValue("key")) {
        if (form.getFieldValue("supportedTypes")?.length === 0) {
          setButtonDisabled(true);
        } else {
          form
            .validateFields()
            .then(() => setButtonDisabled(changedKeys.current.size === 0))
            .catch(() => setButtonDisabled(true));
        }
      } else {
        setButtonDisabled(true);
      }
+   }, 300),
+   [form, changedKeys],
+ );
+
+ useEffect(() => {
+   validateForm();
  }, [form, values]);

255-260: Ensure reliable sorting for arrays of non-primitive elements

The current sorting of arrays in handleValuesChange assumes that the arrays contain primitive values. If the arrays contain objects or non-primitive elements, the default sort() method may not function as intended. Provide a compare function to sort() for accurate sorting of complex elements.

Example:

if (Array.isArray(changedValue)) {
-   changedValue = [...changedValue].sort();
+   changedValue = [...changedValue].sort((a, b) => /* custom compare function */);
}
if (Array.isArray(defaultValue)) {
-   defaultValue = [...defaultValue].sort();
+   defaultValue = [...defaultValue].sort((a, b) => /* custom compare function */);
}
web/src/components/molecules/Common/Form/GeometryItem/index.tsx (2)

228-228: Ensure proper error state reset after successful validation

After a successful validation and type check, handleErrorDelete(); is called followed by a return;. Please verify that this correctly resets any existing error states and that no additional error handling is required beyond this point.


233-233: Potential redundant error handling

In the catch block, handleErrorAdd(); is invoked to handle JSON parsing errors. With the proposed change to call handleErrorAdd(); directly when validation fails, ensure that this does not result in duplicate error handling for the same error condition.

@caichi-t caichi-t enabled auto-merge (squash) October 17, 2024 04:57
@nourbalaha nourbalaha self-requested a review October 17, 2024 05:01
@caichi-t caichi-t merged commit bd13729 into main Oct 17, 2024
15 checks passed
@caichi-t caichi-t deleted the fix-web/toggle-save-button branch October 17, 2024 05:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants