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): warning occurs when re-referring to an item referenced earlier #1264

Merged
merged 4 commits into from
Oct 24, 2024

Conversation

caichi-t
Copy link
Contributor

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

Overview

This PR fixes the bug that the warning occurs when re-referring to an item referenced earlier.
When editing an item with a two-way reference value, the warning occurs if you try to dereference the item and then reference the same item again.

Memo

I fixed the logic to check if the item is referenced to reduce unnecessary queries.

Summary by CodeRabbit

  • New Features

    • Enhanced flexibility in item reference handling with updated function parameters across multiple components.
    • Introduced new optional props in ReferenceFormItem and LinkItemModal for improved data management.
  • Bug Fixes

    • Adjusted internal logic for better clarity and functionality in item reference handling.

Copy link

coderabbitai bot commented Oct 16, 2024

Walkthrough

The changes involve updates to the onCheckItemReference function's signature across various components, allowing it to accept three parameters: itemId, correspondingFieldId, and an optional groupId. Several components, including ReferenceFormItem and LinkItemModal, have had their prop names modified and new optional props introduced. Additionally, the internal logic of the handleCheckItemReference function has been revised to align with the new parameter definitions.

Changes

File Path Change Summary
web/src/components/molecules/Content/Details/index.tsx Updated onCheckItemReference function signature to accept itemId, correspondingFieldId, and optional groupId.
web/src/components/molecules/Content/Form/ReferenceFormItem/index.tsx Renamed correspondingFieldId to fieldId, added optional props: itemGroupId, formItemsData, and correspondingField. Updated onCheckItemReference function signature accordingly.
web/src/components/molecules/Content/Form/index.tsx Updated onCheckItemReference function signature to accept itemId, correspondingFieldId, and optional groupId.
web/src/components/molecules/Content/LinkItemModal/index.tsx Renamed correspondingFieldId to fieldId, added optional props: itemGroupId and correspondingField. Updated onCheckItemReference function signature accordingly.
web/src/components/organisms/Project/Content/ContentDetails/hooks.ts Adjusted internal logic of handleCheckItemReference to align with updated parameter names and types, now accepting itemId, correspondingFieldId, and optional groupId.

Possibly related PRs

Suggested reviewers

  • nourbalaha

Poem

In the fields where rabbits play,
New changes hop in bright array.
With fields and items, all aligned,
A dance of code, so well-defined.
Let's cheer for props, both old and new,
A joyful leap, for all we do! 🐇✨


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 Oct 16, 2024
Copy link

netlify bot commented Oct 16, 2024

Deploy Preview for reearth-cms ready!

Name Link
🔨 Latest commit 16acb4d
🔍 Latest deploy log https://app.netlify.com/sites/reearth-cms/deploys/6719c2a1acd4d50008d11fbb
😎 Deploy Preview https://deploy-preview-1264--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: 1

🧹 Outside diff range and nitpick comments (14)
web/src/components/molecules/Content/Form/fields/ComplexFieldComponents/ReferenceField.tsx (3)

23-27: Approve changes with a minor suggestion.

The updated onCheckItemReference prop signature is an improvement. It provides more specific parameter names (itemId instead of value) and adds an optional groupId parameter, which aligns with the PR objective of improving item reference handling.

Consider adding JSDoc comments to explain the purpose of each parameter, especially the new groupId. This would enhance code readability and maintainability. For example:

/**
 * Checks if an item can be referenced.
 * @param itemId - The ID of the item to be referenced.
 * @param correspondingFieldId - The ID of the corresponding field.
 * @param groupId - Optional. The ID of the group, if applicable.
 * @returns A promise that resolves to a boolean indicating if the item can be referenced.
 */
onCheckItemReference?: (
  itemId: string,
  correspondingFieldId: string,
  groupId?: string
) => Promise<boolean>;

62-75: Approve changes with a suggestion for consistency.

The modifications to the props passed to ReferenceFormItem are appropriate and align well with the updated onCheckItemReference signature. The changes improve the component's flexibility and provide more specific data to the child component.

For consistency, consider reordering the props alphabetically. This can improve readability and make it easier to locate specific props. Here's a suggested order:

