Skip to content

Conversation

@aaryan610
Copy link
Member

@aaryan610 aaryan610 commented Jan 20, 2025

Description

This PR brings the following bug fixes and improvements to stickies-

  1. Added missing empty states in the sticky modal.
  2. Updated skeleton loader.
  3. Remove DND.

Type of Change

  • Bug fix (non-breaking change which fixes an issue)
  • Improvement (change that would cause existing functionality to not work as expected)

Summary by CodeRabbit

  • New Features

    • Added a new StickiesLoader component to improve loading state visualization
    • Enhanced layout management for stickies with dynamic reflow capabilities
  • Bug Fixes

    • Improved error handling in delete modal
    • Refined empty state rendering for stickies list based on search queries
  • Style

    • Updated styling for stickies title and recent sticky icon
    • Adjusted text color and font size for better readability
  • Refactor

    • Simplified component prop handling
    • Removed unnecessary pathname-related logic in sticky components

@aaryan610 aaryan610 added this to the v0.24.0 milestone Jan 20, 2025
@aaryan610 aaryan610 requested a review from gakshita January 20, 2025 11:30
@aaryan610 aaryan610 marked this pull request as draft January 20, 2025 11:30
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 20, 2025

Walkthrough

The pull request introduces several modifications to the stickies components across multiple files. The changes focus on enhancing the loading state, layout management, and error handling in the stickies functionality. A new StickiesLoader component is introduced to handle loading states, and components like StickiesList and StickyDNDWrapper receive updates to support dynamic layout management through a new handleLayout method.

Changes

File Change Summary
web/core/components/stickies/delete-modal.tsx - Updated handleSubmit to be asynchronous
- Refined error handling and toast notification message
web/core/components/stickies/layout/stickies-list.tsx - Replaced Loader with StickiesLoader
- Added masonryRef and handleLayout function
- Modified empty state rendering logic
web/core/components/stickies/layout/stickies-loader.tsx - New component created for loading state
- Uses Loader from @plane/ui with placeholder items
web/core/components/stickies/layout/sticky-dnd-wrapper.tsx - Added handleLayout prop
- Restructured component props handling
web/core/components/stickies/modal/stickies.tsx - Updated imports and styling
- Added semantic button type
web/core/components/stickies/sticky/inputs.tsx - Changed handleUpdate function signature from async to sync
web/core/components/stickies/sticky/root.tsx - Added optional handleLayout prop
- Commented out pathname-related logic

Sequence Diagram

sequenceDiagram
    participant User
    participant StickiesList
    participant StickyDNDWrapper
    participant StickyNote
    participant HandleLayout

    User->>StickiesList: Interact with Stickies
    StickiesList->>StickyDNDWrapper: Trigger Layout Update
    StickyDNDWrapper->>StickyNote: Pass handleLayout
    StickyNote->>HandleLayout: Call Layout Update
    HandleLayout-->>StickyNote: Reflow Layout
Loading

Suggested reviewers

  • SatishGandham
  • rahulramesha

Poem

🐰 Sticky notes dance and sway,
Layout magic finds its way!
Loaders spin with gentle grace,
Refactored code sets new pace.
Rabbit's code, a joyful art! 🎨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@gakshita gakshita marked this pull request as ready for review January 21, 2025 08:05
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 comments (1)
web/core/components/stickies/sticky/inputs.tsx (1)

Line range hint 65-77: Implement proper file upload handling.

The current implementation of uploadFile returns an empty string and lacks error handling. This could lead to silent failures and poor user experience.

Consider implementing proper file upload handling:

- uploadFile={async () => ""}
+ uploadFile={async (file: File) => {
+   try {
+     // Implement actual file upload logic
+     const uploadedUrl = await yourFileUploadService.upload(file);
+     return uploadedUrl;
+   } catch (error) {
+     console.error("File upload failed:", error);
+     throw new Error("Failed to upload file. Please try again.");
+   }
+ }}
🧹 Nitpick comments (5)
web/core/components/stickies/sticky/inputs.tsx (1)

Line range hint 37-44: Consider debouncing editor updates for better performance.

The form submission is triggered on every editor change, which could lead to excessive updates. Consider implementing debouncing to optimize performance.

+ import { debounce } from "lodash";

  const handleFormSubmit = useCallback(
-   async (formdata: Partial<TSticky>) => {
-     await handleUpdate({
+   debounce((formdata: Partial<TSticky>) => {
+     handleUpdate({
        description_html: formdata.description_html ?? "<p></p>",
-     });
+     });
+   }, 300),
    },
    [handleUpdate]
  );
web/core/components/stickies/delete-modal.tsx (1)

23-28: Consider logging the error for debugging.

The error catch block discards the error information. Consider logging it for debugging purposes.

