Skip to content

Comments

Staging#712

Merged
MrgSub merged 10 commits intomainfrom
staging
Apr 18, 2025
Merged

Staging#712
MrgSub merged 10 commits intomainfrom
staging

Conversation

@MrgSub
Copy link
Collaborator

@MrgSub MrgSub commented Apr 18, 2025

Summary by CodeRabbit

  • New Features

    • Enhanced thread and email action handling in the context menu, enabling reply, reply-all, and forward actions with improved feedback and bulk selection support.
    • Composer mode is now managed via a single URL query parameter, simplifying the process of opening and closing reply, reply-all, and forward composers.
  • Bug Fixes

    • Ensured statistics data always returns an array, preventing potential errors when data is unavailable.
    • Improved error handling by performing a full sign-out and storage reset before redirecting to the login page on errors.
  • Refactor

    • Centralized compose mode state management, removing multiple boolean flags in favor of a single mode parameter.
    • Streamlined logic for composer open/close actions and thread selection.
  • Style

    • Minor formatting and whitespace cleanups in CSS for consistency.
  • Chores

    • Disabled mail list hotkeys by commenting out the relevant component.

@vercel
Copy link

vercel bot commented Apr 18, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
0 ✅ Ready (Inspect) Visit Preview 💬 Add feedback Apr 18, 2025 1:50am

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Apr 18, 2025

Walkthrough

This set of changes refactors state management for mail composer modes (reply, reply-all, forward) across multiple components by replacing individual boolean flags with a single mode query parameter. The reply composer, thread display, and context menu components now use this unified query state for mode control. The thread context menu is enhanced with functional handlers for thread and email actions, including improved bulk selection, user feedback, and query state updates for actions like reply, reply-all, and forward. Additional changes include improved error handling on the error page, minor CSS cleanup, and a small update to the useStats hook to ensure array return types.

Changes

File(s) Change Summary
apps/mail/app/error.tsx Updated "Try Again" button to clear IndexedDB, sign out, and redirect to login instead of simply retrying.
apps/mail/components/context/thread-context.tsx Refactored thread context menu to use query state for reply actions, enabled functional handlers for thread/email actions, improved bulk selection, and added user feedback via toasts.
apps/mail/components/mail/mail-list.tsx Removed immediate local state update in handleMailClick; now only updates the threadId query parameter.
apps/mail/components/mail/reply-composer.tsx Replaced multiple boolean flags for composer modes with a single mode query parameter; removed mode prop from ReplyCompose.
apps/mail/components/mail/thread-display.tsx Centralized compose mode state with mode query parameter; removed previous multi-flag state logic.
apps/mail/components/providers/hotkey-provider-wrapper.tsx Commented out <MailListHotkeys /> from rendered hotkey components; reordered imports.
apps/mail/components/create/prosemirror.css Minor formatting and whitespace cleanup; changed placeholder quotes to single; removed commented border style.
apps/mail/hooks/use-stats.ts Ensured data property always returns an array by using data ?? [].

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant ThreadContextMenu
    participant useQueryState
    participant ThreadDisplay
    participant ReplyCompose

    User->>ThreadContextMenu: Clicks Reply/Reply All/Forward
    ThreadContextMenu->>useQueryState: setMode('reply'|'replyAll'|'forward')
    useQueryState-->>ThreadDisplay: mode updated
    ThreadDisplay->>ReplyCompose: Render with current mode
    ReplyCompose->>useQueryState: Read mode to determine composer state
    User->>ReplyCompose: Closes composer
    ReplyCompose->>useQueryState: setMode(null)
Loading
sequenceDiagram
    participant User
    participant ErrorPage
    participant dexieStorageProvider
    participant signOut
    participant Browser

    User->>ErrorPage: Clicks "Try Again"
    ErrorPage->>dexieStorageProvider: clear()
    ErrorPage->>signOut: signOut()
    ErrorPage->>Browser: Redirect to /login
Loading

Possibly related PRs

  • Mail-0/Zero#711: Also modifies the error component to clear storage, sign out, and redirect to login, directly overlapping the changes in error.tsx.
  • Mail-0/Zero#708: Refactors ThreadContextMenu to use query state and adds functional handlers for reply actions, closely related to the context menu changes here.
  • Mail-0/Zero#597: Updates ThreadDisplay to use useQueryState for compose mode state, related to the state management refactor in this PR.