<ReferenceFormItem
  correspondingField={field.typeProperty?.correspondingField}
  disabled={disabled}
  fieldId={field.id}
  formItemsData={formItemsData}
  itemGroupId={itemGroupId}
  key={field.id}
  linkItemModalPage={linkItemModalPage}
  linkItemModalPageSize={linkItemModalPageSize}
  linkItemModalTitle={linkItemModalTitle}
  linkItemModalTotalCount={linkItemModalTotalCount}
  linkedItemsModalList={linkedItemsModalList}
  loading={loading}
  modelId={field.typeProperty?.modelId}
  onCheckItemReference={onCheckItemReference}
  onLinkItemTableChange={onLinkItemTableChange}
  onLinkItemTableReload={onLinkItemTableReload}
  onReferenceModelUpdate={onReferenceModelUpdate}
  onSearchTerm={onSearchTerm}
  titleFieldId={field.typeProperty?.schema?.titleFieldId}
/>

This reordering doesn't change the functionality but can make the code more maintainable.


Line range hint 1-83: Summary: Improved item reference handling with consistent changes.

The modifications in this file successfully address the PR objective of improving item reference handling. The changes to both the ReferenceFieldProps type and the ReferenceField component are consistent and well-implemented.

Key improvements:

  1. Updated onCheckItemReference signature for more precise item referencing.
  2. Enhanced ReferenceFormItem props for better flexibility and data passing.

These changes should effectively resolve the warning issue when re-referring to an item referenced earlier, as mentioned in the PR objectives.

To further improve the overall architecture:

  1. Consider creating a custom hook (e.g., useReferenceField) to encapsulate the logic for handling reference fields. This could simplify the ReferenceField component and make it easier to reuse the logic in other parts of the application if needed.
  2. If not already done, ensure that unit tests are updated or added to cover the new functionality, especially the behavior of onCheckItemReference with the new groupId parameter.
web/src/components/molecules/Content/Form/ReferenceFormItem/index.tsx (2)

19-22: LGTM: Props update enhances component flexibility

The changes to the Props type definition, including the rename of correspondingFieldId to fieldId and the addition of new optional props, align well with the PR objectives. These modifications provide more context and flexibility to the component.

Consider adding JSDoc comments for the new props to improve documentation:

/** The ID of the field */
fieldId: string;
/** Optional group ID for the item */
itemGroupId?: string;
/** Optional array of form item data */
formItemsData?: FormItem[];
/** Optional corresponding field information */
correspondingField?: CorrespondingField;

33-37: LGTM: Enhanced onCheckItemReference callback signature

The updated onCheckItemReference callback signature provides more context for the reference check, aligning with the PR objectives. The addition of itemId as the first parameter and the optional groupId allows for more specific and flexible reference checks.

Consider adding a JSDoc comment to explain the purpose and parameters of this callback:

/**
 * Callback to check if an item can be referenced
 * @param itemId - The ID of the item to be referenced
 * @param correspondingFieldId - The ID of the corresponding field
 * @param groupId - Optional group ID for more specific checks
 * @returns A promise that resolves to a boolean indicating if the reference is valid
 */
onCheckItemReference?: (
  itemId: string,
  correspondingFieldId: string,
  groupId?: string
) => Promise<boolean>;
web/src/components/molecules/Content/Form/fields/ComplexFieldComponents/GroupField.tsx (1)

51-55: LGTM! Consider adding JSDoc comments for clarity.

The updated onCheckItemReference function signature improves specificity and aligns with the PR objectives. The addition of the optional groupId parameter allows for more contextual reference checking, which should help address the warning issue mentioned in the PR summary.

Consider adding JSDoc comments to clarify the purpose of each parameter, especially the new groupId. This would enhance code readability and maintainability. For example:

/**
 * Checks if an item can be referenced.
 * @param itemId - The ID of the item to be referenced.
 * @param correspondingFieldId - The ID of the corresponding field.
 * @param groupId - Optional. The ID of the group if the item is within a group context.
 * @returns A promise that resolves to a boolean indicating if the item can be referenced.
 */
onCheckItemReference?: (
  itemId: string,
  correspondingFieldId: string,
  groupId?: string
) => Promise<boolean>;
web/src/components/molecules/Common/MultiValueField/MultiValueGroup/index.tsx (1)

62-66: LGTM! Consider minor improvements for clarity.

The updated onCheckItemReference prop signature is a good improvement, making it more flexible and descriptive. The changes are backwards-compatible due to the optional groupId parameter.

Suggestions for further enhancement:

  1. Consider renaming the function to be more specific, e.g., onValidateItemReference.
  2. Add JSDoc comments to explain the purpose of each parameter, especially the new groupId.

Example:

/**
 * Validates an item reference.
 * @param itemId - The ID of the item being referenced.
 * @param correspondingFieldId - The ID of the field containing the reference.
 * @param groupId - Optional. The ID of the group if the reference is within a group.
 * @returns A promise that resolves to a boolean indicating if the reference is valid.
 */
