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

[WEB-2774] Chore: re-ordering functionality for entities in favorites. #6078

Open
wants to merge 9 commits into
base: preview
Choose a base branch
from

Conversation

mathalav55
Copy link
Collaborator

@mathalav55 mathalav55 commented Nov 20, 2024

Summary:

Added functionality to re-order entities under Favorites section.
Project highlight fix. Only highlighting the last project dropped.

Reference:

[WEB-2774]

Summary by CodeRabbit

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced drag-and-drop functionality for reordering favorite items in the sidebar.
    • Introduced custom drag previews for a more visually appealing experience.
    • Added a new method for reordering favorites, improving user interaction.
  • Bug Fixes

    • Improved error handling and notifications for reordering operations.
  • Refactor

    • Streamlined method names and signatures for clarity in favorite management.
    • Adjusted component structures to improve drag-and-drop handling.

@CLAassistant
Copy link

CLAassistant commented Nov 20, 2024

CLA assistant check
All committers have signed the CLA.

Copy link
Contributor

coderabbitai bot commented Nov 20, 2024

Walkthrough

The changes in this pull request enhance the drag-and-drop functionality across several components related to favorites management. Key modifications include the introduction of a new handleReorder method for reordering favorites, updates to existing methods for moving favorites between folders, and improvements to the drag preview logic. The Props types in various components have been updated to accommodate these new functionalities, ensuring a more intuitive user experience when managing favorite items.

Changes

File Path Change Summary
web/core/components/workspace/sidebar/favorites/favorite-folder.tsx - Added imports for drag-and-drop functionality.
- Updated Props type to include handleReorder method.
- Renamed handleOnDrop to handleMoveToFolder and modified its implementation.
- Enhanced drag preview generation logic.
- Updated useEffect to link to new drag-and-drop logic.
- Modified child favorites mapping using orderBy.
web/core/components/workspace/sidebar/favorites/favorite-items/root.tsx - Added imports for drag-and-drop utilities.
- Updated Props type to include handleReorder method.
- Modified drag operation data structure in useEffect.
- Updated onDrop handler to manage item reordering.
- Enhanced drag preview generation logic.
web/core/components/workspace/sidebar/favorites/favorites-menu.tsx - Introduced handleReorder method utilizing reOrderFavorite from the useFavorite hook.
- Passed handleReorder prop to FavoriteFolder and FavoriteRoot components.
- Updated destructured return from useFavorite to include reOrderFavorite.
web/core/store/favorite.store.ts - Renamed moveFavorite to moveFavoriteToFolder and moveFavoriteFolder to reOrderFavorite in IFavoriteStore interface.
- Updated constructor and method logic in FavoriteStore class to reflect these changes.
web/core/components/workspace/sidebar/favorites/favorites.helpers.ts - Added new type TargetData for drag-and-drop context.
- Updated getDestinationStateSequence function for reordering logic.
- Introduced getInstructionFromPayload and getCanDrop functions for improved drop validation.
web/core/components/workspace/sidebar/projects-list-item.tsx - Adjusted Disclosure component's ref to enhance drag-and-drop functionality.
- Updated onDrop event handler for correct parameter invocation.
- Refined DropIndicator visibility logic.

Possibly related PRs

Suggested labels

🌟enhancement, 🛠️refactor

Suggested reviewers

  • SatishGandham
  • rahulramesha

Poem

🐇 In the land of favorites, we hop and play,
With drag-and-drop magic, we brighten the day.
Reorder with ease, let the items align,
A seamless experience, oh how divine!
So grab your favorites, let’s dance and cheer,
For improvements are here, let’s spread the good cheer! 🎉


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
Contributor

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

🧹 Outside diff range and nitpick comments (8)
web/core/components/workspace/sidebar/favorites/favorites-menu.tsx (1)

Line range hint 1-238: Consider adding documentation for reordering behavior

The component would benefit from:

  1. Documentation explaining the reordering behavior and sequence calculation logic
  2. JSDoc comments for the handleReorder method describing its parameters and behavior
  3. Comments explaining the interaction between drag-and-drop and reordering functionality

This would improve maintainability and make it easier for other developers to understand the implementation.

web/core/store/favorite.store.ts (2)

Line range hint 171-192: Remove unnecessary return statement in error handling

The error handling logic contains an unnecessary return statement that can be removed for better code clarity.

  runInAction(() => {
    if (!data.parent) return;
-   // revert the parent
    set(this.favoriteMap, [favoriteId, "parent"], oldParent);
  });

Line range hint 193-209: Move throw statement outside runInAction

The throw statement inside runInAction could interfere with MobX state tracking. Consider moving it outside:

  } catch (error) {
    console.error("Failed to move favorite folder");
    runInAction(() => {
      set(this.favoriteMap, [favoriteId, "sequence"], initialSequence);
-     throw error;
    });
+   throw error;
  }
web/core/components/workspace/sidebar/favorites/favorite-items/root.tsx (3)

6-8: Reorder imports to follow proper import ordering

The imports at lines 7 and 8 should be placed before the import at line 6 to comply with the project's import ordering conventions indicated by the linter.

Apply this diff to reorder the imports:

-import { attachClosestEdge, extractClosestEdge } from "@atlaskit/pragmatic-drag-and-drop-hitbox/closest-edge";
+import { setCustomNativeDragPreview } from "@atlaskit/pragmatic-drag-and-drop/element/set-custom-native-drag-preview";
+import { pointerOutsideOfPreview } from "@atlaskit/pragmatic-drag-and-drop/element/pointer-outside-of-preview";
+import { attachClosestEdge, extractClosestEdge } from "@atlaskit/pragmatic-drag-and-drop-hitbox/closest-edge";
🧰 Tools
🪛 GitHub Check: lint-web

[failure] 7-7:
@atlaskit/pragmatic-drag-and-drop/element/set-custom-native-drag-preview import should occur before import of @atlaskit/pragmatic-drag-and-drop-hitbox/closest-edge


[failure] 8-8:
@atlaskit/pragmatic-drag-and-drop/element/pointer-outside-of-preview import should occur before import of @atlaskit/pragmatic-drag-and-drop-hitbox/closest-edge


25-26: Adjust import order to meet coding standards

The import from "react-dom/client" at line 25 should come before the import from "@plane/helpers", and the import from "@plane/ui" at line 26 should be placed before imports from "@/components" to adhere to the project's import ordering rules.

Apply this diff to reorder the imports:

-import { useOutsideClickDetector } from "@plane/helpers";
+import { createRoot } from "react-dom/client";
+import { useOutsideClickDetector } from "@plane/helpers";
+import { DropIndicator } from "@plane/ui";
 import { observer } from "mobx-react";
 // plane helpers