Poem

In the meadow of mail, where the queries hop free,
Composer modes now dance in sweet unity.
With a single "mode" flag, reply flows are bright,
Context menus sparkle, toasts pop with delight.
Errors now vanish with a sign-out and cheer—
This bunny’s code garden grows tidier each year!
🐇✨

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.
✨ 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.
    • 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.
  • @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: 3

🔭 Outside diff range comments (2)
apps/mail/components/mail/reply-composer.tsx (2)

146-163: ⚠️ Potential issue

Unused mail state – remove to avoid dead code

const [mail, setMail] = useMail(); (line 151) is no longer referenced after the refactor.
Leaving unused hooks will trigger ESLint/TS errors and causes an unnecessary re‑render when the global mail atom changes.


796-805: ⚠️ Potential issue

onBlur always writes to the “To” field – breaks Cc/Bcc editing

Inside RecipientInput the blur‑handler hard‑codes 'to' instead of using the current type, so blurring a Cc/Bcc input pushes the address into the wrong array.

- onBlur={(e) => handleAddEmail('to', e.currentTarget.value)}
+ onBlur={(e) => handleAddEmail(type, e.currentTarget.value)}

Without this fix users lose Cc/Bcc addresses and see duplicates in “To”.

@@
-            onBlur={(e) => handleAddEmail('to', e.currentTarget.value)}
+            onBlur={(e) => handleAddEmail(type, e.currentTarget.value)}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c41813e and a7d92c5.

📒 Files selected for processing (8)
  • apps/mail/app/error.tsx (2 hunks)
  • apps/mail/components/context/thread-context.tsx (6 hunks)
  • apps/mail/components/create/prosemirror.css (2 hunks)
  • apps/mail/components/mail/mail-list.tsx (0 hunks)
  • apps/mail/components/mail/reply-composer.tsx (7 hunks)
  • apps/mail/components/mail/thread-display.tsx (5 hunks)
  • apps/mail/components/providers/hotkey-provider-wrapper.tsx (2 hunks)
  • apps/mail/hooks/use-stats.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • apps/mail/components/mail/mail-list.tsx
🧰 Additional context used
🧬 Code Graph Analysis (2)
apps/mail/components/mail/thread-display.tsx (2)
apps/mail/components/mail/reply-composer.tsx (1)
  • ReplyCompose (146-1249)
apps/mail/lib/utils.ts (1)
  • cn (51-51)
apps/mail/components/mail/reply-composer.tsx (2)
apps/mail/hooks/use-threads.ts (1)
  • useThread (136-149)
apps/mail/components/mail/use-mail.ts (1)
  • useMail (23-25)
🔇 Additional comments (7)
apps/mail/components/providers/hotkey-provider-wrapper.tsx (1)

18-18:

Details

❓ Verification inconclusive

Verify the intended behavior of commented out MailListHotkeys

The MailListHotkeys component has been commented out. This appears to be part of the state management refactoring for mail composer modes. Please confirm if this is intentional or if it should be uncommented once the refactoring is complete.


🏁 Script executed:

#!/bin/bash
# Check if MailListHotkeys is used elsewhere or if there are any TODOs related to this
rg -A 3 -B 3 "MailListHotkeys" --type tsx

Length of output: 69


🏁 Script executed:

#!/bin/bash
# Retry searching for occurrences of MailListHotkeys without restricting by file type
rg "MailListHotkeys" -n .

Length of output: 338


Verify intentional removal of MailListHotkeys

I found that MailListHotkeys is still defined and exported here:

• apps/mail/lib/hotkeys/mail-list-hotkeys.tsx:13

and imported (but commented out) here:

• apps/mail/components/providers/hotkey-provider-wrapper.tsx:4, line 18

No other references or TODOs were located. Please confirm whether commenting out <MailListHotkeys /> was deliberate—if it should remain disabled, or if you plan to re‑enable it once the mail‑composer state refactor is complete.

apps/mail/components/create/prosemirror.css (3)

11-11: LGTM: Standardized quote usage in placeholder text

Changed double quotes to single quotes for consistency.


170-170: LGTM: Standardized heading size comments

