feat: add mailto protocol handler support#574
Conversation
|
@jlokos is attempting to deploy a commit to the Zero Team on Vercel. A member of the Team first needs to authorize it. |
|
Caution Review failedThe pull request is closed. WalkthroughThis pull request introduces mailto URL handling into the mail application. A new route processes mailto links by parsing URL parameters, creating email drafts, and managing user authentication with appropriate redirection. A new React compose page component handles mailto parameters by either redirecting to a dedicated handler or initializing the email creation form with provided values. The CreateEmail component is enhanced with email validation and default content generation utilities. Additionally, a protocol handler is registered in the MailLayout for browser-level mailto redirection. Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant MailRoute
participant AuthService
participant Parser
participant DraftService
User->>MailRoute: Send mailto request
MailRoute->>AuthService: Check authentication
alt Not Authenticated
AuthService-->>MailRoute: Authentication failed
MailRoute-->>User: Redirect to login page
else Authenticated
MailRoute->>Parser: parseMailtoUrl(mailto)
alt Parsing fails
Parser-->>MailRoute: null
MailRoute-->>User: Redirect to empty compose page
else Parsing succeeds
MailRoute->>DraftService: createDraftFromMailto(parsedData)
DraftService-->>MailRoute: Draft ID or error
alt Draft creation succeeds
MailRoute-->>User: Redirect to compose page with draftId
else Draft creation fails
MailRoute-->>User: Redirect to empty compose page
end
end
end
sequenceDiagram
participant User
participant ComposePage
participant AuthService
participant MailtoHandler
participant CreateEmail
User->>ComposePage: Access compose page with searchParams
ComposePage->>AuthService: Verify session
alt Session invalid
AuthService-->>ComposePage: Session invalid
ComposePage-->>User: Redirect to login
else Session valid
ComposePage-->>ComposePage: Await searchParams
alt searchParams.to starts with "mailto:"
ComposePage-->>MailtoHandler: Redirect to mailto handler with encoded `to`
else
ComposePage-->>CreateEmail: Render component with initial values
end
end
sequenceDiagram
participant MailLayout
participant Browser
MailLayout->>Browser: Check registerProtocolHandler support
alt Supported
Browser-->>MailLayout: Supported
MailLayout-->>Browser: Register mailto handler (redirect to compose)
else Not Supported
MailLayout-->>Browser: Log error / Skip registration
end
Possibly related PRs
Suggested reviewers
Poem
📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (1)
✨ Finishing Touches
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (9)
apps/mail/components/mail/mail.tsx (1)
278-299: Consider verifying secure contexts for protocol registration.The mailto protocol handler registration looks functional. However,
navigator.registerProtocolHandlerrequires a secure context (HTTPS) in most browsers. Consider verifying or documenting that this code path is only invoked over HTTPS to avoid potential registration failures on non-secure environments.apps/mail/app/(routes)/mail/compose/page.tsx (2)
6-14: Extend interface for additional mailto properties if needed.If you intend to handle cc, bcc, or multiple recipients in the future, consider extending the interface to capture those fields.
16-46: Sanitize user input for safe rendering.While the redirect to
/mail/compose/handle-mailtofilters out mailto URLs, other query fields such assubjectandbodycould contain characters requiring sanitization or encoding. Consider ensuring that the input is sanitized before rendering, especially if eventually displayed in the UI without HTML encoding.apps/mail/app/(routes)/mail/compose/handle-mailto/route.ts (3)
5-79: Consider more robust email parsing or multiple addressees.The current
parseMailtoUrlfunction handles a single email with a straightforward regex pattern. For broader mailto use cases (multiple addresses, “cc”/“bcc” fields, subdomains, plus signs, etc.), consider a more robust email parser or additional parameter handling.
81-127: Escape user-supplied content to prevent unexpected HTML injection.When constructing HTML content, body text is inserted directly without escaping. Although this is for an email draft, untrusted input might contain HTML or scripting elements. Consider escaping
<,>,&, etc., to prevent possible code injection in upstream or downstream usage.
129-162: Support additional mailto parameters.This handler redirects only after extracting basic fields. If future requirements include multiple recipients, cc, or bcc parameters, extend both the parser and the draft-creation logic accordingly.
apps/mail/components/create/create-email.tsx (3)
284-316: Consider consolidating initialization logic.There's duplication between the useState initializers and this useEffect. The component initializes email/subject/body values in two places: during useState initialization and in this useEffect.
Consider consolidating the initialization logic to avoid potential inconsistencies. Either:
- Use null/empty defaults in useState and do all initialization in useEffect, or
- Handle all initialization in useState and use the useEffect only for processing that depends on multiple state values
- const [toEmails, setToEmails] = React.useState<string[]>(initialTo ? [initialTo] : []); - const [subjectInput, setSubjectInput] = React.useState(initialSubject); - const [messageContent, setMessageContent] = React.useState(initialBody); + const [toEmails, setToEmails] = React.useState<string[]>([]); + const [subjectInput, setSubjectInput] = React.useState(''); + const [messageContent, setMessageContent] = React.useState(''); React.useEffect(() => { // Initialize all state from props here // ...existing code... - }, [initialTo, initialSubject, initialBody, defaultValue]); + }, [initialTo, initialSubject, initialBody]);
299-315: Simplify document creation using utility function.You've created a nice utility function for empty document creation but aren't using it consistently here.
if (initialBody && !defaultValue) { - setDefaultValue({ - type: 'doc', - content: [ - { - type: 'paragraph', - content: [ - { - type: 'text', - text: initialBody - } - ] - } - ] - }); + try { + const json = generateJSON(initialBody, [Document, Paragraph, Text, Bold]); + setDefaultValue(json); + } catch (error) { + console.error('Error parsing initial body in useEffect:', error); + // Create document with plain text fallback + const doc = createEmptyDocContent(); + if (doc.content && doc.content.length > 0) { + doc.content[0].content = [{ type: 'text', text: initialBody }]; + } + setDefaultValue(doc); + } setMessageContent(initialBody); }
285-293: Handle multiple recipient addresses correctly.The email handling for mailto links works properly but could be improved to handle multiple recipients more elegantly.
if (initialTo) { const emails = initialTo.split(',').map(email => email.trim()); const validEmails = emails.filter(email => isValidEmail(email)); if (validEmails.length > 0) { setToEmails(validEmails); - } else { + } + + // If we have any invalid emails, put them in the input field for the user to correct + const invalidEmails = emails.filter(email => !isValidEmail(email)); + if (invalidEmails.length > 0) { - setToInput(initialTo); + setToInput(invalidEmails.join(', ')); } }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
apps/mail/app/(routes)/mail/compose/handle-mailto/route.ts(1 hunks)apps/mail/app/(routes)/mail/compose/page.tsx(1 hunks)apps/mail/components/create/create-email.tsx(4 hunks)apps/mail/components/mail/mail.tsx(1 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
apps/mail/app/(routes)/mail/compose/page.tsx (1)
apps/mail/components/create/create-email.tsx (1)
CreateEmail(40-516)
🔇 Additional comments (6)
apps/mail/app/(routes)/mail/compose/page.tsx (1)
1-5: Imports look good.
No concerns here—clean setup and consistent with project structure.apps/mail/components/create/create-email.tsx (5)
25-28: Good email validation implementation.The email validation function uses a standard regex pattern that properly checks for basic email format requirements.
30-38: Good refactoring of document creation.Extracting this repeated document structure into a utility function improves maintainability and reduces duplication across the codebase.
40-48: Nice enhancement to support mailto parameters.The component signature has been properly updated to support the mailto protocol parameters, with appropriate default values and TypeScript typing.
50-57: Initial state values setup correctly.State initialization now properly uses the provided props, enabling pre-populated email forms from mailto links.
60-70: Good defensive programming for initialBody parsing.The code properly attempts to parse the initialBody with appropriate error handling and fallback to an empty document when parsing fails.
|
The latest updates on your projects. Learn more about Vercel for Git ↗︎
|
Implements proper handling of CC and BCC fields in mailto links, including: - Parsing CC and BCC values from mailto URLs - Adding CC and BCC headers to MIME messages when creating drafts - Extracting CC and BCC values from draft headers - Validating and sanitizing email addresses - Updating UI to display CC and BCC fields when values are present Enhances the existing mailto protocol handler support from PR Mail-0#574
Implements proper handling of CC and BCC fields in mailto links, including: - Parsing CC and BCC values from mailto URLs - Adding CC and BCC headers to MIME messages when creating drafts - Extracting CC and BCC values from draft headers - Validating and sanitizing email addresses - Updating UI to display CC and BCC fields when values are present Enhances the existing mailto protocol handler support from PR Mail-0#574
feat: add mailto protocol handler support
Description
This PR adds support for handling mailto protocol links in the 0.email application. When users click on mailto links in their browser, they can now choose to open them in 0.email. This implementation follows web standards for protocol handlers and provides a seamless experience when creating emails from external applications or websites.
Key features implemented:
Type of Change
Areas Affected
Testing Done
I've tested this implementation across multiple browsers and confirmed the protocol handler registration works correctly. The feature has been tested with various mailto link formats including:
Security Considerations
The implementation includes robust validation and sanitization of inputs from mailto URLs to prevent security issues. Email addresses are validated using regex patterns, and all mailto parameters are properly decoded and sanitized before use.
Checklist
Additional Notes
The implementation follows best practices for handling web protocols and maintains the existing UX patterns of the application. Code has been refactored to improve maintainability and reuse common functions across components.
Changes include:
isValidEmail,createEmptyDocContent)By submitting this pull request, I confirm that my contribution is made under the terms of the project's license.
Summary by CodeRabbit