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): item could not be saved if the multiple value had an empty value #1321

Merged
merged 3 commits into from
Dec 2, 2024

Conversation

caichi-t
Copy link
Contributor

@caichi-t caichi-t commented Nov 25, 2024

Overview

This PR fixes a bug that an item could not be saved if the multiple value had an empty value.

What I've done

  • Converting empty characters in multiple values to undefined

Screenshot

image

Summary by CodeRabbit

  • New Features

    • Enhanced handling of form values and metadata in the ContentForm component.
    • Added an asynchronous function to retrieve and format metadata fields based on validated values.
  • Bug Fixes

    • Improved logic to return undefined for empty string values in form processing.
  • Refactor

    • Streamlined the submission process to utilize a new method for fetching metadata fields.
    • Introduced memoization for field mappings to optimize performance.
  • Tests

    • Added new end-to-end test cases for editing asset fields, including asset creation, file uploads, and UI interactions for validation.

@caichi-t caichi-t requested a review from nourbalaha as a code owner November 25, 2024 03:44
Copy link

coderabbitai bot commented Nov 25, 2024

Walkthrough

The changes in this pull request primarily focus on the ContentForm component within index.tsx. Key modifications include the removal of the FieldType import, updates to the logic for handling form values, and the introduction of new memoized variables for field mappings. A new function, metaFieldsGet, has been added to manage the retrieval of metadata fields asynchronously. The handleSubmit and handleMetaUpdate functions have been revised to use this new function, enhancing the management of metadata and form values without altering the overall structure of the component.

Changes

File Path Change Summary
web/src/components/molecules/Content/Form/index.tsx Removed import of FieldType, added modelFields and metaFieldsMap variables, introduced metaFieldsGet function, and updated handleSubmit and handleMetaUpdate functions.
web/e2e/project/item/fields/asset.spec.ts Added new test case for editing asset fields, expanded asset upload logic, and enhanced UI interaction checks.

Possibly related PRs

Suggested reviewers

  • nourbalaha

🐇 In the meadow, changes bloom,
A form transformed, dispelling gloom.
Fields mapped and values clear,
Metadata dances, drawing near.
With every submit, a new delight,
In our code, the future's bright! 🌼


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 Nov 25, 2024
Copy link

netlify bot commented Nov 25, 2024

Deploy Preview for reearth-cms ready!

Name Link
🔨 Latest commit 24a4df4
🔍 Latest deploy log https://app.netlify.com/sites/reearth-cms/deploys/674d1bd5bd92440008448adf
😎 Deploy Preview https://deploy-preview-1321--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/Content/Form/index.tsx (2)

360-374: Consider enhancing error handling in metaFieldsGet

While the implementation is clean and efficient, consider adding explicit error handling for validation failures and logging for debugging purposes.

 const metaFieldsGet = useCallback(async () => {
   const result: ItemField[] = [];
-  const metaValues = await metaForm.validateFields();
+  try {
+    const metaValues = await metaForm.validateFields();
+    for (const [key, value] of Object.entries(metaValues)) {
+      const metaField = metaFieldsMap.get(key);
+      if (metaField) {
+        result.push({
+          value: inputValueGet(value as ItemValue, metaField.multiple),
+          schemaFieldId: key,
+          type: metaField.type,
+        });
+      }
+    }
+    return result;
+  } catch (error) {
+    console.error('Meta fields validation failed:', error);
+    throw error;
+  }
-  for (const [key, value] of Object.entries(metaValues)) {
-    const metaField = metaFieldsMap.get(key);
-    if (metaField) {
-      result.push({
-        value: inputValueGet(value as ItemValue, metaField.multiple),
-        schemaFieldId: key,
-        type: metaField.type,
-      });
-    }
-  }
-  return result;
 }, [inputValueGet, metaFieldsMap, metaForm]);

431-445: Improve error handling in handleSubmit

The error handling in handleSubmit silently catches all errors. Consider logging the error and potentially showing a user-friendly notification.