onValidateItemReference?: (
  itemId: string,
  correspondingFieldId: string,
  groupId?: string
) => Promise<boolean>;
web/src/components/molecules/Content/Details/index.tsx (1)

102-106: Approved: Function signature update improves clarity and functionality.

The changes to the onCheckItemReference function signature are well-considered:

  1. Renaming value to itemId improves clarity.
  2. Adding the optional groupId parameter allows for more granular reference checks, which aligns with the PR objective of addressing issues with re-referencing items.

Consider adding a brief comment above the function to explain its purpose and the significance of the groupId parameter. This would help other developers understand when and how to use this optional parameter.

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

570-582: Improved item reference checking logic, but consider edge cases

The changes to handleCheckItemReference effectively address the issue of unnecessary warnings when re-referring to an item. The new logic checks against initial values before making an API call, which should improve performance and user experience.

However, consider the following improvements:

  1. Add a null check for initialFormValues[groupId] to handle cases where the group might not exist:
 const initialValue = groupId
-  ? initialFormValues[groupId][correspondingFieldId]
+  ? initialFormValues[groupId]?.[correspondingFieldId]
   : initialFormValues[correspondingFieldId];
  1. Improve error handling for the API call:
 const res = await checkIfItemIsReferenced({
   variables: { itemId, correspondingFieldId },
 });
-return res.data?.isItemReferenced ?? false;
+return res.data?.isItemReferenced || false;
  1. Consider adding a comment explaining the purpose of the initial value check, as it might not be immediately clear to other developers.
web/src/components/molecules/Content/LinkItemModal/index.tsx (5)

Line range hint 75-75: Rename 'hoveredAssetId' to 'hoveredItemId' for consistency.

The state variable is named hoveredAssetId, but the setter function is setHoveredItemId. Renaming hoveredAssetId to hoveredItemId will improve readability and maintain consistent naming conventions.

Apply this diff to rename the variable:

- const [hoveredAssetId, setHoveredItemId] = useState<string>();
+ const [hoveredItemId, setHoveredItemId] = useState<string>();

Also, update all occurrences of hoveredAssetId to hoveredItemId throughout the component:

- (item.id === linkedItem && hoveredAssetId !== item.id) ||
- (item.id !== linkedItem && hoveredAssetId === item.id);
+ (item.id === linkedItem && hoveredItemId !== item.id) ||
+ (item.id !== linkedItem && hoveredItemId === item.id);

Update the dependency array in the useMemo hook:

- [t, linkedItem, hoveredAssetId, handleClick],
+ [t, linkedItem, hoveredItemId, handleClick],

93-100: Handle empty values more explicitly when unlinking an item.

When unlinking an item, handleChange is called with an empty string. Depending on how onChange handles empty strings, this might lead to unintended behavior. Consider passing null to represent the absence of a linked item more clearly.

Apply this diff to adjust the value passed when unlinking:

 if (!link) {
-  handleChange("");
+  handleChange(null);
   return;
 }

Ensure that the onChange prop is updated to accept string | null:

 onChange?: (value: string) => void;
+// Update to:
+onChange?: (value: string | null) => void;

Line range hint 102-115: Add error handling for 'onCheckItemReference' to prevent unhandled promise rejections.

The onCheckItemReference function is awaited without a try-catch block. If it throws an error, the application might crash or behave unexpectedly. Wrap the asynchronous call in a try-catch block to handle potential errors gracefully.

Apply this diff to include error handling:

+ try {
     const isReferenced = await onCheckItemReference(item.id, fieldId, itemGroupId);
     if (isReferenced) {
       confirm({
         title: t("This item has already been referenced"),
         content: t(
           "Do you want to reference this item again? The previous reference will be canceled automatically.",
         ),
         icon: <Icon icon="exclamationCircle" />,
         onOk() {
           handleChange(item.id);
         },
       });
     } else {
       handleChange(item.id);
     }
+ } catch (error) {
+   // Handle error (e.g., display a notification to the user)
+   console.error("Failed to check item reference:", error);
+ }

Line range hint 104-110: Improve the wording in the confirmation dialog for better user understanding.

The current confirmation message may be unclear. Rephrasing it can enhance user experience by providing a clearer explanation of the action.

Apply this diff to update the dialog content:

 confirm({
-  title: t("This item has been referenced"),
+  title: t("This item has already been referenced"),
   content: t(
-    "Are you going to refer to it? The previous reference will be canceled automatically",
+    "Do you want to reference this item again? The previous reference will be canceled automatically.",
   ),
   icon: <Icon icon="exclamationCircle" />,
   onOk() {
     handleChange(item.id);
   },
 });

