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): handling initial values of multiple field #1345

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

caichi-t
Copy link
Contributor

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

Overview

  • This PR fixes handling initial values of multiple field.

What I've done

  • Fixing type definitions

Capture

The saving button behaved incorrectly when creating a new item with multiple field.

2024-12-17.12.15.46.mov

Summary by CodeRabbit

  • New Features

    • Introduced new type definitions: FormValue and FormGroupValue for enhanced data structure handling.
  • Bug Fixes

    • Updated TypeProperty to allow null values for several properties, improving data handling flexibility.
  • Improvements

    • Enhanced form value handling and item creation/update processes in various components.
    • Updated dateConvert function to accept null values, improving robustness.

@caichi-t caichi-t requested a review from nourbalaha as a code owner December 18, 2024 06:26
Copy link

coderabbitai bot commented Dec 18, 2024

Walkthrough

This pull request introduces new type definitions and modifications across several TypeScript files in the web components. The changes primarily focus on enhancing type safety and flexibility for form handling, particularly in content management. New types FormValue and FormGroupValue are introduced to provide more robust type definitions for form-related data. The modifications allow for more flexible value handling, including support for null values and improved type checking in various components related to project content and form management.

Changes

File Change Summary
web/src/components/molecules/Content/types.ts Added new types FormValue and FormGroupValue to support complex form value handling
web/src/components/molecules/Schema/types.ts Updated TypeProperty type to allow null values for defaultValue, assetDefaultValue, selectDefaultValue, and integerDefaultValue
web/src/components/organisms/Project/Content/ContentDetails/hooks.ts Imported new types, updated state initialization and value handling with new FormValue and FormGroupValue types
web/src/components/organisms/Project/Content/ContentDetails/utils.ts Modified dateConvert function to accept null values

Possibly related PRs

Suggested labels

web

Suggested reviewers

  • nourbalaha

Poem

🐰 Hop, hop, through types so bright,
Null values dancing left and right,
Forms now flexible and free,
Type safety, a rabbit's glee!
Code leaps forward with delight! 🌈

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.


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.

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

netlify bot commented Dec 18, 2024

Deploy Preview for reearth-cms ready!

Name Link
🔨 Latest commit 2e0896e
🔍 Latest deploy log https://app.netlify.com/sites/reearth-cms/deploys/67626b29a4d989000894b2a7
😎 Deploy Preview https://deploy-preview-1345--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

🧹 Nitpick comments (6)
web/src/components/molecules/Content/types.ts (1)

21-21: Consider adding JSDoc comments for better documentation.

While the type definition is clear, adding JSDoc comments would help other developers understand the purpose and usage of these types, especially for complex form structures.

+/** Represents a group of form values, where each key maps to a single form value or array of values */
 export type FormGroupValue = Record<string, FormValue>;
web/src/components/organisms/Project/Content/ContentDetails/hooks.ts (5)

7-8: LGTM! Well-structured type handling with a minor suggestion.

The valueGet function implementation is now more type-safe and handles multiple fields correctly. Consider extracting the field type mapping to a separate constant for better maintainability.

+const FIELD_TYPE_DEFAULT_VALUE_MAP = {
+  Select: (field: Field) => field.typeProperty?.selectDefaultValue,
+  Integer: (field: Field) => field.typeProperty?.integerDefaultValue,
+  Asset: (field: Field) => field.typeProperty?.assetDefaultValue,
+  Date: (field: Field) => dateConvert(field.typeProperty?.defaultValue),
+  default: (field: Field) => field.typeProperty?.defaultValue,
+} as const;

 const valueGet = useCallback((field: Field) => {
   let result: FormValue;
-  switch (field.type) {
-    case "Select":
-      result = field.typeProperty?.selectDefaultValue;
-      break;
-    case "Integer":
-      result = field.typeProperty?.integerDefaultValue;
-      break;
-    case "Asset":
-      result = field.typeProperty?.assetDefaultValue;
-      break;
-    case "Date":
-      result = dateConvert(field.typeProperty?.defaultValue);
-      break;
-    default:
-      result = field.typeProperty?.defaultValue;
-  }
+  const getDefaultValue = FIELD_TYPE_DEFAULT_VALUE_MAP[field.type as keyof typeof FIELD_TYPE_DEFAULT_VALUE_MAP] 
+    ?? FIELD_TYPE_DEFAULT_VALUE_MAP.default;
+  result = getDefaultValue(field);
   if (field.multiple && !result) {
     result = [];
   }
   return result;
 }, []);

Also applies to: 371-391


408-410: Consider creating a type alias for form values record.

The explicit type definition improves type safety, but readability could be enhanced.

+type FormValuesRecord = Record<string, FormValue | FormGroupValue>;

-const [initialFormValues, setInitialFormValues] = useState<
-  Record<string, FormValue | FormGroupValue>
->({});
+const [initialFormValues, setInitialFormValues] = useState<FormValuesRecord>({});

415-421: Consider extracting the nested group values update function.

The groupInitialValuesUpdate function could be moved outside for better readability and potential reuse.