-      changedKeys.current.clear();
-    } catch (_) {
+      changedKeys.current.clear();
+    } catch (error) {
+      console.error('Failed to submit form:', error);
+      Notification.error({
+        message: t('Failed to save'),
+        description: t('An error occurred while saving the item. Please try again.'),
+      });
       setIsDisabled(false);
     }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c817481 and 54a9ef8.

📒 Files selected for processing (1)
  • web/src/components/molecules/Content/Form/index.tsx (4 hunks)
🔇 Additional comments (2)
web/src/components/molecules/Content/Form/index.tsx (2)

339-341: LGTM: Empty value handling implementation looks good!

The implementation correctly converts empty strings to undefined for multiple values while preserving the handling of dayjs objects. This change effectively addresses the issue where items couldn't be saved if multiple values had empty values.


350-358: LGTM: Efficient field mapping implementation!

The introduction of memoized Maps for both model and meta fields is a great optimization. Using Map provides O(1) lookup complexity, which is particularly beneficial when dealing with large schemas. The memoization dependencies are correctly set to rebuild only when the field arrays change.

@caichi-t caichi-t enabled auto-merge (squash) December 2, 2024 02:30
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 (3)
web/src/components/molecules/Content/Form/index.tsx (3)

350-358: Consider adding null checks for model fields

While the memoization implementation is good for performance, consider adding null checks to handle cases where model might be undefined:

  const modelFields = useMemo(
-   () => new Map((model?.schema.fields || []).map(field => [field.id, field])),
+   () => new Map(model?.schema?.fields?.map(field => [field.id, field]) ?? []),
    [model?.schema.fields],
  );

  const metaFieldsMap = useMemo(
-   () => new Map((model?.metadataSchema.fields || []).map(field => [field.id, field])),
+   () => new Map(model?.metadataSchema?.fields?.map(field => [field.id, field]) ?? []),
    [model?.metadataSchema.fields],
  );

360-374: Consider adding error handling for validation failures

The metaFieldsGet function correctly handles metadata field transformation, but consider adding error handling for validation failures:

  const metaFieldsGet = useCallback(async () => {
    const result: ItemField[] = [];
-   const metaValues = await metaForm.validateFields();
+   try {
+     const metaValues = await metaForm.validateFields();
+     for (const [key, value] of Object.entries(metaValues)) {
+       const metaField = metaFieldsMap.get(key);
+       if (metaField) {
+         result.push({
+           value: inputValueGet(value as ItemValue, metaField.multiple),
+           schemaFieldId: key,
+           type: metaField.type,
+         });
+       }
+     }
+     return result;
+   } catch (error) {
+     console.error('Meta fields validation failed:', error);
+     throw error;
+   }
-   for (const [key, value] of Object.entries(metaValues)) {
-     const metaField = metaFieldsMap.get(key);
-     if (metaField) {
-       result.push({
-         value: inputValueGet(value as ItemValue, metaField.multiple),
-         schemaFieldId: key,
-         type: metaField.type,
-       });
-     }
-   }
-   return result;
  }, [inputValueGet, metaFieldsMap, metaForm]);

450-458: Consider adding user feedback for metadata update failures

While the error handling catches validation failures, consider adding user feedback:

  const handleMetaUpdate = useCallback(async () => {
    if (!itemId) return;
    try {
      const metaFields = await metaFieldsGet();
      await onMetaItemUpdate({
        metaItemId: item?.metadata?.id,
        metaFields,
      });
    } catch (info) {
-     console.log("Validate Failed:", info);
+     console.error("Metadata validation failed:", info);
+     Notification.error({
+       message: t("Failed to update metadata"),
+       description: t("Please check your input and try again"),
+     });
    }
  }, [itemId, metaFieldsGet, onMetaItemUpdate, item?.metadata?.id]);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 0e3a89a and 24a4df4.

📒 Files selected for processing (1)
  • web/src/components/molecules/Content/Form/index.tsx (4 hunks)
🔇 Additional comments (1)
web/src/components/molecules/Content/Form/index.tsx (1)

339-341: LGTM: Empty string handling for multiple values

The implementation correctly converts empty strings to undefined for multiple values while preserving date objects and other non-empty values. This change directly addresses the issue where items couldn't be saved with empty multiple values.

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