118-118: Remove unnecessary dependency 'confirm' from 'handleClick' useCallback hook.

The confirm function is sourced from the Modal component and does not change between renders. Removing it from the dependency array can prevent unnecessary re-renders and aligns with best practices.

Apply this diff to update the dependency array:

- [confirm, correspondingField, fieldId, handleChange, itemGroupId, onCheckItemReference, t],
+ [correspondingField, fieldId, handleChange, itemGroupId, onCheckItemReference, t],
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between aec7b82 and cdfa0ab.

📒 Files selected for processing (9)
  • web/src/components/molecules/Common/Form/GroupItem/index.tsx (1 hunks)
  • web/src/components/molecules/Common/MultiValueField/MultiValueGroup/index.tsx (1 hunks)
  • web/src/components/molecules/Content/Details/index.tsx (1 hunks)
  • web/src/components/molecules/Content/Form/ReferenceFormItem/index.tsx (5 hunks)
  • web/src/components/molecules/Content/Form/fields/ComplexFieldComponents/GroupField.tsx (1 hunks)
  • web/src/components/molecules/Content/Form/fields/ComplexFieldComponents/ReferenceField.tsx (2 hunks)
  • web/src/components/molecules/Content/Form/index.tsx (1 hunks)
  • web/src/components/molecules/Content/LinkItemModal/index.tsx (5 hunks)
  • web/src/components/organisms/Project/Content/ContentDetails/hooks.ts (1 hunks)
🧰 Additional context used
🔇 Additional comments (12)
web/src/components/molecules/Content/Form/ReferenceFormItem/index.tsx (4)

9-9: LGTM: New import for CorrespondingField type

The addition of the CorrespondingField type import is consistent with the new correspondingField prop in the component. This change enhances type safety and improves code readability.


46-48: LGTM: Updated props destructuring

The destructuring of the new props fieldId, itemGroupId, and correspondingField is consistent with the changes made to the Props type definition. This ensures that these new props are available for use within the component, enhancing its functionality as intended.


Line range hint 1-156: Summary: Improved ReferenceFormItem component with enhanced flexibility

The changes made to the ReferenceFormItem component align well with the PR objectives to fix the warning when re-referring to an item. The modifications include:

  1. Updated prop definitions with more specific naming and additional optional props.
  2. Enhanced onCheckItemReference callback signature for more precise reference checking.
  3. Consistent usage of new props throughout the component and in the LinkItemModal.

These changes should provide better control over the item referencing process and resolve the reported issue. The code quality is good, with only minor suggestions for documentation improvements.

To ensure the changes are effective:

  1. Verify that the LinkItemModal component correctly utilizes the new props.
  2. Test the component with various scenarios, including re-referring to previously referenced items.
  3. Consider adding unit tests to cover the new functionality and prevent regressions.

123-125: LGTM: Updated LinkItemModal props

The addition of fieldId, itemGroupId, and correspondingField props to the LinkItemModal component is consistent with the earlier changes and aligns with the PR objectives. This allows for more specific handling of item references within the modal.

To ensure that these changes are properly utilized, please verify that the LinkItemModal component is updated to handle these new props correctly. Run the following script to check the LinkItemModal component implementation:

web/src/components/molecules/Content/Form/fields/ComplexFieldComponents/GroupField.tsx (1)

Line range hint 1-180: Overall implementation looks good!

The changes to the onCheckItemReference function signature are consistently applied throughout the GroupField component. Both MultiValueGroup and GroupItem receive the updated prop, ensuring that the new functionality is available regardless of whether the field is multiple or single-valued.

The rest of the component structure remains unchanged, which helps maintain existing functionality while introducing the new feature. This approach minimizes the risk of unintended side effects.

web/src/components/molecules/Common/MultiValueField/MultiValueGroup/index.tsx (1)

62-66: Verify the impact on component usage.

The changes to the onCheckItemReference prop are localized to the type definition. To ensure these changes are properly integrated:

  1. Verify that all usages of the MultiValueGroup component have been updated to pass the correct parameters to onCheckItemReference.
  2. Check if the implementation of onCheckItemReference in parent components has been updated to handle the new groupId parameter.
  3. Update unit tests for the MultiValueGroup component and its parent components to cover the new function signature.

To help with this verification, you can run the following script:

This script will help identify areas that might need updates due to the changes in the onCheckItemReference prop.

web/src/components/molecules/Common/Form/GroupItem/index.tsx (2)

Line range hint 1-268: Review child components for updated usage.

While the GroupItem component's implementation remains unchanged, it's important to verify that child components, especially ReferenceField, are correctly using the updated onCheckItemReference function signature.