-    } catch {
+    } catch (error) {
+      console.error("Failed to delete sticky:", error);
       setToast({
         type: TOAST_TYPE.ERROR,
         title: "Warning!",
         message: "Something went wrong. Please try again later.",
       });
web/core/components/stickies/layout/stickies-loader.tsx (1)

5-44: LGTM! Well-structured loading skeleton.

The loader component effectively mimics the sticky note structure with appropriate spacing and layout. Good use of grid and flex layouts for responsive design.

A minor optimization suggestion: Consider extracting the repeated loader structure into a separate component for better maintainability.

const StickyLoader = () => (
  <Loader className="space-y-5 border border-custom-border-200 p-3 rounded">
    {/* ... existing loader structure ... */}
  </Loader>
);

export const StickiesLoader = () => (
  <div className="overflow-scroll pb-2 grid grid-cols-4 gap-4">
    {Array.from({ length: 4 }).map((_, index) => (
      <StickyLoader key={index} />
    ))}
  </div>
);
web/core/components/stickies/layout/stickies-list.tsx (2)

44-51: Optimize layout handling with useCallback.

The handleLayout function should be memoized to prevent unnecessary re-renders of child components.

- const handleLayout = () => {
+ const handleLayout = useCallback(() => {
    if (masonryRef.current) {
      // Force reflow
      masonryRef.current.performLayout();
    }
- };
+ }, []);

Line range hint 88-102: Extract empty state logic to a separate component.

The empty state conditional rendering is becoming complex and could benefit from being extracted into a dedicated component.

Consider creating a new component like this:

type StickiesEmptyStateProps = {
  isStickiesPage: boolean;
  searchQuery: string;
  onCreateSticky: () => void;
};

const StickiesEmptyStateWrapper: React.FC<StickiesEmptyStateProps> = ({
  isStickiesPage,
  searchQuery,
  onCreateSticky,
}) => {
  if (isStickiesPage || searchQuery) {
    return (
      <EmptyState
        type={searchQuery ? EmptyStateType.STICKIES_SEARCH : EmptyStateType.STICKIES}
        layout={searchQuery ? "screen-simple" : "screen-detailed"}
        primaryButtonOnClick={onCreateSticky}
        primaryButtonConfig={{ size: "sm" }}
      />
    );
  }
  return <StickiesEmptyState />;
};

This would simplify the main component and improve maintainability.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 22836ea and 848d355.

📒 Files selected for processing (7)
  • web/core/components/stickies/delete-modal.tsx (3 hunks)
  • web/core/components/stickies/layout/stickies-list.tsx (5 hunks)
  • web/core/components/stickies/layout/stickies-loader.tsx (1 hunks)
  • web/core/components/stickies/layout/sticky-dnd-wrapper.tsx (1 hunks)
  • web/core/components/stickies/modal/stickies.tsx (3 hunks)
  • web/core/components/stickies/sticky/inputs.tsx (1 hunks)
  • web/core/components/stickies/sticky/root.tsx (4 hunks)
🔇 Additional comments (7)
web/core/components/stickies/sticky/inputs.tsx (1)

Line range hint 15-19: Clarify the distinction between handleUpdate and handleChange.

The props have similar signatures but different async behaviors:

  • handleUpdate: synchronous, returns void
  • handleChange: asynchronous, returns Promise

This inconsistency could lead to confusion. Consider:

  1. Renaming them to better reflect their specific purposes
  2. Maintaining consistent async patterns

Let's verify the usage pattern of these handlers:

web/core/components/stickies/delete-modal.tsx (1)

10-10: LGTM! Good async handling.

The handleSubmit method is now properly typed as async, which better reflects its asynchronous nature.

web/core/components/stickies/modal/stickies.tsx (2)

31-33: LGTM! Improved visual hierarchy.

Good improvements to the title section with better text contrast and icon placement.


Line range hint 59-64: LGTM! Added semantic button type.

Good addition of type="button" attribute for better semantics.

web/core/components/stickies/sticky/root.tsx (2)

23-23: LGTM! Good prop addition.

The handleLayout prop is well integrated into the component's type definition and props destructuring.

Also applies to: 26-26


91-94: LGTM! Good update handling.

The update handler properly chains the layout update with the form save operation.

web/core/components/stickies/layout/sticky-dnd-wrapper.tsx (1)

27-36: Props type definition looks good but verify DND removal requirement.

The Props type is well-defined with proper TypeScript types. However, there seems to be an inconsistency with the PR objectives which mention DND removal, yet this component retains all drag-and-drop functionality.

Could you clarify if the DND functionality should be removed as mentioned in the PR objectives? If so, this component would need significant refactoring.

const { onClose, workspaceSlug, className = "", stickyId, showToolbar, handleLayout } = props;
// navigation
const pathName = usePathname();
// const pathName = usePathname();
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

Remove commented code.

There are several instances of commented-out code that should be removed to maintain code cleanliness:

  • Line 28: // const pathName = usePathname();
  • Line 37: // const isStickiesPage = pathName?.includes("stickies");
  • Line 81: // {isStickiesPage && <StickyItemDragHandle isDragging={false} />}{" "}
- // const pathName = usePathname();
- // const isStickiesPage = pathName?.includes("stickies");
- // {isStickiesPage && <StickyItemDragHandle isDragging={false} />}{" "}

Also applies to: 37-37, 81-81

Comment on lines +70 to +85
render: ({ container }) => {
const root = createRoot(container);
root.render(
<div className="scale-50">
<div className="-m-2 max-h-[150px]">
<StickyNote
className={"w-[290px]"}
workspaceSlug={workspaceSlug.toString()}
stickyId={stickyId}
showToolbar={false}
/>
</div>
);
return () => root.unmount();
},
nativeSetDragImage,
});
},
}),
dropTargetForElements({
element,
canDrop: ({ source }) => source.data?.type === "sticky",
getData: ({ input, element }) => {
const blockedStates: InstructionType[] = ["make-child"];
if (!isLastChild) {
blockedStates.push("reorder-below");
}
</div>
);
return () => root.unmount();
},
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

Fix potential memory leak in drag preview rendering.

The drag preview rendering using createRoot might lead to memory leaks. While the root is unmounted in the cleanup function, any resources created within the preview (like event listeners) might not be properly cleaned up.

Consider refactoring to:

  1. Move the preview component to a separate file
  2. Ensure all resources are cleaned up properly
  3. Use useCallback for the render function to prevent unnecessary re-renders
- render: ({ container }) => {
-   const root = createRoot(container);
-   root.render(
-     <div className="scale-50">
-       <div className="-m-2 max-h-[150px]">
-         <StickyNote
-           className={"w-[290px]"}
-           workspaceSlug={workspaceSlug.toString()}
-           stickyId={stickyId}
-           showToolbar={false}
-         />
-       </div>
-     </div>
-   );
-   return () => root.unmount();
- },
+ render: useCallback(({ container }) => {
+   const root = createRoot(container);
+   const Preview = () => (
+     <div className="scale-50">
+       <div className="-m-2 max-h-[150px]">
+         <StickyNote
+           className={"w-[290px]"}
+           workspaceSlug={workspaceSlug.toString()}
+           stickyId={stickyId}
+           showToolbar={false}
+         />
+       </div>
+     </div>
+   );
+   root.render(<Preview />);
+   return () => {
+     root.unmount();
+     // Add any additional cleanup here
+   };
+ }, [workspaceSlug, stickyId]),
📝 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
render: ({ container }) => {
const root = createRoot(container);
root.render(
<div className="scale-50">
<div className="-m-2 max-h-[150px]">
<StickyNote
className={"w-[290px]"}
workspaceSlug={workspaceSlug.toString()}
stickyId={stickyId}
showToolbar={false}
/>
</div>
);
return () => root.unmount();
},
nativeSetDragImage,
});
},
}),
dropTargetForElements({
element,
canDrop: ({ source }) => source.data?.type === "sticky",
getData: ({ input, element }) => {
const blockedStates: InstructionType[] = ["make-child"];
if (!isLastChild) {
blockedStates.push("reorder-below");
}
</div>
);
return () => root.unmount();
},
render: useCallback(({ container }) => {
const root = createRoot(container);
const Preview = () => (
<div className="scale-50">
<div className="-m-2 max-h-[150px]">
<StickyNote
className={"w-[290px]"}
workspaceSlug={workspaceSlug.toString()}
stickyId={stickyId}
showToolbar={false}
/>
</div>
</div>
);
root.render(<Preview />);
return () => {
root.unmount();
// Add any additional cleanup here
};
}, [workspaceSlug, stickyId]),

Comment on lines 109 to +110
{/* @ts-expect-error type mismatch here */}
<Masonry elementType="div">
<Masonry elementType="div" ref={masonryRef}>
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

Fix type mismatch in Masonry component.

The @ts-expect-error comment indicates a known type issue that should be properly addressed rather than suppressed.

Please investigate the type mismatch and consider:

  1. Updating the type definitions for the Masonry component
  2. Using a properly typed alternative
  3. Creating a proper type declaration file if one doesn't exist

const handleLayout = () => {
if (masonryRef.current) {
// Force reflow
masonryRef.current.performLayout();
Copy link
Contributor

Choose a reason for hiding this comment

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

@aaryan610 could you please let me know what is happening here? cant find mdn docs for it? going by your comment are you trying to force layout reflow? if that is the case it is usually not a good practice since it is better to always allow browser decide on forcing layout reflow

Copy link
Member Author

Choose a reason for hiding this comment

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

@gakshita can you please take this up?

Copy link
Collaborator

Choose a reason for hiding this comment

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

If the content addition in sticky was resulting in increment of height then the masonry library wasn't adjusting the layout, resulting in overlap of stickies. Therefore i am doing a force update.

@pushya22 pushya22 merged commit 58a4b45 into preview Jan 21, 2025
20 of 22 checks passed
@pushya22 pushya22 deleted the fix/stickies-bugs branch January 21, 2025 11:07
aaryan610 added a commit that referenced this pull request Apr 9, 2025
* fix: stickies bugs

* fix: sticky height fixed

---------

Co-authored-by: Aaryan Khandelwal <65252264+aaryan610@users.noreply.github.com>
Co-authored-by: gakshita <akshitagoyal1516@gmail.com>
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.

5 participants