Skip to content

Comments

Delete Draft #1246

Closed
Adarsh9977 wants to merge 24 commits intoMail-0:stagingfrom
Adarsh9977:zero/delete-draft
Closed

Delete Draft #1246
Adarsh9977 wants to merge 24 commits intoMail-0:stagingfrom
Adarsh9977:zero/delete-draft

Conversation

@Adarsh9977
Copy link
Contributor

@Adarsh9977 Adarsh9977 commented Jun 7, 2025

Aded delete draft functionality

This PR fix/complete https://feedback.0.email/p/unable-to-delete-draft-emails-in-zero-client

  • After
Screen.Recording.2025-06-08.at.4.41.04.AM.mov

Summary by CodeRabbit

  • New Features

    • Added the ability to delete draft emails, including support for bulk deletion.
    • Introduced a context menu for draft items with a delete option.
    • Drafts now disappear instantly upon deletion for a smoother user experience.
  • Bug Fixes

    • Draft UI correctly hides when a draft is deleted.
  • Localization

    • Added a new label for the delete draft action to the English locale.
  • Configuration

    • Introduced an environment variable to enable or disable draft deletion functionality.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 7, 2025

"""

Walkthrough

This change introduces optimistic deletion for draft emails in a mail application. It adds a context menu for drafts with a delete option, updates hooks and state management to support optimistic deletion, extends backend interfaces and APIs to handle draft deletions, and updates localization for the new action. Both single and bulk draft deletions are supported.

Changes

File(s) Change Summary
apps/mail/components/context/draft-context.tsx Added DraftContextMenu component for draft context menu with delete action.
apps/mail/components/mail/mail-list.tsx Wrapped draft display in DraftContextMenu; conditional rendering for optimistic UI; removed AnimatePresence.
apps/mail/components/mail/optimistic-thread-state.tsx Added 'DELETE' action handling to useOptimisticThreadState for hiding/removing drafts optimistically.
apps/mail/hooks/use-optimistic-actions.ts Added optimistic draft deletion logic, new PendingAction type, optimisticDeleteDrafts function.
apps/mail/store/optimistic-updates.ts Extended OptimisticAction type to include 'DELETE' for threads.
apps/mail/locales/en.json Added "deleteDraft" shortcut label to English locale.
apps/server/src/lib/driver/google.ts Added deleteDraft method to GoogleMailManager for Gmail draft deletion.
apps/server/src/lib/driver/types.ts Added deleteDraft method to MailManager interface.
apps/server/src/trpc/routes/mail.ts Added bulkDeleteDraft mutation procedure for deleting multiple drafts.
apps/mail/lib/optimistic-actions-manager.ts Extended PendingAction type to include 'DELETE' action variant.
.env.example Added environment variable VITE_PUBLIC_IS_DRAFT_DELETE_ENABLED=true.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant DraftContextMenu
    participant useOptimisticActions
    participant BackendAPI
    participant MailManager

    User->>DraftContextMenu: Right-click draft, select "Delete"
    DraftContextMenu->>useOptimisticActions: optimisticDeleteDrafts([draftId])
    useOptimisticActions->>useOptimisticThreadState: Set shouldHide, isRemoving = true
    useOptimisticActions->>BackendAPI: Call bulkDeleteDraft([draftId])
    BackendAPI->>MailManager: deleteDraft(draftId)
    MailManager-->>BackendAPI: Deletion result
    BackendAPI-->>useOptimisticActions: Success/Failure response
    useOptimisticActions->>useOptimisticThreadState: Finalize optimistic state
Loading

Possibly related PRs

  • Skeleton for drafts #1302: Adds a skeleton loader placeholder for drafts without modifying draft rendering logic or adding context menu or deletion features; related to draft rendering but addresses different aspects.

Suggested reviewers

  • ahmetskilinc
  • MrgSub

Poem

A draft once lingered, soon to be gone,
With a right-click menu, we move it along.
Optimistic bunnies, quick to erase,
Backend and frontend, both keep the pace.
"Delete!" cries the shortcut, with nary a fuss—
Now the drafts are all hopping off,
Leaving more inbox space for us! 🐇✨
"""


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 85df7e6 and 3f86053.