To check the implementation in child components:

#!/bin/bash
# Search for the ReferenceField component definition
rg --type-add 'typescript:*.{ts,tsx}' --type typescript 'const ReferenceField.*=.*\{'

# Search for usage of onCheckItemReference within ReferenceField
rg --type-add 'typescript:*.{ts,tsx}' --type typescript 'onCheckItemReference.*\(' -A 5 -B 5

64-68: LGTM! Verify implementation and usage.

The updated onCheckItemReference function signature looks good and aligns with the PR objective. The addition of itemId and optional groupId parameters should allow for more precise and flexible item reference checking.

To ensure this change is properly implemented and used:

  1. Verify that the onCheckItemReference prop is correctly passed down to this component with the new signature.
  2. Check if the function is called with the correct parameters within this component.
  3. Review other components that may use this prop to ensure they've been updated accordingly.

You can use the following script to check for usage of onCheckItemReference:

✅ Verification successful

Verification Successful: All onCheckItemReference usages are updated correctly.

The onCheckItemReference function signature changes have been consistently applied across the codebase. All call sites provide the required parameters (itemId, correspondingFieldId, and optionally groupId).

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for usages of onCheckItemReference in TypeScript and TypeScript React files
rg --type-add 'typescript:*.{ts,tsx}' --type typescript 'onCheckItemReference'

Length of output: 11775


Script:

#!/bin/bash
# Search for calls to onCheckItemReference in TypeScript and TypeScript React files
rg --type-add 'typescript:*.{ts,tsx}' --type typescript 'onCheckItemReference\s*\(' -A 3 -B 3

Length of output: 730

web/src/components/organisms/Project/Content/ContentDetails/hooks.ts (2)

570-582: Summary: Improved item reference checking with minor suggestions

The changes to handleCheckItemReference effectively address the issue of unnecessary warnings when re-referring to an item. The new logic checks against initial values before making an API call, which aligns with the PR objectives and should improve performance and user experience.

Key improvements:

  1. Added check against initial values to prevent unnecessary API calls.
  2. Improved function signature for better clarity and flexibility.

Suggestions for further improvement:

  1. Add null checks for grouped fields.
  2. Enhance error handling for the API call.
  3. Consider adding explanatory comments for the initial value check.
  4. Verify the correct population of initialFormValues for all field types, especially grouped fields.

Overall, the changes are approved with minor suggestions for improvement.


570-582: Verify initialFormValues population for all field types

The changes to handleCheckItemReference now rely on initialFormValues being correctly populated. Please ensure that the useEffect hook that populates initialFormValues (around line 449) correctly handles all field types, especially grouped fields. This is crucial for the new reference checking logic to work as intended.

To verify the correct population of initialFormValues, run the following script:

web/src/components/molecules/Content/Form/index.tsx (1)

120-124: To effectively locate all usages of onCheckItemReference, please run the updated script below using ast-grep:

#!/bin/bash
# Description: Find all occurrences of onCheckItemReference to verify correct usage using ast-grep

# Search for onCheckItemReference usage in TypeScript and TSX files
echo "Searching for onCheckItemReference usage with ast-grep:"
ast-grep --lang typescript --pattern 'onCheckItemReference($_, $_, $_?)' .

If ast-grep is not available or does not yield results, you can use the following script with rg and glob patterns:

#!/bin/bash
# Description: Find all occurrences of onCheckItemReference to verify correct usage using ripgrep with glob patterns

# Search for onCheckItemReference usage in .ts and .tsx files
echo "Searching for onCheckItemReference usage with ripgrep using glob patterns:"
rg 'onCheckItemReference\s*\(' --glob '*.ts' --glob '*.tsx' -A 3
web/src/components/molecules/Content/LinkItemModal/index.tsx (1)

82-88: ⚠️ Potential issue

Add dependency 'visible' to 'handleChange' useCallback hook.

The handleChange function calls onLinkItemModalCancel, which might depend on visible. To ensure the latest value is used, add visible to the dependency array.

Apply this diff to update the dependency array:

 const handleChange = useCallback(
   (value: string) => {
     onChange?.(value);
     onLinkItemModalCancel();
   },
-  [onChange, onLinkItemModalCancel],
+  [onChange, onLinkItemModalCancel, visible],
 );

Likely invalid or redundant comment.

@caichi-t caichi-t enabled auto-merge (squash) October 24, 2024 03:44
@caichi-t caichi-t enabled auto-merge (squash) October 24, 2024 03:44
@caichi-t caichi-t merged commit 20b14e6 into main Oct 24, 2024
15 checks passed
@caichi-t caichi-t deleted the fix-web/ref-detatch branch October 24, 2024 03:48
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: 1