Added clearer comments to indicate the text size utility class equivalents.

Also applies to: 177-177, 184-184


192-192: LGTM: Improved comment formatting

Standardized comment spacing for better readability.

apps/mail/hooks/use-stats.ts (1)

21-21: Good defensive programming with null coalescing operator

Using data ?? [] ensures an empty array is always returned even when data is null or undefined, preventing potential runtime errors when consuming code tries to iterate over the data array.

apps/mail/app/error.tsx (2)

4-5: LGTM: Added necessary imports for error recovery

Added imports for the sign-out and storage clearing functionality needed for the updated error recovery process.


24-34: Verify if this aggressive error recovery approach is appropriate

The error handling strategy has been significantly changed. Instead of simply calling the reset() function to retry the operation, the code now:

  1. Clears all IndexedDB storage
  2. Signs out the user
  3. Redirects to the login page

While this approach ensures a clean slate, it could be frustrating for users encountering minor recoverable errors, as they'll lose their session and need to log in again.

Consider if there are certain error types that could use a less drastic recovery approach:

- onClick={async () => {
-   await dexieStorageProvider().clear();
-   await signOut();
-   window.location.href = '/login';
- }}
+ onClick={async () => {
+   // For critical errors, reset everything
+   if (error.message.includes("critical") || error.name === "AuthError") {
+     await dexieStorageProvider().clear();
+     await signOut();
+     window.location.href = '/login';
+   } else {
+     // For non-critical errors, try the built-in reset
+     reset();
+   }
+ }}

Comment on lines +378 to 402
className={cn(mode === 'reply' && 'bg-primary/10')}
onClick={() => {
setMail((prev) => ({
...prev,
replyComposerOpen: true,
replyAllComposerOpen: false,
forwardComposerOpen: false,
}));
setMode('reply');
}}
/>
{hasMultipleParticipants && (
<ThreadActionButton
icon={ReplyAll}
label={t('common.threadDisplay.replyAll')}
disabled={!emailData}
className={cn(mail.replyAllComposerOpen && 'bg-primary/10')}
className={cn(mode === 'replyAll' && 'bg-primary/10')}
onClick={() => {
setMail((prev) => ({
...prev,
replyComposerOpen: false,
replyAllComposerOpen: true,
forwardComposerOpen: false,
}));
setMode('replyAll');
}}
/>
)}
<ThreadActionButton
icon={Forward}
label={t('common.threadDisplay.forward')}
disabled={!emailData}
className={cn(mail.forwardComposerOpen && 'bg-primary/10')}
className={cn(mode === 'forward' && 'bg-primary/10')}
onClick={() => {
setMail((prev) => ({
...prev,
replyComposerOpen: false,
replyAllComposerOpen: false,
forwardComposerOpen: true,
}));
setMode('forward');
}}
/>
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

⚠️ Potential issue

Ensure threadId is always present before opening the composer

All three click‑handlers set mode but never (re‑)set threadId.
If the current URL was entered directly (e.g. /mail/inbox/123) and therefore lacks the ?threadId= query param, ReplyCompose will read threadId === null and silently fail to fetch the thread – the composer opens with no data.

 onClick={() => {
-  setMode('reply');
+  setThreadId(id);   // keep the current thread in the query string
+  setMode('reply');
 }}

Consider doing the same for replyAll and forward, or wrapping this into a small helper to avoid repetition.

📝 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
className={cn(mode === 'reply' && 'bg-primary/10')}
onClick={() => {
setMail((prev) => ({
...prev,
replyComposerOpen: true,
replyAllComposerOpen: false,
forwardComposerOpen: false,
}));
setMode('reply');
}}
/>
{hasMultipleParticipants && (
<ThreadActionButton
icon={ReplyAll}
label={t('common.threadDisplay.replyAll')}
disabled={!emailData}
className={cn(mail.replyAllComposerOpen && 'bg-primary/10')}
className={cn(mode === 'replyAll' && 'bg-primary/10')}
onClick={() => {
setMail((prev) => ({
...prev,
replyComposerOpen: false,
replyAllComposerOpen: true,
forwardComposerOpen: false,
}));
setMode('replyAll');
}}
/>
)}
<ThreadActionButton
icon={Forward}
label={t('common.threadDisplay.forward')}
disabled={!emailData}
className={cn(mail.forwardComposerOpen && 'bg-primary/10')}
className={cn(mode === 'forward' && 'bg-primary/10')}
onClick={() => {
setMail((prev) => ({
...prev,
replyComposerOpen: false,
replyAllComposerOpen: false,
forwardComposerOpen: true,
}));
setMode('forward');
}}
/>
className={cn(mode === 'reply' && 'bg-primary/10')}
onClick={() => {
- setMode('reply');
+ setThreadId(id); // keep the current thread in the query string
+ setMode('reply');
}}
/>