-import { createRoot } from "react-dom/client";
 // components
-import { DropIndicator } from "@plane/ui";
 import {
   FavoriteItemDragHandle,
   FavoriteItemQuickAction,
🧰 Tools
🪛 GitHub Check: lint-web

[failure] 25-25:
react-dom/client import should occur before import of @plane/helpers


[failure] 26-26:
@plane/ui import should occur before import of @/components/workspace/sidebar/favorites


142-142: Remove trailing spaces

There's a trailing space at line 142. Removing it will keep the code clean and conform to coding standards.

Apply this diff:

-              const sourceType = source.data?.type as string | undefined;
-              
+              const sourceType = source.data?.type as string | undefined;
🧰 Tools
🪛 GitHub Check: lint-web

[failure] 142-142:
Trailing spaces not allowed

web/core/components/workspace/sidebar/favorites/favorite-folder.tsx (2)

92-92: Remove commented-out code

The line // onDragStart: () => setIsDragging(true), is commented out. If it's no longer needed, consider removing it to keep the codebase clean.


155-155: Remove trailing whitespace

Line 155 contains trailing spaces, which should be removed to comply with coding style guidelines.

Apply this diff to remove trailing spaces:

- 
+ 
🧰 Tools
🪛 GitHub Check: lint-web

[failure] 155-155:
Trailing spaces not allowed

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ca91d59 and 0f641ec.

📒 Files selected for processing (4)
  • web/core/components/workspace/sidebar/favorites/favorite-folder.tsx (7 hunks)
  • web/core/components/workspace/sidebar/favorites/favorite-items/root.tsx (4 hunks)
  • web/core/components/workspace/sidebar/favorites/favorites-menu.tsx (4 hunks)
  • web/core/store/favorite.store.ts (4 hunks)
🧰 Additional context used
🪛 GitHub Check: lint-web
web/core/components/workspace/sidebar/favorites/favorite-folder.tsx

[failure] 7-7:
@atlaskit/pragmatic-drag-and-drop/element/pointer-outside-of-preview import should occur before import of @atlaskit/pragmatic-drag-and-drop/element/set-custom-native-drag-preview


[failure] 14-14:
react-dom/client import should occur before import of lucide-react


[failure] 31-31:
lodash import should occur before import of lodash/uniqBy


[failure] 155-155:
Trailing spaces not allowed

web/core/components/workspace/sidebar/favorites/favorite-items/root.tsx

[failure] 7-7:
@atlaskit/pragmatic-drag-and-drop/element/set-custom-native-drag-preview import should occur before import of @atlaskit/pragmatic-drag-and-drop-hitbox/closest-edge


[failure] 8-8:
@atlaskit/pragmatic-drag-and-drop/element/pointer-outside-of-preview import should occur before import of @atlaskit/pragmatic-drag-and-drop-hitbox/closest-edge


[failure] 25-25:
react-dom/client import should occur before import of @plane/helpers


[failure] 26-26:
@plane/ui import should occur before import of @/components/workspace/sidebar/favorites


[failure] 142-142:
Trailing spaces not allowed

🔇 Additional comments (5)
web/core/components/workspace/sidebar/favorites/favorites-menu.tsx (2)

36-36: LGTM: Hook usage is correct

The addition of reOrderFavorite to the useFavorite hook destructuring is consistent with the reordering functionality requirements.


217-217: LGTM: Props passing is implemented correctly

The handleReorder prop is consistently passed to both FavoriteFolder and FavoriteRoot components, enabling reordering functionality throughout the favorites hierarchy.

Also applies to: 226-226

web/core/store/favorite.store.ts (3)

29-31: LGTM! Method names now better reflect their functionality

The renaming of methods from moveFavorite to moveFavoriteToFolder and moveFavoriteFolder to reOrderFavorite improves code clarity by making the intended functionality more explicit.


67-69: LGTM! MobX action decorators properly updated

The action decorators have been correctly updated to match the renamed methods, maintaining proper MobX state management.


Line range hint 171-209: Consider adding unit tests for reordering edge cases

The reordering functionality should be thoroughly tested, particularly for:

  1. Concurrent reordering operations
  2. Edge cases with sequence numbers
  3. Error recovery scenarios
  4. State rollback accuracy

Would you like help creating comprehensive unit tests for these scenarios?

},
})
);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [elementRef.current, isDragging, favorite.id, handleOnDrop]);
}, [elementRef.current, isDragging, favorite.id, handleMoveToFolder]);
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Avoid including mutable refs in the useEffect dependency array

Including elementRef.current in the dependency array of useEffect is unnecessary and can lead to unexpected behaviors. Mutable refs like elementRef.current do not trigger re-renders when they change, so it's safe to omit them from the dependency array.

Apply this diff to adjust the dependency array:

- }, [elementRef.current, isDragging, favorite.id, handleMoveToFolder]);
+ }, [isDragging, favorite.id, handleMoveToFolder]);
📝 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
}, [elementRef.current, isDragging, favorite.id, handleMoveToFolder]);
}, [isDragging, favorite.id, handleMoveToFolder]);

Comment on lines 134 to 139
const sourceId = source?.data?.id as string;
const destinationId = self?.data?.id as string | undefined;
if (groupedFavorites[sourceId].parent !== destinationId) {
setIsDraggedOver(true);
setIsDragging(true);
};
Copy link
Contributor

@coderabbitai coderabbitai bot Nov 20, 2024

Choose a reason for hiding this comment

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

⚠️ Potential issue

Prevent potential runtime errors due to undefined properties

Accessing groupedFavorites[sourceId] without ensuring it exists may cause runtime errors if sourceId is not a valid key. Please add a check to ensure groupedFavorites[sourceId] is defined before accessing its properties.

Apply this diff to add the necessary check:

  const sourceId = source?.data?.id as string;
  const destinationId = self?.data?.id as string | undefined;