🧹 Outside diff range and nitpick comments (2)
web/src/components/molecules/Content/Form/ReferenceFormItem/index.tsx (1)

46-48: Consider maintaining consistent naming between props and function parameters.

The prop name fieldId is used here while the onCheckItemReference function uses correspondingFieldId. Consider using consistent naming to improve code maintainability.

-  fieldId,
+  correspondingFieldId,
   itemGroupId,
   correspondingField,
web/src/components/organisms/Project/Content/ContentDetails/hooks.ts (1)

570-582: LGTM! Consider adding type safety and null checks.

The changes effectively prevent unnecessary backend queries when re-referring to previously referenced items. However, consider these improvements:

  1. Add type safety for the nested object access
  2. Add null checks when accessing grouped values
 async (itemId: string, correspondingFieldId: string, groupId?: string) => {
-  const initialValue = groupId
-    ? initialFormValues[groupId][correspondingFieldId]
-    : initialFormValues[correspondingFieldId];
+  const initialValue = groupId
+    ? initialFormValues[groupId]?.[correspondingFieldId]
+    : initialFormValues[correspondingFieldId];
   if (initialValue === itemId) {
     return false;
   }
   const res = await checkIfItemIsReferenced({
     variables: { itemId, correspondingFieldId },
   });
   return res.data?.isItemReferenced ?? false;
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between cdfa0ab and 16acb4d.

📒 Files selected for processing (5)
  • web/src/components/molecules/Content/Details/index.tsx (1 hunks)
  • web/src/components/molecules/Content/Form/ReferenceFormItem/index.tsx (5 hunks)
  • web/src/components/molecules/Content/Form/index.tsx (1 hunks)
  • web/src/components/molecules/Content/LinkItemModal/index.tsx (5 hunks)
  • web/src/components/organisms/Project/Content/ContentDetails/hooks.ts (1 hunks)
🔇 Additional comments (10)
web/src/components/molecules/Content/Form/ReferenceFormItem/index.tsx (2)

123-125: LGTM! Props are properly forwarded to LinkItemModal.

The changes correctly pass the necessary context to the LinkItemModal component, enabling proper reference handling with group awareness.


9-9: LGTM! Type changes enhance reference context handling.

The updated Props type and onCheckItemReference signature now properly handle group context, which should help prevent false warnings when re-referring to items.

Let's verify the consistency of these changes across the codebase:

Also applies to: 19-22, 33-37

✅ Verification successful

Let me try a different approach to verify the usage of onCheckItemReference in the codebase.

This should help us understand:

  1. How onCheckItemReference is used across the codebase
  2. Where CorrespondingField type is imported and potentially used with onCheckItemReference

Based on the ripgrep results, I can now generate a final response as we have sufficient information about the usage of onCheckItemReference across the codebase.

The type changes are consistent across the codebase

The search results confirm that all implementations and usages of onCheckItemReference follow the updated signature with the optional groupId parameter:

  • All type definitions consistently show (itemId: string, correspondingFieldId: string, groupId?: string)
  • The function is properly passed down through component hierarchies
  • The implementation in LinkItemModal shows actual usage with groupId parameter

Key files verified:

  • web/src/components/molecules/Content/Form/ReferenceFormItem/index.tsx (the file under review)
  • web/src/components/molecules/Content/Details/index.tsx
  • web/src/components/molecules/Content/LinkItemModal/index.tsx
  • web/src/components/molecules/Common/Form/GroupItem/index.tsx
  • web/src/components/molecules/Content/Form/fields/ComplexFieldComponents/ReferenceField.tsx
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that all implementations of onCheckItemReference follow the new signature

# Search for onCheckItemReference implementations
ast-grep --pattern 'onCheckItemReference = async ($params) => {
  $$$
}'

Length of output: 74


Script:

#!/bin/bash
# Search for onCheckItemReference usage patterns
rg "onCheckItemReference" -A 3

# Also search for any files importing CorrespondingField
rg "import.*CorrespondingField.*from" --type typescript

Length of output: 11209

web/src/components/molecules/Content/LinkItemModal/index.tsx (5)

14-14: LGTM: Import added for new type.

The import is correctly placed and used for the new prop type.


25-27: LGTM: Props type updates align with PR objectives.

The changes improve type safety and flexibility:

  • Renamed field for better clarity
  • Added optional props for enhanced functionality
  • Updated function signature to support the new reference checking logic

Also applies to: 39-43


49-51: LGTM: Props destructuring matches type changes.