Comment on lines +76 to 82
const {
data: { threads },
mutate,
isLoading,
isValidating,
} = useThreads();
const currentFolder = folder ?? '';
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

⚠️ Potential issue

useThreads() destructuring is unsafe – may throw when data is undefined

const {
  data: { threads },
  ...
} = useThreads();

If useThreads() returns { data: undefined, ... } during the initial fetch, the destructuring of threads will raise “Cannot destructure property ‘threads’ of undefined”.

Safer pattern:

-const { data: { threads }, mutate, isLoading, isValidating } = useThreads();
+const { data, mutate, isLoading, isValidating } = useThreads();
+const threads = data?.threads ?? [];

Update the downstream selectedThreads/isUnread/isStarred calculations accordingly.

Comment on lines +29 to 42
import { markAsRead, markAsUnread, toggleStar } from '@/actions/mail';
import { useThread, useThreads } from '@/hooks/use-threads';
import { useSearchValue } from '@/hooks/use-search-value';
import { useThreads } from '@/hooks/use-threads';
import { useParams, useRouter } from 'next/navigation';
import { modifyLabels } from '@/actions/mail';
import { LABELS, FOLDERS } from '@/lib/utils';
import { useStats } from '@/hooks/use-stats';
import { useParams } from 'next/navigation';
import { useMail } from '../mail/use-mail';
import { useTranslations } from 'use-intl';
import { type ReactNode } from 'react';
import { toast } from 'sonner';
import { modifyLabels } from '@/actions/mail';
import { markAsRead, markAsUnread, toggleStar } from '@/actions/mail';
import { useQueryState } from 'nuqs';
import { useMemo } from 'react';
import { toast } from 'sonner';

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

Incorrect import for useTranslations causes compile‑time crash

useTranslations is exported from next-intl, not use-intl. The wrong module path breaks the build.

-import { useTranslations } from 'use-intl';
+import { useTranslations } from 'next-intl';
📝 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 { markAsRead, markAsUnread, toggleStar } from '@/actions/mail';
import { useThread, useThreads } from '@/hooks/use-threads';
import { useSearchValue } from '@/hooks/use-search-value';
import { useThreads } from '@/hooks/use-threads';
import { useParams, useRouter } from 'next/navigation';
import { modifyLabels } from '@/actions/mail';
import { LABELS, FOLDERS } from '@/lib/utils';
import { useStats } from '@/hooks/use-stats';
import { useParams } from 'next/navigation';
import { useMail } from '../mail/use-mail';
import { useTranslations } from 'use-intl';
import { type ReactNode } from 'react';
import { toast } from 'sonner';
import { modifyLabels } from '@/actions/mail';
import { markAsRead, markAsUnread, toggleStar } from '@/actions/mail';
import { useQueryState } from 'nuqs';
import { useMemo } from 'react';
import { toast } from 'sonner';
import { markAsRead, markAsUnread, toggleStar } from '@/actions/mail';
import { useThread, useThreads } from '@/hooks/use-threads';
import { useSearchValue } from '@/hooks/use-search-value';
import { useParams, useRouter } from 'next/navigation';
import { modifyLabels } from '@/actions/mail';
import { LABELS, FOLDERS } from '@/lib/utils';
import { useStats } from '@/hooks/use-stats';
import { useMail } from '../mail/use-mail';
import { useTranslations } from 'next-intl';
import { type ReactNode } from 'react';
import { useQueryState } from 'nuqs';
import { useMemo } from 'react';
import { toast } from 'sonner';

@MrgSub MrgSub merged commit e6f2da7 into main Apr 18, 2025
4 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Jun 7, 2025
34 tasks
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.

2 participants