- if (groupedFavorites[sourceId].parent !== destinationId) {
+ if (groupedFavorites[sourceId] && groupedFavorites[sourceId].parent !== destinationId) {
      setIsDraggedOver(true);
      setIsDragging(true);
  };
📝 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
const sourceId = source?.data?.id as string;
const destinationId = self?.data?.id as string | undefined;
if (groupedFavorites[sourceId].parent !== destinationId) {
setIsDraggedOver(true);
setIsDragging(true);
};
const sourceId = source?.data?.id as string;
const destinationId = self?.data?.id as string | undefined;
if (groupedFavorites[sourceId] && groupedFavorites[sourceId].parent !== destinationId) {
setIsDraggedOver(true);
setIsDragging(true);
};

Copy link
Collaborator

Choose a reason for hiding this comment

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

please check this

Copy link
Contributor

Choose a reason for hiding this comment

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

@rahulramesha, I reviewed the code again.

In the line:

if (groupedFavorites[sourceId].parent !== destinationId) {

there's a potential risk that groupedFavorites[sourceId] might be undefined if sourceId is not present in groupedFavorites. Accessing groupedFavorites[sourceId].parent without ensuring groupedFavorites[sourceId] exists could lead to a runtime error.

However, if sourceId is guaranteed to be a key in groupedFavorites at this point in the code, then the additional check may not be necessary. Please let me know if that's the case, and we can proceed without the additional check.

Let me know if you have any questions or need further assistance.

Comment on lines 6 to 7
import { setCustomNativeDragPreview } from "@atlaskit/pragmatic-drag-and-drop/element/set-custom-native-drag-preview";
import { pointerOutsideOfPreview } from "@atlaskit/pragmatic-drag-and-drop/element/pointer-outside-of-preview";
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Correct the import order according to coding standards

The static analysis tool indicates that pointerOutsideOfPreview import should occur before setCustomNativeDragPreview. Please reorder the imports to comply with project conventions.

Apply this diff to fix the import order:

- import { setCustomNativeDragPreview } from "@atlaskit/pragmatic-drag-and-drop/element/set-custom-native-drag-preview";
- import { pointerOutsideOfPreview } from "@atlaskit/pragmatic-drag-and-drop/element/pointer-outside-of-preview";
+ import { pointerOutsideOfPreview } from "@atlaskit/pragmatic-drag-and-drop/element/pointer-outside-of-preview";
+ import { setCustomNativeDragPreview } from "@atlaskit/pragmatic-drag-and-drop/element/set-custom-native-drag-preview";
📝 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
import { setCustomNativeDragPreview } from "@atlaskit/pragmatic-drag-and-drop/element/set-custom-native-drag-preview";
import { pointerOutsideOfPreview } from "@atlaskit/pragmatic-drag-and-drop/element/pointer-outside-of-preview";
import { pointerOutsideOfPreview } from "@atlaskit/pragmatic-drag-and-drop/element/pointer-outside-of-preview";
import { setCustomNativeDragPreview } from "@atlaskit/pragmatic-drag-and-drop/element/set-custom-native-drag-preview";
🧰 Tools
🪛 GitHub Check: lint-web

[failure] 7-7:
@atlaskit/pragmatic-drag-and-drop/element/pointer-outside-of-preview import should occur before import of @atlaskit/pragmatic-drag-and-drop/element/set-custom-native-drag-preview

Comment on lines 158 to 159
if (!sourceId || !destinationId) return;
if (groupedFavorites[sourceId].parent === destinationId) return;
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add null check to prevent runtime errors

Similarly, ensure that groupedFavorites[sourceId] is defined before accessing .parent to prevent potential errors.

Apply this diff to add the necessary check:

  if (!sourceId || !destinationId) return;
- if (groupedFavorites[sourceId].parent === destinationId) return;
+ if (groupedFavorites[sourceId] && groupedFavorites[sourceId].parent === destinationId) return;
📝 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
if (!sourceId || !destinationId) return;
if (groupedFavorites[sourceId].parent === destinationId) return;
if (!sourceId || !destinationId) return;
if (groupedFavorites[sourceId] && groupedFavorites[sourceId].parent === destinationId) return;

@@ -24,21 +28,23 @@
import { FavoriteRoot } from "./favorite-items";
import { getDestinationStateSequence } from "./favorites.helpers";
import { NewFavoriteFolder } from "./new-fav-folder";
import { orderBy } from "lodash";
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Reorder imports to comply with coding standards

The static analysis tool suggests that the import of lodash should occur before the import of lodash/uniqBy. Please reorder the imports to align with project conventions.

Apply this diff to fix the import order:

- import uniqBy from "lodash/uniqBy";
  import { useParams } from "next/navigation";
  import { PenSquare, Star, MoreHorizontal, ChevronRight, GripVertical } from "lucide-react";
  import { Disclosure, Transition } from "@headlessui/react";
+ import { orderBy } from "lodash";

+ import uniqBy from "lodash/uniqBy";

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 GitHub Check: lint-web

[failure] 31-31:
lodash import should occur before import of lodash/uniqBy


import { attachClosestEdge, extractClosestEdge } from "@atlaskit/pragmatic-drag-and-drop-hitbox/closest-edge";
import uniqBy from "lodash/uniqBy";
import { useParams } from "next/navigation";
import { PenSquare, Star, MoreHorizontal, ChevronRight, GripVertical } from "lucide-react";
import { Disclosure, Transition } from "@headlessui/react";
import { createRoot } from "react-dom/client";
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Adjust the import order to follow project conventions

According to the static analysis tool, the import of react-dom/client should occur before the import of lucide-react. Please adjust the import statements accordingly.

Apply this diff to fix the import order:

- import { PenSquare, Star, MoreHorizontal, ChevronRight, GripVertical } from "lucide-react";
  import { Disclosure, Transition } from "@headlessui/react";
+ import { createRoot } from "react-dom/client";

+ import { PenSquare, Star, MoreHorizontal, ChevronRight, GripVertical } from "lucide-react";

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 GitHub Check: lint-web

[failure] 14-14:
react-dom/client import should occur before import of lucide-react

Copy link
Contributor

@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: 3

🧹 Outside diff range and nitpick comments (5)
web/core/components/workspace/sidebar/favorites/favorite-items/root.tsx (2)

136-146: Simplify drop handler logic.

The drop handler contains nested conditionals that could be simplified for better readability and maintainability.

-onDrop: ({ self, source }) => {
-  setIsDragging(false);
-  setIsDraggedOver(false);
-  const sourceId = source.data?.id as string | undefined;
-  const destinationType = self.data?.type as string | undefined;
-
-  if(!sourceId) return;
-
-  if(destinationType === 'NON_PARENT'){
-    handleRemoveFromFavoritesFolder(sourceId)
-  }
-},
+onDrop: ({ self, source }) => {
+  setIsDragging(false);
+  setIsDraggedOver(false);
+  
+  const sourceId = source.data?.id;
+  const isNonParentDestination = self.data?.type === 'NON_PARENT';
+  
+  if (sourceId && isNonParentDestination) {
+    handleRemoveFromFavoritesFolder(sourceId);
+  }
+},

158-158: Consider consolidating DropIndicator implementation.

The duplicate DropIndicator components could be consolidated into a single reusable component or mapping to improve maintainability.

-<DropIndicator isVisible={isDraggedOver && closestEdge === "top"} classNames="absolute top-0" />
// ... other content ...
-<DropIndicator isVisible={isDraggedOver && closestEdge === "bottom"} classNames="absolute bottom-0" />
+{['top', 'bottom'].map((edge) => (
+  <DropIndicator
+    key={edge}
+    isVisible={isDraggedOver && closestEdge === edge}
+    classNames={`absolute ${edge}-0`}
+  />
+))}

Also applies to: 170-170

web/core/components/workspace/sidebar/favorites/favorite-folder.tsx (3)

93-109: Consider memoizing the drag preview render function

The drag preview render function is recreated on every render. Consider memoizing it for better performance.

+ const renderDragPreview = React.useCallback(({ container }) => {
+   const root = createRoot(container);
+   root.render(
+     <div className="rounded flex gap-1 bg-custom-background-100 text-sm p-1 pr-2">
+       <div className="size-5 grid place-items-center flex-shrink-0">
+         <FavoriteFolderIcon />
+       </div>
+       <p className="truncate text-sm font-medium text-custom-sidebar-text-200">{favorite.name}</p>
+     </div>
+   );
+   return () => root.unmount();
+ }, [favorite.name]);

  onGenerateDragPreview: ({ nativeSetDragImage }) => {
    setCustomNativeDragPreview({
      getOffset: pointerOutsideOfPreview({ x: "0px", y: "0px" }),
-     render: ({ container }) => {
-       const root = createRoot(container);
-       root.render(
-         <div className="rounded flex gap-1 bg-custom-background-100 text-sm p-1 pr-2">
-           <div className="size-5 grid place-items-center flex-shrink-0">
-             <FavoriteFolderIcon />
-           </div>
-           <p className="truncate text-sm font-medium text-custom-sidebar-text-200">{favorite.name}</p>
-         </div>
-       );
-       return () => root.unmount();
-     },
+     render: renderDragPreview,
      nativeSetDragImage,
    });
  },

118-121: Extract sequence calculation logic

Consider extracting the sequence calculation logic into a separate helper function for better maintainability and reusability.

+ const calculateNewSequence = (
+   groupedFavorites: Record<string, any>,
+   destinationId: string,
+   edge?: string
+ ): number => {
+   return Math.round(
+     getDestinationStateSequence(groupedFavorites, destinationId, edge) || 0
+   );
+ };

- const sequence = Math.round(
-   getDestinationStateSequence(groupedFavorites, destinationData.id as string, edge) || 0
- );
+ const sequence = calculateNewSequence(
+   groupedFavorites,
+   destinationData.id as string,
+   edge
+ );

327-327: Add type safety to orderBy parameters

Consider adding type safety to the orderBy parameters to prevent potential runtime errors.

- orderBy(uniqBy(favorite.children, "id"),'sequence','desc')
+ orderBy(
+   uniqBy(favorite.children, "id"),
+   ['sequence'] as const,
+   ['desc'] as const
+ )
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 0f641ec and 12743b5.

📒 Files selected for processing (3)
  • web/core/components/workspace/sidebar/favorites/favorite-folder.tsx (7 hunks)
  • web/core/components/workspace/sidebar/favorites/favorite-items/root.tsx (4 hunks)
  • web/core/components/workspace/sidebar/favorites/favorites-menu.tsx (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • web/core/components/workspace/sidebar/favorites/favorites-menu.tsx
🔇 Additional comments (4)
web/core/components/workspace/sidebar/favorites/favorite-items/root.tsx (2)

6-8: LGTM: Imports and type definitions are well-structured.

The new imports and type definitions appropriately support the drag-and-drop functionality enhancements.

Also applies to: 11-11, 16-16, 27-29, 36-36


41-48: LGTM: Props destructuring is clean and consistent.

The props destructuring properly includes all required properties and maintains consistency with the type definition.

web/core/components/workspace/sidebar/favorites/favorite-folder.tsx (2)

38-38: LGTM: Props type definition is well-structured

The new handleReorder prop is properly typed with clear parameter definitions.


42-42: LGTM: Clean props destructuring and hook usage

Props destructuring and hook usage follow React best practices.

Also applies to: 47-47

Comment on lines 86 to 92
if (favorite.id && destinationData) {
const edge = extractClosestEdge(destinationData) || undefined;
const sequence = Math.round(
getDestinationStateSequence(favoriteMap, destinationData.id as string, edge) || 0
);
handleReorder(favorite.id, sequence);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for sequence calculation.

The sequence calculation and reordering logic lacks error handling. Consider adding validation and error handling to prevent potential issues.

 if (favorite.id && destinationData) {
+  try {
     const edge = extractClosestEdge(destinationData) || undefined;
     const sequence = Math.round(
       getDestinationStateSequence(favoriteMap, destinationData.id as string, edge) || 0
     );
     handleReorder(favorite.id, sequence);
+  } catch (error) {
+    console.error('Failed to reorder favorite:', error);
+    // Consider showing a user-friendly error notification
+  }
 }
📝 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
if (favorite.id && destinationData) {
const edge = extractClosestEdge(destinationData) || undefined;
const sequence = Math.round(
getDestinationStateSequence(favoriteMap, destinationData.id as string, edge) || 0
);
handleReorder(favorite.id, sequence);
}
if (favorite.id && destinationData) {
try {
const edge = extractClosestEdge(destinationData) || undefined;
const sequence = Math.round(
getDestinationStateSequence(favoriteMap, destinationData.id as string, edge) || 0
);
handleReorder(favorite.id, sequence);
} catch (error) {
console.error('Failed to reorder favorite:', error);
// Consider showing a user-friendly error notification
}
}

Comment on lines +94 to +112
onGenerateDragPreview: ({ nativeSetDragImage }) => {
setCustomNativeDragPreview({
getOffset: pointerOutsideOfPreview({ x: "0px", y: "0px" }),
render: ({ container }) => {
const root = createRoot(container);
root.render(
<div className="rounded bg-custom-background-100 text-sm p-1 pr-2">
<FavoriteItemTitle
href={itemLink}
icon={itemIcon}
title={itemTitle}
isSidebarCollapsed={!!sidebarCollapsed}
/>
</div>
);
return () => root.unmount();
},
nativeSetDragImage,
});
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add cleanup for drag preview root.

The current implementation of the drag preview could potentially cause memory leaks if the component unmounts during a drag operation. Consider wrapping the root creation in a try-catch block and ensuring cleanup.

 onGenerateDragPreview: ({ nativeSetDragImage }) => {
+  let root: Root | null = null;
   setCustomNativeDragPreview({
     getOffset: pointerOutsideOfPreview({ x: "0px", y: "0px" }),
     render: ({ container }) => {
-      const root = createRoot(container);
+      try {
+        root = createRoot(container);
+        root.render(
-      root.render(
         <div className="rounded bg-custom-background-100 text-sm p-1 pr-2">
           <FavoriteItemTitle
             href={itemLink}
             icon={itemIcon}
             title={itemTitle}
             isSidebarCollapsed={!!sidebarCollapsed}
           />
         </div>
       );
-      return () => root.unmount();
+      return () => {
+        root?.unmount();
+        root = null;
+      };
+      } catch (error) {
+        console.error('Failed to create drag preview:', error);
+        return () => {};
+      }
     },
     nativeSetDragImage,
   });
 },
📝 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
onGenerateDragPreview: ({ nativeSetDragImage }) => {
setCustomNativeDragPreview({
getOffset: pointerOutsideOfPreview({ x: "0px", y: "0px" }),
render: ({ container }) => {
const root = createRoot(container);
root.render(
<div className="rounded bg-custom-background-100 text-sm p-1 pr-2">
<FavoriteItemTitle
href={itemLink}
icon={itemIcon}
title={itemTitle}
isSidebarCollapsed={!!sidebarCollapsed}
/>
</div>
);
return () => root.unmount();
},
nativeSetDragImage,
});
onGenerateDragPreview: ({ nativeSetDragImage }) => {
let root: Root | null = null;
setCustomNativeDragPreview({
getOffset: pointerOutsideOfPreview({ x: "0px", y: "0px" }),
render: ({ container }) => {
try {
root = createRoot(container);
root.render(
<div className="rounded bg-custom-background-100 text-sm p-1 pr-2">
<FavoriteItemTitle
href={itemLink}
icon={itemIcon}
title={itemTitle}
isSidebarCollapsed={!!sidebarCollapsed}
/>
</div>
);
return () => {
root?.unmount();
root = null;
};
} catch (error) {
console.error('Failed to create drag preview:', error);
return () => {};
}
},
nativeSetDragImage,
});

@@ -51,10 +57,10 @@ export const FavoriteFolder: React.FC<Props> = (props) => {
const actionSectionRef = useRef<HTMLDivElement | null>(null);
const elementRef = useRef<HTMLDivElement | null>(null);

!favorite.children && getGroupedFavorites(workspaceSlug.toString(), favorite.id);
if(!favorite.children) getGroupedFavorites(workspaceSlug.toString(), favorite.id);
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for grouped favorites fetch

The conditional fetch should include error handling to gracefully handle failures.

-  if(!favorite.children) getGroupedFavorites(workspaceSlug.toString(), favorite.id);
+  if(!favorite.children) {
+    getGroupedFavorites(workspaceSlug.toString(), favorite.id)
+      .catch((error) => {
+        setToast({
+          type: TOAST_TYPE.ERROR,
+          title: "Error!",
+          message: "Failed to fetch favorites.",
+        });
+      });
+  }

Committable suggestion skipped: line range outside the PR's diff.

@@ -83,6 +83,26 @@ export const SidebarFavoritesMenu = observer(() => {
});
});
};

const handleReorder = (favoriteId: string, sequence: number) => {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Memoize this.

Comment on lines 134 to 139
const sourceId = source?.data?.id as string;
const destinationId = self?.data?.id as string | undefined;
if (groupedFavorites[sourceId].parent !== destinationId) {
setIsDraggedOver(true);
setIsDragging(true);
};
Copy link
Collaborator

Choose a reason for hiding this comment

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

please check this

@mathalav55 mathalav55 marked this pull request as draft November 21, 2024 10:00
@mathalav55 mathalav55 marked this pull request as ready for review November 22, 2024 18:51
@mathalav55 mathalav55 marked this pull request as draft November 22, 2024 18:51
Copy link
Contributor

@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: 3

🧹 Outside diff range and nitpick comments (6)
web/core/components/workspace/sidebar/favorites/favorites.helpers.ts (3)

49-50: Remove unnecessary console.log statement

The console.log({resultSequence}); statement appears to be a leftover from debugging and should be removed to clean up the code.

Apply this diff to remove the statement:

-  console.log({resultSequence});

85-86: Correct typo in comment

There's a typo in the comment. "A group cannon be a child..." should be "A group cannot be a child...".

Apply this diff to correct the typo:

-  // if source that is being dragged is a group. A group cannon be a child of any other favorite,
+  // If the source that is being dragged is a group, a group cannot be a child of any other favorite,

104-105: Fix typo in comment

The comment contains a typo: "dropped unto itself" should be "dropped onto itself".

Apply this diff to fix the typo:

-  // a favorite cannot be dropped unto itself
+  // a favorite cannot be dropped onto itself
web/core/components/workspace/sidebar/favorites/favorite-items/root.tsx (1)

73-162: Consider performance optimizations

The drag-and-drop implementation could benefit from the following optimizations:

  1. Memoize complex calculations
  2. Optimize effect dependencies
  3. Use callbacks for event handlers

Consider applying these optimizations:

+ const memoizedInitialData = useMemo(
+   () => ({ id: favorite.id, isGroup: false, isChild: !!parentId, parentId }),
+   [favorite.id, parentId]
+ );

+ const handleDrop = useCallback(({ source, location }) => {
+   // ... existing drop logic
+ }, [favoriteMap, handleReorder, handleRemoveFromFavoritesFolder]);

  useEffect(() => {
    const element = elementRef.current;
    if (!element) return;

-   const initialData = { id: favorite.id, isGroup: false, isChild: !!parentId, parentId };
    return combine(
      draggable({
        element,
        dragHandle: elementRef.current,
-       getInitialData: () => initialData,
+       getInitialData: () => memoizedInitialData,
        // ... rest of the code
      }),
      dropTargetForElements({
        // ... other props
-       onDrop: ({ source, location }) => { ... },
+       onDrop: handleDrop,
      })
    );
-   // eslint-disable-next-line react-hooks/exhaustive-deps
+   // explicit dependencies
+   }, [elementRef.current, isDragging, memoizedInitialData, handleDrop]);
web/core/components/workspace/sidebar/projects-list-item.tsx (2)

Line range hint 39-48: Consider enhancing type safety for project-related props

The projectListType prop could benefit from using a TypeScript enum or union type constant instead of string literals for better type safety and maintainability.

+type ProjectListType = "JOINED" | "FAVORITES";
+
 type Props = {
   projectId: string;
   handleCopyText: () => void;
   handleOnProjectDrop?: (
     sourceId: string | undefined,
     destinationId: string | undefined,
     shouldDropAtEnd: boolean
   ) => void;
-  projectListType: "JOINED" | "FAVORITES";
+  projectListType: ProjectListType;
   disableDrag?: boolean;
   disableDrop?: boolean;
   isLastChild: boolean;
 };

Line range hint 77-81: Optimize state management to reduce re-renders

Consider combining related state variables into a single state object to reduce the number of state updates and potential re-renders.

-  const [leaveProjectModalOpen, setLeaveProjectModal] = useState(false);
-  const [publishModalOpen, setPublishModal] = useState(false);
-  const [isMenuActive, setIsMenuActive] = useState(false);
-  const [isDragging, setIsDragging] = useState(false);
-  const [isProjectListOpen, setIsProjectListOpen] = useState(false);
+  const [uiState, setUiState] = useState({
+    leaveProjectModalOpen: false,
+    publishModalOpen: false,
+    isMenuActive: false,
+    isDragging: false,
+    isProjectListOpen: false
+  });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 12743b5 and b2a58a3.

📒 Files selected for processing (5)
  • web/core/components/workspace/sidebar/favorites/favorite-folder.tsx (5 hunks)
  • web/core/components/workspace/sidebar/favorites/favorite-items/root.tsx (4 hunks)
  • web/core/components/workspace/sidebar/favorites/favorites-menu.tsx (7 hunks)
  • web/core/components/workspace/sidebar/favorites/favorites.helpers.ts (3 hunks)
  • web/core/components/workspace/sidebar/projects-list-item.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • web/core/components/workspace/sidebar/favorites/favorite-folder.tsx
  • web/core/components/workspace/sidebar/favorites/favorites-menu.tsx
🔇 Additional comments (5)
web/core/components/workspace/sidebar/favorites/favorites.helpers.ts (1)

51-51: Double-check the necessity of rounding resultSequence

Confirm whether rounding resultSequence is essential. Depending on how sequence values are used elsewhere, rounding might introduce unintended ordering issues.

Would you like to verify if floating-point sequence values cause any problems in the application?

web/core/components/workspace/sidebar/favorites/favorite-items/root.tsx (2)

6-9: LGTM: Clean imports and well-defined types

The new imports and type definitions are well-organized and properly typed for the drag-and-drop functionality.

Also applies to: 15-17, 32-33, 39-39


170-170: LGTM: Clean implementation of drop indicators

The drop indicators are well-positioned and provide clear visual feedback during drag operations. The conditional rendering based on instruction state is implemented correctly.

Also applies to: 184-184

web/core/components/workspace/sidebar/projects-list-item.tsx (2)

Line range hint 1-607: Implementation successfully achieves re-ordering functionality

The changes effectively implement the project re-ordering functionality with proper drag-and-drop handling, state management, and UI feedback. The code is well-structured and maintains good separation of concerns.


301-307: Verify ref assignment and cleanup

The ref prop has been moved from the Disclosure component to the outer div. While this change supports the drag-and-drop functionality, ensure that the ref is properly cleaned up when the component unmounts.

✅ Verification successful

Let me search for the ref cleanup patterns and drag-drop implementation more broadly.


Let me search for the drag-drop implementation and ref usage in the specific file.


Based on the code analysis, I can now provide a final response about the ref cleanup concern:

Ref cleanup is properly handled through drag-drop cleanup

The projectRef is used within the drag-drop setup which is handled by the combine function from Atlaskit's pragmatic-drag-and-drop library. The cleanup is automatically managed through:

  1. The ref is properly scoped within component lifecycle
  2. The drag-drop cleanup is handled by the library's internal cleanup mechanism
  3. The ref is only used for DOM element reference and event delegation, not for storing mutable values that need explicit cleanup
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for other instances of projectRef cleanup in the codebase
rg -A 5 "projectRef.current = null" 

Length of output: 37


Script:

#!/bin/bash
# Search for useEffect cleanup patterns in the file
rg -A 10 "useEffect.*return" "web/core/components/workspace/sidebar/projects-list-item.tsx"

# Search for drag-drop related code to understand the ref usage
ast-grep --pattern 'useEffect(() => {
  $$$
  return () => {
    $$$
  }
}, $$$)'  

Length of output: 63369


Script:

#!/bin/bash
# Search for drag-drop related code and ref usage in the file
rg -A 10 "projectRef|useEffect.*drag" "web/core/components/workspace/sidebar/projects-list-item.tsx"

# Search for the ref declaration
ast-grep --pattern 'const $ref = useRef'

Length of output: 2056

Comment on lines +100 to +101
const sourceData = source?.data;

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure consistent typing of sourceData

In the getCanDrop function, sourceData is not explicitly typed as TargetData. To ensure type safety and avoid runtime errors, cast sourceData to TargetData.

Apply this diff to cast sourceData:

-  const sourceData = source?.data;
+  const sourceData = source?.data as TargetData;

This ensures that properties like id and isGroup are properly recognized by TypeScript.

📝 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
const sourceData = source?.data;
const sourceData = source?.data as TargetData;

Comment on lines +136 to +159
onDrop: ({ source, location }) => {
setInstruction(undefined);
const dropTargets = location?.current?.dropTargets ?? []
if(!dropTargets || dropTargets.length <= 0) return;

const dropTarget = dropTargets.length > 1 ? dropTargets.find(target=>target?.data?.isChild) : dropTargets[0];

const dropTargetData = dropTarget?.data as TargetData;

if(!dropTarget || !dropTargetData) return;

const instruction = getInstructionFromPayload(dropTarget, source, location);
const parentId = instruction === 'make-child' ? dropTargetData.id : dropTargetData.parentId;
const droppedFavId = instruction !== "make-child" ? dropTargetData.id : undefined;
const sourceData = source.data as TargetData;

if(droppedFavId && sourceData.id){
const destinationSequence = getDestinationStateSequence(favoriteMap,droppedFavId,instruction)
handleReorder(sourceData.id,destinationSequence || 0)
}

if(!parentId && sourceData.isChild){
handleRemoveFromFavoritesFolder(sourceData.id)
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add error boundaries and validation for drop operations

The drop handling logic is complex and should be protected with proper error handling and validation:

  1. Validate sequence calculation results
  2. Add error boundaries for the drag-and-drop operations
  3. Handle edge cases when dropTarget data is malformed

Apply this diff to improve error handling:

 onDrop: ({  source, location }) => {
   setInstruction(undefined);
+  try {
     const dropTargets = location?.current?.dropTargets ?? []
-    if(!dropTargets || dropTargets.length <= 0) return;
+    if(!dropTargets || dropTargets.length <= 0) {
+      console.warn('No valid drop targets found');
+      return;
+    }

     const dropTarget = dropTargets.length > 1 ? dropTargets.find(target=>target?.data?.isChild) : dropTargets[0];
     const dropTargetData = dropTarget?.data as TargetData;

-    if(!dropTarget || !dropTargetData) return;
+    if(!dropTarget || !dropTargetData) {
+      console.warn('Invalid drop target data');
+      return;
+    }

     const instruction = getInstructionFromPayload(dropTarget, source, location);
     const parentId = instruction === 'make-child' ? dropTargetData.id : dropTargetData.parentId;
     const droppedFavId = instruction !== "make-child" ? dropTargetData.id : undefined;
     const sourceData = source.data as TargetData;

     if(droppedFavId && sourceData.id){
       const destinationSequence = getDestinationStateSequence(favoriteMap,droppedFavId,instruction)
+      if (typeof destinationSequence !== 'number') {
+        console.error('Invalid sequence calculation');
+        return;
+      }
       handleReorder(sourceData.id,destinationSequence || 0)
     }

     if(!parentId && sourceData.isChild){
       handleRemoveFromFavoritesFolder(sourceData.id)
     }
+  } catch (error) {
+    console.error('Error during drop operation:', error);
+    // Consider showing a user-friendly error notification
+  }
 },
📝 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
onDrop: ({ source, location }) => {
setInstruction(undefined);
const dropTargets = location?.current?.dropTargets ?? []
if(!dropTargets || dropTargets.length <= 0) return;
const dropTarget = dropTargets.length > 1 ? dropTargets.find(target=>target?.data?.isChild) : dropTargets[0];
const dropTargetData = dropTarget?.data as TargetData;
if(!dropTarget || !dropTargetData) return;
const instruction = getInstructionFromPayload(dropTarget, source, location);
const parentId = instruction === 'make-child' ? dropTargetData.id : dropTargetData.parentId;
const droppedFavId = instruction !== "make-child" ? dropTargetData.id : undefined;
const sourceData = source.data as TargetData;
if(droppedFavId && sourceData.id){
const destinationSequence = getDestinationStateSequence(favoriteMap,droppedFavId,instruction)
handleReorder(sourceData.id,destinationSequence || 0)
}
if(!parentId && sourceData.isChild){
handleRemoveFromFavoritesFolder(sourceData.id)
}
onDrop: ({ source, location }) => {
setInstruction(undefined);
try {
const dropTargets = location?.current?.dropTargets ?? []
if(!dropTargets || dropTargets.length <= 0) {
console.warn('No valid drop targets found');
return;
}
const dropTarget = dropTargets.length > 1 ? dropTargets.find(target=>target?.data?.isChild) : dropTargets[0];
const dropTargetData = dropTarget?.data as TargetData;
if(!dropTarget || !dropTargetData) {
console.warn('Invalid drop target data');
return;
}
const instruction = getInstructionFromPayload(dropTarget, source, location);
const parentId = instruction === 'make-child' ? dropTargetData.id : dropTargetData.parentId;
const droppedFavId = instruction !== "make-child" ? dropTargetData.id : undefined;
const sourceData = source.data as TargetData;
if(droppedFavId && sourceData.id){
const destinationSequence = getDestinationStateSequence(favoriteMap,droppedFavId,instruction)
if (typeof destinationSequence !== 'number') {
console.error('Invalid sequence calculation');
return;
}
handleReorder(sourceData.id,destinationSequence || 0)
}
if(!parentId && sourceData.isChild){
handleRemoveFromFavoritesFolder(sourceData.id)
}
} catch (error) {
console.error('Error during drop operation:', error);
// Consider showing a user-friendly error notification
}

Comment on lines +301 to +307
<Disclosure key={`${project.id}_${URLProjectId}`} defaultOpen={isProjectListOpen} as="div">
<div
id={`sidebar-${projectId}-${projectListType}`}
className={cn("relative", {
"bg-custom-sidebar-background-80 opacity-60": isDragging,
})}
ref={projectRef}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance accessibility for drag-and-drop interactions

The drag-and-drop functionality should include ARIA attributes to improve accessibility. Consider adding appropriate aria-labels and roles.

 <Disclosure key={`${project.id}_${URLProjectId}`} defaultOpen={isProjectListOpen} as="div">
   <div
     id={`sidebar-${projectId}-${projectListType}`}
     className={cn("relative", {
       "bg-custom-sidebar-background-80 opacity-60": isDragging,
     })}
+    role="listitem"
+    aria-label={`Project ${project.name}`}
+    aria-grabbed={isDragging}
     ref={projectRef}
   >
📝 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
<Disclosure key={`${project.id}_${URLProjectId}`} defaultOpen={isProjectListOpen} as="div">
<div
id={`sidebar-${projectId}-${projectListType}`}
className={cn("relative", {
"bg-custom-sidebar-background-80 opacity-60": isDragging,
})}
ref={projectRef}
<Disclosure key={`${project.id}_${URLProjectId}`} defaultOpen={isProjectListOpen} as="div">
<div
id={`sidebar-${projectId}-${projectListType}`}
className={cn("relative", {
"bg-custom-sidebar-background-80 opacity-60": isDragging,
})}
role="listitem"
aria-label={`Project ${project.name}`}
aria-grabbed={isDragging}
ref={projectRef}

@mathalav55 mathalav55 marked this pull request as ready for review November 22, 2024 19:36
Copy link
Contributor

@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/core/components/workspace/sidebar/favorites/favorite-folder.tsx (2)

92-109: Consider extracting drag preview into a separate component

The drag preview rendering logic could be moved to a separate component to improve maintainability and reusability.

+const FavoriteDragPreview: React.FC<{ name: string }> = ({ name }) => (
+  <div className="rounded flex gap-1 bg-custom-background-100 text-sm p-1 pr-2">
+    <div className="size-5 grid place-items-center flex-shrink-0">
+      <FavoriteFolderIcon />
+    </div>
+    <p className="truncate text-sm font-medium text-custom-sidebar-text-200">{name}</p>
+  </div>
+);

 onGenerateDragPreview: ({ nativeSetDragImage }) => {
   setCustomNativeDragPreview({
     getOffset: pointerOutsideOfPreview({ x: "0px", y: "0px" }),
     render: ({ container }) => {
       const root = createRoot(container);
-      root.render(
-        <div className="rounded flex gap-1 bg-custom-background-100 text-sm p-1 pr-2">
-          <div className="size-5 grid place-items-center flex-shrink-0">
-            <FavoriteFolderIcon />
-          </div>
-          <p className="truncate text-sm font-medium text-custom-sidebar-text-200">{favorite.name}</p>
-        </div>
-      );
+      root.render(<FavoriteDragPreview name={favorite.name} />);
       return () => root.unmount();
     },
     nativeSetDragImage,
   });
 },

172-186: Remove commented-out code

The commented-out code should be removed as it's no longer needed and can cause confusion.

-          // if(parentId)
-          //   handleMoveToFolder(sourceData.id,parentId);
-          // else
-          //   handleRemoveFromFavoritesFolder(sourceData.id)
-
-          // setIsDragging(false);
-          // const sourceId = source?.data?.id as string | undefined;
-          // const destinationId = self?.data?.id as string | undefined;
-
-          // if (source.data.is_folder) return;
-          // if (sourceId === destinationId) return;
-          // if (!sourceId || !destinationId) return;
-          // if (groupedFavorites[sourceId].parent === destinationId) return;
-
-          // handleMoveToFolder(sourceId, destinationId);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b2a58a3 and 1b124c6.

📒 Files selected for processing (2)
  • web/core/components/workspace/sidebar/favorites/favorite-folder.tsx (5 hunks)
  • web/core/components/workspace/sidebar/favorites/favorites-menu.tsx (8 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • web/core/components/workspace/sidebar/favorites/favorites-menu.tsx
🔇 Additional comments (2)
web/core/components/workspace/sidebar/favorites/favorite-folder.tsx (2)

32-38: LGTM! Props interface updated correctly

The addition of handleReorder prop and its proper destructuring aligns well with the reordering functionality requirements.

Also applies to: 41-41


211-211: LGTM! Rendering logic properly implements reordering functionality

The changes correctly implement:

  • Instruction-based styling for drag and drop visual feedback
  • Proper ordering of children using orderBy
  • Correct prop passing for reordering functionality

Also applies to: 354-354, 359-360, 364-364


const dropTargetData = dropTarget?.data as TargetData;

if(!dropTarget || !dropTargetData) return;
Copy link
Collaborator

Choose a reason for hiding this comment

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

This logic looks complex and similar to the favorite folder, try to separate it out to a common folder

Copy link
Contributor

@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/core/components/workspace/sidebar/favorites/favorite-folder.tsx (2)

133-162: Consider breaking down the complex drop handler

The drop handler contains multiple responsibilities and nested conditions. Consider extracting the logic into smaller, focused functions for better maintainability.

Example refactor:

+const handleDropReorder = (sourceData: TargetData, droppedFavId: string, instruction: InstructionType) => {
+  if(instruction === 'make-child') return;
+  const destinationSequence = getDestinationStateSequence(groupedFavorites, droppedFavId, instruction);
+  handleReorder(sourceData.id, destinationSequence || 0);
+};

+const handleDropParentChange = (sourceData: TargetData, parentId: string) => {
+  if(parentId !== sourceData.parentId) {
+    handleMoveToFolder(sourceData.id, parentId);
+  }
+};

onDrop: ({ source, location }) => {
  setInstruction(undefined);

  const dropTargets = location?.current?.dropTargets ?? [];
  if(!dropTargets || dropTargets.length <= 0) return;
  
  const dropTarget = dropTargets.length > 1 
    ? dropTargets.find(target => target?.data?.isChild) 
    : dropTargets[0];

  const dropTargetData = dropTarget?.data as TargetData;
  if(!dropTarget || !dropTargetData) return;

  const instruction = getInstructionFromPayload(dropTarget, source, location);
  const parentId = instruction === 'make-child' ? dropTargetData.id : dropTargetData.parentId;
  const droppedFavId = instruction !== "make-child" ? dropTargetData.id : undefined;
  const sourceData = source.data as TargetData;

  if(!sourceData.id) return;
  
+  if(parentId) {
+    handleDropParentChange(sourceData, parentId);
+  } else if(sourceData.isChild) {
+    handleRemoveFromFavoritesFolder(sourceData.id);
+  }

+  if(droppedFavId) {
+    handleDropReorder(sourceData, droppedFavId, instruction);
+  }
-  if(parentId){
-    if(parentId !== sourceData.parentId){
-      handleMoveToFolder(sourceData.id,parentId)
-    }
-  } else {
-    if(sourceData.isChild){
-      handleRemoveFromFavoritesFolder(sourceData.id)
-    }
-  }
-  if(droppedFavId){
-    if(instruction === 'make-child') return;
-    const destinationSequence = getDestinationStateSequence(groupedFavorites,droppedFavId,instruction)
-    handleReorder(sourceData.id,destinationSequence || 0)
-  }
},

330-340: Consider memoizing sorted children

The orderBy operation on children array could be memoized to prevent unnecessary re-sorting on each render.

Apply this diff:

+const sortedChildren = useMemo(
+  () => orderBy(favorite.children, 'sequence', 'desc'),
+  [favorite.children]
+);

-{orderBy(favorite.children,'sequence','desc').map((child,index) => (
+{sortedChildren.map((child, index) => (

Don't forget to add the useMemo import:

-import { useEffect, useRef, useState } from "react";
+import { useEffect, useRef, useState, useMemo } from "react";
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1b124c6 and d1cc0e0.

📒 Files selected for processing (2)
  • web/core/components/workspace/sidebar/favorites/favorite-folder.tsx (5 hunks)
  • web/core/components/workspace/sidebar/favorites/favorites-menu.tsx (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • web/core/components/workspace/sidebar/favorites/favorites-menu.tsx
🔇 Additional comments (2)
web/core/components/workspace/sidebar/favorites/favorite-folder.tsx (2)

6-8: LGTM: Import statements and Props type updates

The new imports enhance drag-and-drop functionality, and the Props type has been correctly extended with the handleReorder method.

Also applies to: 37-37


85-102: LGTM: Well-implemented custom drag preview

The drag preview implementation using createRoot provides a clean and consistent visual experience.

const { workspaceSlug } = useParams();
// states
const [isMenuActive, setIsMenuActive] = useState(false);
const [isDragging, setIsDragging] = useState(false);
const [folderToRename, setFolderToRename] = useState<string | boolean | null>(null);
const [isDraggedOver, setIsDraggedOver] = useState(false);
const [closestEdge, setClosestEdge] = useState<string | null>(null);
const [instruction, setInstruction] = useState<InstructionType | undefined>(undefined);
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add error handling to getGroupedFavorites call

The fetch operation should include error handling to manage potential failures gracefully.

Apply this diff:

-if(!favorite.children) getGroupedFavorites(workspaceSlug.toString(), favorite.id);
+if(!favorite.children) {
+  getGroupedFavorites(workspaceSlug.toString(), favorite.id)
+    .catch((error) => {
+      setToast({
+        type: TOAST_TYPE.ERROR,
+        title: "Error!",
+        message: "Failed to fetch favorites.",
+      });
+    });
+}

Also applies to: 58-58

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants