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): change detection logic of schema setting #1334

Merged
merged 3 commits into from
Dec 5, 2024

Conversation

caichi-t
Copy link
Contributor

@caichi-t caichi-t commented Dec 4, 2024

Overview

This PR fixes the change detection logic of schema setting.
This fix was added because the change was not detected when the order of multiple default values or options was reordered.

Summary by CodeRabbit

  • New Features

    • Enhanced validation logic for input fields to check for empty and duplicated values.
    • Improved handling of form state based on selected field types when the modal opens.
  • Bug Fixes

    • Refined logic for sorting values in the supportedTypes field to ensure accurate behavior.
  • Improvements

    • Enhanced type safety for value changes in the FieldModal component.
    • Updated submission handling for better structure of values before submission.

@caichi-t caichi-t requested a review from nourbalaha as a code owner December 4, 2024 08:00
Copy link

coderabbitai bot commented Dec 4, 2024

Walkthrough

The pull request modifies the FieldModal component's hooks to enhance type safety and validation logic. Key changes include explicit typing for the changedValues parameter, refined sorting logic for the supportedTypes field, and adjustments to the handleSubmit function. Additionally, new validation functions for empty and duplicated values have been introduced, enhancing error tracking. The useEffect hooks have been updated to reset specific fields based on the selected field type when the modal opens, improving overall control flow and error handling.

Changes

File Path Change Summary
web/src/components/molecules/Schema/FieldModal/hooks.ts - Updated handleValuesChange to explicitly type changedValues as [keyof FormTypes, unknown].
- Refined sorting logic for supportedTypes field.
- Modified handleSubmit to directly assign typeProperty from typePropertyGet.
- Adjusted useEffect to reset specific fields based on selected type.
- Introduced emptyValidator and duplicatedValidator for enhanced validation logic.
- Updated errorIndexes state to track errors comprehensively.

Possibly related PRs

Suggested reviewers

  • nourbalaha

Poem

🐰 In the modal's gentle sway,
Fields now dance in a new way.
With types defined and values clear,
Validation sings, no room for fear.
A hop, a skip, through code we glide,
In this field, our joys reside! 🌼


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.

@github-actions github-actions bot added the web label Dec 4, 2024
Copy link

netlify bot commented Dec 4, 2024

Deploy Preview for reearth-cms ready!

Name Link
🔨 Latest commit af01d11
🔍 Latest deploy log https://app.netlify.com/sites/reearth-cms/deploys/6751106a37b3da0008989216
😎 Deploy Preview https://deploy-preview-1334--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.

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

🧹 Outside diff range and nitpick comments (2)
web/src/components/molecules/Schema/FieldModal/hooks.ts (2)

260-263: Consider extending array comparison logic to other array fields

Good job on fixing the change detection for supportedTypes array reordering! However, to prevent similar issues, consider:

  1. Applying the same sorting logic to other array fields that might have order-independent values
  2. Using non-mutating sort operations to avoid potential side effects