+const updateGroupInitialValues = (
+  group: Group,
+  itemGroupId: string,
+  initialValues: Record<string, FormValue | FormGroupValue>,
+  valueGetter: (field: Field) => FormValue
+) => {
+  group?.schema?.fields?.forEach(field => {
+    initialValues[field.id] = {
+      ...(initialValues[field.id] as FormGroupValue),
+      ...{ [itemGroupId]: valueGetter(field) },
+    };
+  });
+};

 const handleInitialValuesSet = async () => {
   const initialValues: Record<string, FormValue | FormGroupValue> = {};
-  const groupInitialValuesUpdate = (group: Group, itemGroupId: string) => {
-    group?.schema?.fields?.forEach(field => {
-      initialValues[field.id] = {
-        ...(initialValues[field.id] as FormGroupValue),
-        ...{ [itemGroupId]: valueGet(field) },
-      };
-    });
-  };
+  const updateGroup = (group: Group, itemGroupId: string) => 
+    updateGroupInitialValues(group, itemGroupId, initialValues, valueGet);

Line range hint 562-568: Improve type handling and readability in reference check.

The function could be more robust with early returns and explicit type handling.

 const handleCheckItemReference = useCallback(
   async (itemId: string, correspondingFieldId: string, groupId?: string) => {
+    if (!itemId || !correspondingFieldId) return false;
+
     const initialValue = groupId
-      ? (initialFormValues[groupId] as FormGroupValue)[correspondingFieldId]
-      : initialFormValues[correspondingFieldId];
+      ? (initialFormValues[groupId] as FormGroupValue | undefined)?.[correspondingFieldId]
+      : initialFormValues[correspondingFieldId] ?? null;

-    if (initialValue === itemId) {
-      return false;
-    }
+    if (initialValue === itemId) return false;

Line range hint 1-653: Consider splitting this large hook into smaller, focused custom hooks.

This file has grown quite large and handles multiple concerns. Consider breaking it down into smaller, more focused custom hooks:

  • useFormValues (form state and initialization)
  • useItemOperations (create, update)
  • useRequestOperations (request-related functionality)
  • useNavigationHandlers (navigation-related callbacks)

This would improve maintainability, testability, and reusability.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 07186df and 2e0896e.

📒 Files selected for processing (4)
  • web/src/components/molecules/Content/types.ts (1 hunks)
  • web/src/components/molecules/Schema/types.ts (1 hunks)
  • web/src/components/organisms/Project/Content/ContentDetails/hooks.ts (5 hunks)
  • web/src/components/organisms/Project/Content/ContentDetails/utils.ts (1 hunks)
🔇 Additional comments (3)
web/src/components/molecules/Content/types.ts (1)

9-19: LGTM! Comprehensive type definition for form values.

The FormValue type properly handles all possible form field values, including arrays for multiple fields and explicit null/undefined cases. The special handling for date fields with ("" | Dayjs)[] is particularly well thought out.

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

84-84: LGTM! Consistent null handling across field types.

The updates to TypeProperty properly align with the new FormValue type and support multiple field scenarios. The addition of array support for assetDefaultValue and integerDefaultValue is particularly valuable for handling multiple fields.

However, let's verify the impact of these changes on existing code:

Also applies to: 86-88

✅ Verification successful

Based on the search results, I can see that the changes to defaultValue and related properties in Schema/types.ts are consistently used throughout the codebase in:

  1. GraphQL type definitions that define the schema field types and their properties
  2. Form handling components that manage field default values
  3. Field rendering components that display the values

The changes are properly aligned with the type system and there are no inconsistencies in how these properties are used. The null support is consistently handled across all field types and the array support matches the multiple field scenarios.

LGTM! The changes are properly integrated across the codebase.

The type changes are well-aligned with both the GraphQL schema and the UI components that consume these types. The null and array support is consistently implemented throughout the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for any existing usage of these properties that might be affected
rg -A 2 "defaultValue|assetDefaultValue|selectDefaultValue|integerDefaultValue" --type ts

Length of output: 70039

web/src/components/organisms/Project/Content/ContentDetails/utils.ts (1)

Line range hint 5-11: LGTM! Proper null handling in date conversion.

The updated signature properly handles null values while maintaining existing functionality for arrays and single values. The function correctly returns empty string for null/undefined cases, which is consistent with the form value handling requirements.

Let's verify the usage of this function across the codebase:

✅ Verification successful

Let's analyze the usage of dateConvert further by checking the type definitions and imports:


The dateConvert function update is safe and properly used across the codebase

The verification shows that:

  • The function is imported and used in two locations: RequestDetails/utils.ts and ContentDetails/hooks.ts
  • All usages are for date type fields and properly handle the nullable values
  • The ItemValue type supports both single values and arrays, which aligns with the function's implementation
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for dateConvert usage to ensure compatibility
rg -A 3 "dateConvert\(" --type ts

Length of output: 2966


Script:

#!/bin/bash
# Check imports of dateConvert
rg "import.*dateConvert" --type ts

# Check ItemValue type definition
rg "type ItemValue" --type ts -A 3

Length of output: 673

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.

1 participant