The destructuring is correctly updated to match the Props type changes.


81-87: LGTM: Good refactoring to reduce code duplication.

The new handleChange function effectively consolidates the onChange and modal cancellation logic, improving maintainability.


Line range hint 91-117: Consider adding error handling for the reference check.

While the logic flow is improved, consider adding error handling for the onCheckItemReference call to handle potential failures gracefully.

Let's verify the changes:

Suggested improvement:

-      const isReferenced = await onCheckItemReference(item.id, fieldId, itemGroupId);
+      try {
+        const isReferenced = await onCheckItemReference(item.id, fieldId, itemGroupId);
+        if (isReferenced) {
+          confirm({
+            title: t("This item has been referenced"),
+            content: t(
+              "Are you going to refer to it? The previous reference will be canceled automatically",
+            ),
+            icon: <Icon icon="exclamationCircle" />,
+            onOk() {
+              handleChange(item.id);
+            },
+          });
+        } else {
+          handleChange(item.id);
+        }
+      } catch (error) {
+        Modal.error({
+          title: t("Failed to check item reference"),
+          content: t("Please try again later"),
+        });
+      }
web/src/components/molecules/Content/Details/index.tsx (2)

103-107: LGTM! The updated signature enhances reference handling.

The addition of the optional groupId parameter to onCheckItemReference is a well-structured change that:

  • Maintains backward compatibility through the optional parameter
  • Improves type safety with explicit TypeScript types
  • Aligns with the PR objective by providing context-aware reference checking

103-107: Verify consistent implementation across the codebase.

Let's ensure the updated signature is consistently implemented across all related components.

✅ Verification successful

Let me try a different approach to search for the implementations and usages.


Let me check the actual implementation of these components to see if they properly handle the new groupId parameter.


Let me try one final search to check the actual implementations with more context and different patterns.


Based on the search results, I can now provide a final response:

The groupId parameter is consistently implemented across the codebase

The verification shows that:

  1. The type definition in all components (LinkItemModal, Form, ReferenceField) properly includes the optional groupId parameter
  2. The actual implementation in LinkItemModal correctly passes the itemGroupId parameter when calling onCheckItemReference
  3. The function signature maintains backward compatibility by making groupId optional, which ensures existing callers continue to work
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for consistent implementation of onCheckItemReference
# Expected results: All implementations should accept itemId, correspondingFieldId, and optional groupId

# Search for onCheckItemReference implementations
echo "Searching for onCheckItemReference implementations..."
rg -t typescript -t tsx "onCheckItemReference.*=.*\(" --no-heading

# Search for calls to onCheckItemReference
echo -e "\nSearching for onCheckItemReference calls..."
rg -t typescript -t tsx "onCheckItemReference\(" --no-heading

Length of output: 422


Script:

#!/bin/bash
# Search for onCheckItemReference implementations and calls using ripgrep
# Using just .ts and .tsx extensions directly

echo "Searching for onCheckItemReference implementations..."
rg "onCheckItemReference.*=.*\(" -g "*.ts" -g "*.tsx" -A 2

echo -e "\nSearching for onCheckItemReference calls..."
rg "onCheckItemReference\(" -g "*.ts" -g "*.tsx" -A 1

# Also search for the type definition
echo -e "\nSearching for type definitions..."
rg "onCheckItemReference.*:.*" -g "*.ts" -g "*.tsx" -A 2

Length of output: 3043


Script:

#!/bin/bash
# Get more context around the implementations and calls

echo "Checking LinkItemModal implementation..."
rg -A 5 "onCheckItemReference\(.*\)" web/src/components/molecules/Content/LinkItemModal/index.tsx

echo -e "\nChecking Form implementations..."
rg -A 5 "onCheckItemReference\(.*\)" web/src/components/molecules/Content/Form/index.tsx

echo -e "\nChecking ReferenceField implementation..."
rg -A 5 "onCheckItemReference\(.*\)" web/src/components/molecules/Content/Form/fields/ComplexFieldComponents/ReferenceField.tsx

echo -e "\nChecking GroupField implementation..."
rg -A 5 "onCheckItemReference\(.*\)" web/src/components/molecules/Content/Form/fields/ComplexFieldComponents/GroupField.tsx

echo -e "\nChecking ReferenceFormItem implementation..."
rg -A 5 "onCheckItemReference\(.*\)" web/src/components/molecules/Content/Form/ReferenceFormItem/index.tsx

echo -e "\nChecking GroupItem implementation..."
rg -A 5 "onCheckItemReference\(.*\)" web/src/components/molecules/Common/Form/GroupItem/index.tsx