- if (key === "supportedTypes" && Array.isArray(value) && Array.isArray(defaultValue)) {
-   changedValue = [...value].sort();
-   defaultValue = [...defaultValue].sort();
+ // Add more array fields that should ignore order
+ const orderIndependentFields = ["supportedTypes", "values", "tags"];
+ if (orderIndependentFields.includes(key) && Array.isArray(value) && Array.isArray(defaultValue)) {
+   changedValue = [...value].slice().sort();
+   defaultValue = [...defaultValue].slice().sort();

Line range hint 417-456: Enhance validation functions with type safety and performance improvements

The validation logic is well-structured but could be enhanced:

  1. Add explicit type annotations for better type safety
  2. Simplify empty value checks
  3. Optimize duplicate detection using Set
- const emptyValidator = useCallback(async (values?: string[]) => {
+ const emptyValidator = useCallback(async (values?: readonly string[]) => {
   if (values) {
-    const indexes = values
-      .map((value: string, index: number) => value.length === 0 && index)
-      .filter(value => typeof value === "number");
+    const indexes = values
+      .map((value, index) => (!value.trim() ? index : -1))
+      .filter(index => index !== -1);
     setEmptyIndexes(indexes);
     if (indexes.length) {
       return Promise.reject();
     }
   }
 }, []);

- const duplicatedValidator = useCallback(async (values?: string[]) => {
+ const duplicatedValidator = useCallback(async (values?: readonly string[]) => {
   if (values) {
+    const seen = new Set<string>();
     const indexes = values
-      .map((value: string, selfIndex: number) => {
-        if (!value) return;
-        const index = values.findIndex(v => v === value);
-        return index < selfIndex && selfIndex;
+      .map((value, index) => {
+        if (!value.trim()) return -1;
+        return seen.has(value) ? index : (seen.add(value), -1);
       })
-      .filter(value => typeof value === "number");
+      .filter(index => index !== -1);
     setDuplicatedIndexes(indexes);
     if (indexes.length) {
       return Promise.reject();
     }
   }
 }, []);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between eeca1e8 and a295bdc.

📒 Files selected for processing (1)
  • web/src/components/molecules/Schema/FieldModal/hooks.ts (1 hunks)

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

🧹 Outside diff range and nitpick comments (1)
web/src/components/molecules/Schema/FieldModal/hooks.ts (1)

Line range hint 442-476: Consider enhancing validation with specific error messages and memoization.

The validation functions are well-structured but could be improved:

  1. Add specific error messages for better UX
  2. Memoize validation functions to prevent unnecessary recalculations

Apply this diff to enhance the validation:

-  const emptyValidator = useCallback(async (values?: string[]) => {
+  const emptyValidator = useCallback(async (values?: string[], fieldName?: string) => {
     if (values) {
       const indexes = values
         .map((value: string, index: number) => value.length === 0 && index)
         .filter(value => typeof value === "number");
       setEmptyIndexes(indexes);
       if (indexes.length) {
-        return Promise.reject();
+        return Promise.reject(`${fieldName || 'Values'} cannot be empty`);
       }
     }
-  }, []);
+  }, []); // Already memoized correctly

-  const duplicatedValidator = useCallback(async (values?: string[]) => {
+  const duplicatedValidator = useCallback(async (values?: string[], fieldName?: string) => {
     if (values) {
       const indexes = values
         .map((value: string, selfIndex: number) => {
           if (!value) return;
           const index = values.findIndex(v => v === value);
           return index < selfIndex && selfIndex;
         })
         .filter(value => typeof value === "number");
       setDuplicatedIndexes(indexes);
       if (indexes.length) {
-        return Promise.reject();
+        return Promise.reject(`${fieldName || 'Values'} contain duplicates`);
       }
     }
-  }, []);
+  }, []); // Already memoized correctly

   const errorIndexes = useMemo(
     () => new Set([...emptyIndexes, ...duplicatedIndexes]),
     [duplicatedIndexes, emptyIndexes],
   );
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a295bdc and af01d11.

📒 Files selected for processing (1)
  • web/src/components/molecules/Schema/FieldModal/hooks.ts (1 hunks)
🔇 Additional comments (2)
web/src/components/molecules/Schema/FieldModal/hooks.ts (2)

270-272: 🛠️ Refactor suggestion

Enhance type safety and error handling.

The current implementation could benefit from additional type safety and error handling:

  1. Add a guard clause for empty changedValues
  2. Use optional chaining for safer defaultValue access

Apply this diff to improve the code:

-    const [key, value] = Object.entries(changedValues)[0] as [keyof FormTypes, unknown];
-    let changedValue = value;
-    let defaultValue = defaultValueRef.current?.[key];
+    const entries = Object.entries(changedValues);
+    if (entries.length === 0) return;
+    
+    const [key, value] = entries[0] as [keyof FormTypes, unknown];
+    let changedValue = value;
+    let defaultValue = defaultValueRef.current?.[key];

273-276: LGTM: Array sorting ensures consistent change detection.

The added sorting logic for supportedTypes arrays ensures that reordering of values is not incorrectly detected as a change. This fixes the original issue mentioned in the PR description.

Let's verify the change detection behavior:

✅ Verification successful

Let me analyze the results and generate the final response.

Array sorting for supportedTypes is correctly implemented and no other similar cases need attention

The codebase scan reveals that:

  • The supportedTypes array comparison is unique to the field modal component
  • Other array comparisons in the codebase already handle array ordering properly:
    • In Request/Details/SidebarWrapper.tsx, reviewer arrays are sorted before comparison
    • Other array comparisons use JSON.stringify with emptyConvert utility for consistent comparison

The sorting implementation is appropriate for this specific use case and doesn't need to be replicated elsewhere in the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for other array-type fields that might need similar sorting
# Look for field type definitions and array comparisons

# Search for array type definitions
rg -A 2 "type.*=.*\[\]" 

# Search for array comparisons
rg "JSON\.stringify\(.*\)"

Length of output: 4476

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