📒 Files selected for processing (1)
  • apps/mail/components/mail/mail-list.tsx (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/mail/components/mail/mail-list.tsx
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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: 2

🔭 Outside diff range comments (2)
apps/mail/hooks/use-optimistic-actions.ts (2)

367-402: ⚠️ Potential issue

Fix the syntax error in optimisticToggleImportant function.

The function is missing proper closure and the dependency array is misplaced. This is not a useCallback hook but a regular function.

   function optimisticToggleImportant(threadIds: string[], isImportant: boolean) {
     if (!threadIds.length) return;

     const optimisticId = addOptimisticAction({
       type: 'IMPORTANT',
       threadIds,
       important: isImportant,
     });

     createPendingAction({
       type: 'IMPORTANT',
       threadIds,
       params: { important: isImportant },
       optimisticId,
       execute: async () => {
         await toggleImportant({ ids: threadIds });

         if (mail.bulkSelected.length > 0) {
           setMail({ ...mail, bulkSelected: [] });
         }
       },
       undo: () => {
         removeOptimisticAction(optimisticId);
       },
       toastMessage: isImportant ? 'Marked as important' : 'Unmarked as important',
     });
-    },
-    [
-      addOptimisticAction,
-      createPendingAction,
-      mail,
-      removeOptimisticAction,
-      setMail,
-      toggleImportant,
-    ],
-  );
+  }
🧰 Tools
🪛 Biome (1.9.4)

[error] 393-402: Expected a statement but instead found ',
[
addOptimisticAction,
createPendingAction,
mail,
removeOptimisticAction,
setMail,
toggleImportant,
],
)'.

Expected a statement here.

(parse)


467-487: ⚠️ Potential issue

Fix the undoLastAction implementation.

The function has several issues that need to be addressed:

  1. It checks lastActionIdRef.current which is an unused ref
  2. Missing closing bracket and dependency array for useCallback
   const undoLastAction = useCallback(() => {
-    if (!lastActionIdRef.current) return;
+    if (!optimisticActionsManager.lastActionId) return;

     const lastAction = optimisticActionsManager.pendingActions.get(
       optimisticActionsManager.lastActionId,
     );
     if (!lastAction) return;

     lastAction.undo();

     optimisticActionsManager.pendingActions.delete(optimisticActionsManager.lastActionId);
     optimisticActionsManager.pendingActionsByType
       .get(lastAction.type)
       ?.delete(optimisticActionsManager.lastActionId);

     if (lastAction.toastId) {
       toast.dismiss(lastAction.toastId);
     }

     optimisticActionsManager.lastActionId = null;
-  }
+  }, []);
🧹 Nitpick comments (6)
apps/mail/components/mail/mail-list.tsx (1)

534-582: Consider simplifying the complex conditional rendering structure.

The Draft component refactor correctly integrates optimistic deletion state, but the nested conditional logic is quite complex and impacts readability.