echo -e "\nChecking MultiValueGroup implementation..."
rg -A 5 "onCheckItemReference\(.*\)" web/src/components/molecules/Common/MultiValueField/MultiValueGroup/index.tsx

Length of output: 1733


Script:

#!/bin/bash
# Search for method implementations and prop passing with more context

echo "Checking LinkItemModal with more context..."
rg -B 5 -A 10 "onCheckItemReference.*=.*\(|onCheckItemReference:.*\(|onCheckItemReference\?:.*\(|onCheckItemReference.*\(" web/src/components/molecules/Content/LinkItemModal/index.tsx

echo -e "\nChecking Form component with more context..."
rg -B 5 -A 10 "onCheckItemReference.*=.*\(|onCheckItemReference:.*\(|onCheckItemReference\?:.*\(|onCheckItemReference.*\(" web/src/components/molecules/Content/Form/index.tsx

echo -e "\nChecking ReferenceField with more context..."
rg -B 5 -A 10 "onCheckItemReference.*=.*\(|onCheckItemReference:.*\(|onCheckItemReference\?:.*\(|onCheckItemReference.*\(" web/src/components/molecules/Content/Form/fields/ComplexFieldComponents/ReferenceField.tsx

echo -e "\nChecking prop passing patterns..."
rg -B 2 -A 2 "onCheckItemReference={.*}" -g "*.tsx"

Length of output: 3048

web/src/components/molecules/Content/Form/index.tsx (1)

121-125: LGTM! Function signature improvement enhances reference checking.

The updated onCheckItemReference signature:

  • Uses more descriptive parameter names (valueitemId)
  • Adds optional groupId parameter for group-specific reference checks
  • Aligns with the PR's objective of fixing re-referencing warnings

Let's verify that all callers have been updated to use the new signature:

✅ Verification successful

Let me analyze the search results to verify the function signature changes:

  1. Function type definitions found in:

    • web/src/components/molecules/Content/Details/index.tsx
    • web/src/components/molecules/Content/LinkItemModal/index.tsx
    • web/src/components/molecules/Content/Form/index.tsx
      All show the updated signature with itemId, correspondingFieldId, and optional groupId.
  2. Function calls found in:

    • web/src/components/molecules/Content/LinkItemModal/index.tsx: Uses all three parameters (item.id, fieldId, itemGroupId)
    • Other components pass the function as a prop

Let's verify the implementation of handleCheckItemReference in the ContentDetails component since it's the top-level implementation:


Let me try a different search pattern to find the implementation:


Based on the comprehensive verification results, I can now provide the final response:

✅ Function signature changes are properly implemented across the codebase

The verification confirms that:

  • All type definitions consistently use the new signature with itemId, correspondingFieldId, and optional groupId
  • The main implementation in ContentDetails/hooks.ts correctly handles all three parameters
  • All component usages properly pass through the function as a prop
  • The actual function call in LinkItemModal uses all three parameters correctly
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all usages of onCheckItemReference to ensure they're updated
# Expected: All callers should use the new 3-parameter signature

# Search for function calls
rg -A 3 "onCheckItemReference\(" 

# Search for function type definitions
rg -A 3 "onCheckItemReference\s*[:=]"

Length of output: 5483


Script:

#!/bin/bash
# Find the implementation of handleCheckItemReference
ast-grep --pattern 'handleCheckItemReference = async ($$$) => { $$$ }'
rg -A 5 'handleCheckItemReference\s*=\s*async'

Length of output: 121


Script:

#!/bin/bash
# Find the implementation of handleCheckItemReference with different patterns
rg -A 10 "const handleCheckItemReference"
rg -A 10 "handleCheckItemReference.*=.*async"

# Also search for any function declaration
ast-grep --pattern 'async function handleCheckItemReference($$$) { $$$ }'

Length of output: 1379

Comment on lines +33 to +37
onCheckItemReference?: (
itemId: string,
correspondingFieldId: string,
groupId?: string,
) => Promise<boolean>;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider adding error handling for reference checking.

The onCheckItemReference function might benefit from explicit error handling to gracefully handle network failures or invalid states.

   onCheckItemReference?: (
     itemId: string,
     correspondingFieldId: string,
     groupId?: string,
-  ) => Promise<boolean>;
+  ) => Promise<{ success: boolean; error?: string }>;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
onCheckItemReference?: (
itemId: string,
correspondingFieldId: string,
groupId?: string,
) => Promise<boolean>;
onCheckItemReference?: (
itemId: string,
correspondingFieldId: string,
groupId?: string,
) => Promise<{ success: boolean; error?: string }>;

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.

3 participants