Consider this cleaner structure:

  return (
-    draft ? (
-      <AnimatePresence mode="sync">
-        {!optimisticState.shouldHide && (<DraftContextMenu draftId={message.id}>
+    draft && !optimisticState.shouldHide ? (
+      <DraftContextMenu draftId={message.id}>
          <div className="select-none py-1" onClick={handleMailClick}>
            {/* draft content */}
          </div>
-        </DraftContextMenu> )}
-      </AnimatePresence>
-    ): null
+      </DraftContextMenu>
+    ) : null

Also, consider whether AnimatePresence is necessary here since you're only conditionally rendering based on shouldHide rather than animating transitions.

apps/server/src/trpc/routes/mail.ts (1)

321-339: Well-implemented bulk deletion with proper error handling.

The mutation correctly uses Promise.allSettled for concurrent operations and provides appropriate error handling. The implementation follows established patterns in the codebase.

Consider enhancing error details to include which specific draft IDs failed:

  const results = await Promise.allSettled(ids.map((id) => driver.deleteDraft(id)));
- const errors = results.filter((result) => result.status === 'rejected');
+ const failures = results
+   .map((result, index) => ({ result, draftId: ids[index] }))
+   .filter(({ result }) => result.status === 'rejected');
  if (errors.length > 0) {
-   return { success: false, error: 'Failed to delete some drafts', details: errors };
+   return { 
+     success: false, 
+     error: 'Failed to delete some drafts', 
+     failedIds: failures.map(f => f.draftId),
+     details: failures.map(f => f.result)
+   };
  }
apps/mail/components/context/draft-context.tsx (1)

1-11: Clean up unused imports.

Several context menu components are imported but not used in this file.

Remove the unused imports:

  import {
    ContextMenu,
    ContextMenuContent,
    ContextMenuItem,
-   ContextMenuSeparator,
-   ContextMenuShortcut,
-   ContextMenuSub,
-   ContextMenuSubContent,
-   ContextMenuSubTrigger,
    ContextMenuTrigger,
  } from '../ui/context-menu';
apps/mail/hooks/use-optimistic-actions.ts (3)

423-423: Remove debug console.log statement.

Debug logging should be removed before merging to production.

-          console.log("DELETING DRAFT FROM OPTIMISTIC", draftIds )

95-95: Remove all debug console.log statements.

Multiple debug logging statements should be removed throughout the file.

-    console.log('here Generated pending action ID:', pendingActionId);
-      console.log('here Creating new Set for action type:', type);
-    console.log(
-      'here',
-      'Added pending action to type:',
-      type,
-      'Current size:',
-      optimisticActionsManager.pendingActionsByType.get(type)?.size,
-    );
-        console.log('here', {
-          pendingActionsByTypeRef: optimisticActionsManager.pendingActionsByType.get(type)?.size,
-          pendingActionsRef: optimisticActionsManager.pendingActions.size,
-          typeActions: typeActions?.size,
-        });

Also applies to: 98-98, 102-108, 129-133


452-465: Consider optimizing the dependency array.

The optimisticDeleteDrafts callback has many dependencies which could cause frequent re-creations. Consider whether all these dependencies are necessary, particularly mail which might change frequently.

You might want to use mail more selectively or use a ref to avoid unnecessary re-renders:

+  const mailRef = useRef(mail);
+  mailRef.current = mail;

   const optimisticDeleteDrafts = useCallback(
     (draftIds: string[]) => {
       // ... existing code ...
-          if (mail.bulkSelected.length > 0) {
-            setMail({ ...mail, bulkSelected: [] });
+          if (mailRef.current.bulkSelected.length > 0) {
+            setMail({ ...mailRef.current, bulkSelected: [] });
           }

And remove mail from the dependency array.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8e9a1e3 and 533b0df.

📒 Files selected for processing (9)
  • apps/mail/components/context/draft-context.tsx (1 hunks)
  • apps/mail/components/mail/mail-list.tsx (2 hunks)
  • apps/mail/components/mail/optimistic-thread-state.tsx (1 hunks)
  • apps/mail/hooks/use-optimistic-actions.ts (5 hunks)
  • apps/mail/locales/en.json (1 hunks)
  • apps/mail/store/optimistic-updates.ts (1 hunks)
  • apps/server/src/lib/driver/google.ts (1 hunks)
  • apps/server/src/lib/driver/types.ts (1 hunks)
  • apps/server/src/trpc/routes/mail.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
apps/mail/components/mail/mail-list.tsx (3)
apps/mail/components/mail/optimistic-thread-state.tsx (1)
  • useOptimisticThreadState (7-80)
apps/mail/components/context/draft-context.tsx (1)
  • DraftContextMenu (24-58)
apps/mail/lib/utils.ts (1)
  • cn (51-51)
apps/server/src/trpc/routes/mail.ts (1)
apps/server/src/trpc/trpc.ts (1)
  • activeDriverProcedure (44-78)
apps/mail/hooks/use-optimistic-actions.ts (1)
apps/mail/lib/optimistic-actions-manager.ts (1)
  • PendingAction (1-10)
🪛 Biome (1.9.4)
apps/mail/hooks/use-optimistic-actions.ts

[error] 16-16: Shouldn't redeclare 'PendingAction'. Consider to delete it or rename it.

'PendingAction' is defined here:

(lint/suspicious/noRedeclare)


[error] 393-402: Expected a statement but instead found ',
[
addOptimisticAction,
createPendingAction,
mail,
removeOptimisticAction,
setMail,
toggleImportant,
],
)'.

Expected a statement here.

(parse)

🔇 Additional comments (6)
apps/server/src/lib/driver/types.ts (1)

52-52: Clean interface extension for draft deletion.

The method signature is well-designed and appropriately positioned among other draft-related methods in the interface.

apps/mail/locales/en.json (1)

462-462: Appropriate localization for draft deletion.

The label is clear and properly placed in the shortcuts actions section.

apps/mail/store/optimistic-updates.ts (1)

9-10: Well-structured optimistic action type for deletion.

The new DELETE action follows the established pattern and correctly uses threadIds array for consistency with the UI layer.

apps/server/src/lib/driver/google.ts (1)

589-602: Solid implementation following established patterns.

The deleteDraft method correctly implements the interface using the established error handling pattern and appropriate Gmail API calls. The implementation is consistent with other methods in the class.

apps/mail/components/mail/optimistic-thread-state.tsx (1)

66-69: LGTM! Clean implementation following existing patterns.

The DELETE case correctly sets both isRemoving and shouldHide flags, which is consistent with the MOVE action pattern and appropriate for deletion operations.

apps/mail/components/context/draft-context.tsx (1)

24-58: Well-designed context menu component with proper state management.

The component correctly handles both single and bulk draft deletion scenarios, and appropriately clears bulk selection state after deletion. The logic is clean and follows React best practices.

Copy link
Contributor

@ahmetskilinc ahmetskilinc left a comment

Choose a reason for hiding this comment

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

Hey great pr. I left 1 comment.

@Adarsh9977
Copy link
Contributor Author

Hey great pr. I left 1 comment.

Thank you @ahmetskilinc, fixed the requested changes. Please let me know if any update needed

Copy link
Collaborator

MrgSub commented Jun 10, 2025

Merge activity

  • Jun 10, 2:11 AM UTC: A user started a stack merge that includes this pull request via Graphite.
  • Jun 10, 2:11 AM UTC: Graphite couldn't merge this PR because it failed for an unknown reason (Stack merges are not currently supported for forked repositories. Please create a branch in the target repository in order to merge).

@Adarsh9977
Copy link
Contributor Author

@MrgSub ready to merge!

Copy link
Collaborator

@MrgSub MrgSub left a comment

Choose a reason for hiding this comment

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

Please add a flag to enable/disable this feature, i.e isDeleteDraftEnabled somewhere in the env

@Adarsh9977
Copy link
Contributor Author

@MrgSub Added the flag in env and tested. Working fine as expected.

@Adarsh9977
Copy link
Contributor Author

@MrgSub please take a look

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

🧹 Nitpick comments (1)
apps/mail/components/mail/mail-list.tsx (1)

41-41: Verify if the motion import is needed.

Based on the past review comments discussing animation removal and the fact that AnimatePresence was removed, this motion import appears to be unused in the current code. Consider removing it if it's not needed.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3c7d256 and 85df7e6.

📒 Files selected for processing (1)
  • apps/mail/components/mail/mail-list.tsx (4 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
apps/mail/components/mail/mail-list.tsx

[error] 646-646: Expected a property, a shorthand property, a getter, a setter, or a method but instead found '!optimisticState.shouldHide && (<DraftContextMenu draftId={message.id'.

Expected a property, a shorthand property, a getter, a setter, or a method here.

(parse)


[error] 690-690: expected ) but instead found <

Remove <

(parse)


[error] 691-691: Expected a semicolon or an implicit semicolon after a statement, but found none

An explicit or implicit semicolon is expected here...

...Which is required to end this statement

(parse)

🔇 Additional comments (3)
apps/mail/components/mail/mail-list.tsx (3)

31-31: LGTM!

The import of DraftContextMenu is correctly added and aligns with the draft deletion functionality implementation.


604-604: LGTM!

The integration of useOptimisticThreadState hook is correctly implemented and necessary for the optimistic deletion functionality.


600-693: Approve the optimistic deletion integration approach.

The overall approach to implement optimistic deletion is well-designed:

  1. Integration with useOptimisticThreadState for state management
  2. Conditional rendering based on shouldHide state
  3. Wrapping with DraftContextMenu for delete functionality

Once the syntax errors are resolved, this implementation will effectively support the draft deletion feature.

createPendingAction({
type: 'DELETE',
threadIds: draftIds,
params: { currentFoler: 'draft', isDraft: true },
Copy link
Contributor

Choose a reason for hiding this comment

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

There's a typo in the parameter name: currentFoler should be currentFolder.

Suggested change
params: { currentFoler: 'draft', isDraft: true },
params: { currentFolder: 'draft', isDraft: true },

Spotted by Diamond

Is this helpful? React 👍 or 👎 to let us know.

@github-actions
Copy link
Contributor

github-actions bot commented Aug 7, 2025

This PR has merge conflicts and has been open for more than 3 days. It will be automatically closed. Please resolve the conflicts and reopen the PR if you'd like to continue working on it.

@github-actions github-actions bot closed this Aug 7, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants