diff --git a/components/calendar/calendar-app.tsx b/components/calendar/calendar-app.tsx index 1263433fb..11a50836e 100644 --- a/components/calendar/calendar-app.tsx +++ b/components/calendar/calendar-app.tsx @@ -115,6 +115,7 @@ import { useLiteLinkSegments } from "@/hooks/use-lite-link-segments"; import { IS_LITE } from "@/lib/lite"; import { findMeetingLink } from "@/lib/event-links"; import { useDocumentTitle } from "@/hooks/use-document-title"; +import { useDesktopWindowName } from "@/lib/desktop/window-name"; import { useFocusTrap } from "@/hooks/use-focus-trap"; import { MvTopBar } from "@/components/layout/mv-top-bar"; import { useMountainViewShell } from "@/hooks/use-mountain-view-shell"; @@ -161,6 +162,7 @@ export function CalendarApp({ linkSegments: routeSegments }: CalendarAppProps = const tSidebar = useTranslations("sidebar"); const tOffline = useTranslations("calendar_offline"); useDocumentTitle(tSidebar("calendar")); + useDesktopWindowName(tSidebar("calendar"), { withAccount: true }); const skeletonLabels = useSkeletonLabels(); const tWebcalAction = useTranslations("calendar.webcal_action"); const { demoMode } = useConfig(); diff --git a/components/contacts/contacts-app.tsx b/components/contacts/contacts-app.tsx index 00e76d684..f59092a32 100644 --- a/components/contacts/contacts-app.tsx +++ b/components/contacts/contacts-app.tsx @@ -60,6 +60,7 @@ import { useDeepLinkUrl } from "@/hooks/use-deep-link-url"; import { useProInterfaceActive } from "@/components/pro/pro-interface-redirect"; import { useLiteLinkSegments } from "@/hooks/use-lite-link-segments"; import { useDocumentTitle } from "@/hooks/use-document-title"; +import { useDesktopWindowName } from "@/lib/desktop/window-name"; import { ContactsSkeleton, ContactsSkeletonBody } from "@/components/boot-skeleton/contacts-skeleton"; import { useSkeletonLabels } from "@/components/boot-skeleton/use-skeleton-labels"; import { useRegisterCommands } from "@/lib/command-registry"; @@ -110,6 +111,7 @@ function ContactsAppContent({ linkSegments: routeSegments }: ContactsAppProps = const tShell = useTranslations("shell"); const tMerge = useTranslations("ux_pim_cimport"); useDocumentTitle(tSidebar("contacts")); + useDesktopWindowName(tSidebar("contacts"), { withAccount: true }); const contactsEnabled = usePolicyStore((s) => s.isFeatureEnabled('contactsEnabled')); const { client, isAuthenticated, logout, checkAuth, isLoading: authLoading } = useAuthStore(); const { showAppsModal, inlineApp, loadedApps, handleManageApps, handleInlineApp, closeInlineApp, closeAppsModal } = useSidebarApps(); diff --git a/components/email/__tests__/composer-a11y.test.tsx b/components/email/__tests__/composer-a11y.test.tsx index f71f24a0d..437bb596a 100644 --- a/components/email/__tests__/composer-a11y.test.tsx +++ b/components/email/__tests__/composer-a11y.test.tsx @@ -253,6 +253,12 @@ describe('recipient fields (SR-06, CV-02)', () => { expect(screen.getByRole('list', { name: 'to:' })).toBeInTheDocument(); }); + // compose-p2-18: the ring outside the input was cut by the field's scroller. + it("draws the To field's keyboard focus ring inside it", () => { + render(); + expect(screen.getByRole('combobox', { name: 'to:' })).toHaveClass('focus-inset'); + }); + it('labels the subject field', () => { render(); expect(screen.getByLabelText('subject_label')).toBe(screen.getByTestId('composer-subject')); @@ -394,6 +400,21 @@ describe('moving a recipient by keyboard (MO-07)', () => { expect(liveRegion()).toHaveTextContent('recipient_moved:Anna Berg|cc'); }); + // compose-p2-16: a click did nothing visible, and Escape then closed the composer. + it('opens the chip menu on a click, and Escape closes only the menu', async () => { + const onClose = vi.fn(); + render(); + const chip = within(screen.getByRole('list', { name: 'to:' })).getByRole('listitem'); + fireEvent.click(chip.querySelector('.truncate')!); + + const move = await screen.findByTestId('recipient-move-bcc'); + fireEvent.keyDown(move, { key: 'Escape' }); + + await waitFor(() => expect(screen.queryByTestId('recipient-move-bcc')).toBeNull()); + expect(onClose).not.toHaveBeenCalled(); + expect(screen.getAllByRole('listitem')).toHaveLength(1); + }); + it('opens the chip menu with Shift+F10 too', async () => { render(); const chip = within(screen.getByRole('list', { name: 'to:' })).getByRole('listitem'); diff --git a/components/email/__tests__/composer-attachment-list-scroll.test.tsx b/components/email/__tests__/composer-attachment-list-scroll.test.tsx index 04bc59023..c4fe570c2 100644 --- a/components/email/__tests__/composer-attachment-list-scroll.test.tsx +++ b/components/email/__tests__/composer-attachment-list-scroll.test.tsx @@ -259,6 +259,16 @@ describe('attachment list', () => { expect(row.className).toContain('max-h-['); }); + // compose-p2-11: 5.25rem showed two rows of 2rem chips and half a third. + it('is as high as whole rows of chips, so none is cut in half', () => { + render(); + + const heights = [...chipRow().className.matchAll(/max-h-\[([\d.]+)rem\]/g)].map((m) => Number(m[1])); + expect(heights.length).toBeGreaterThan(0); + // n rows of 2rem chips with 0.5rem gaps: 2.5n - 0.5. + for (const height of heights) expect(Number.isInteger((height + 0.5) / 2.5)).toBe(true); + }); + it('says how many files and how much they weigh', () => { render(); diff --git a/components/email/__tests__/composer-discard-uploads.test.tsx b/components/email/__tests__/composer-discard-uploads.test.tsx index 36cfc0199..cf1960591 100644 --- a/components/email/__tests__/composer-discard-uploads.test.tsx +++ b/components/email/__tests__/composer-discard-uploads.test.tsx @@ -1,5 +1,5 @@ import React, { StrictMode, useState } from 'react'; -import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react'; +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { NextIntlClientProvider } from 'next-intl'; import { EmailComposer, type ComposerDraftData } from '@/components/email/email-composer'; @@ -134,9 +134,10 @@ async function openComposer(strict = false) { add: async (...files: File[]) => { fireEvent.change(document.querySelector('input[type="file"]')!, { target: { files } }); await advance(); }, - dialog: (control: Control) => { + // The bin asks nothing (compose-p2-10). + discard: (control: Control) => { fireEvent.click(screen.getByTestId(control === 'toolbar' ? 'composer-discard' : 'composer-close')); - return within(screen.getByRole('alertdialog')); + expect(screen.queryByRole('alertdialog')).toBeNull(); }, reopen: async () => { act(() => reopen()); await advance(); }, }; @@ -167,7 +168,7 @@ describe('explicit Discard with pending attachment uploads', () => { void upload.mock.results[0].value.then(settled, settled); expect([...resources.files.values()].map(f => f.name)).toEqual(['A.txt']); expect(resources.progress.size).toBe(1); - fireEvent.click(c.dialog(control).getByRole('button', { name: /^Discard$/ })); await advance(); + c.discard(control); await advance(); await c.reopen(); await c.add(file('B.txt')); await complete(1); expectNewComposer(); @@ -197,17 +198,6 @@ describe('explicit Discard with pending attachment uploads', () => { expect(resources.files.size).toBe(0); expect(resources.progress.size).toBe(0); expectNewComposer(); expect(c.closed).toHaveBeenCalledOnce(); }); - - it('keeps active and queued uploads when the close/discard dialog is cancelled', async () => { - const uploaded = vi.spyOn(emailHooks.onAfterAttachmentUpload, 'emit'); - const c = await openComposer(strict); await c.add(file('A.txt'), file('C.txt')); - const dialog = c.dialog(control); - expect(UploadXHR.instances[0].abort).not.toHaveBeenCalled(); - fireEvent.click(dialog.getByRole('button', { name: /^Cancel$/ })); await advance(); - await complete(0); expect(UploadXHR.instances[1].body?.name).toBe('C.txt'); await complete(1); - expect(uploaded.mock.calls.map(([attachment]) => attachment.name)).toEqual(['A.txt', 'C.txt']); - expect(c.closed).not.toHaveBeenCalled(); expect(resources.files.size).toBe(0); expect(resources.progress.size).toBe(0); - }); }); it.each(['saveFile', 'getFile', 'deleteFile'] as const)('cancels while asynchronous %s is pending', async method => { @@ -234,7 +224,7 @@ describe('explicit Discard with pending attachment uploads', () => { await c.add(file('A.txt'), file('C.txt')); if (method === 'deleteFile') await complete(0); expect(entered).toHaveBeenCalledOnce(); - fireEvent.click(c.dialog('toolbar').getByRole('button', { name: /^Discard$/ })); await advance(); + c.discard('toolbar'); await advance(); await c.reopen(); await act(async () => { gate.resolve(); }); await advance(); await c.add(file('B.txt')); await complete(UploadXHR.instances.findIndex(xhr => xhr.body?.name === 'B.txt')); diff --git a/components/email/__tests__/composer-discard.test.tsx b/components/email/__tests__/composer-discard.test.tsx index 4df7b6d90..bc90773ee 100644 --- a/components/email/__tests__/composer-discard.test.tsx +++ b/components/email/__tests__/composer-discard.test.tsx @@ -1,4 +1,4 @@ -import { render, screen, fireEvent, within } from '@testing-library/react'; +import { render, screen, fireEvent } from '@testing-library/react'; import { describe, it, expect, vi, beforeEach } from 'vitest'; import React from 'react'; import { EmailComposer } from '../email-composer'; @@ -7,6 +7,8 @@ import { EmailComposer } from '../email-composer'; const editorKeyDown = vi.hoisted(() => vi.fn()); const toastError = vi.hoisted(() => vi.fn()); +const discardWithUndo = vi.hoisted(() => vi.fn()); +vi.mock('@/lib/compose/draft-close-toast', () => ({ discardWithUndo, showDraftSavedToast: vi.fn() })); vi.mock('@/components/email/rich-text-editor', () => ({ RichTextEditor: () => React.createElement('div', { @@ -209,27 +211,56 @@ const REOPENED_DRAFT = { describe('composer Discard button', () => { beforeEach(() => { + discardWithUndo.mockClear(); toastError.mockClear(); updateSetting.mockClear(); editorKeyDown.mockClear(); }); - it('deletes a reopened draft without unsaved changes after confirming', async () => { + // compose-p2-10: no question; "Draft discarded" with Undo, as the toast's Discard. + it('closes at once and deletes a reopened draft once Undo is over', () => { const onDiscardDraft = vi.fn(); const onClose = vi.fn(); render(); fireEvent.click(screen.getByText('discard')); - const dialog = await screen.findByRole('alertdialog'); - expect(within(dialog).getByText('discard_draft_title')).toBeInTheDocument(); - // The user already chose to discard; there is nothing to save. - expect(within(dialog).queryByText('save')).toBeNull(); - - fireEvent.click(within(dialog).getByText('discard')); + expect(screen.queryByRole('alertdialog')).toBeNull(); + expect(onClose).toHaveBeenCalledTimes(1); + expect(discardWithUndo).toHaveBeenCalledTimes(1); + const [commit, labels] = discardWithUndo.mock.calls[0]; + expect(labels).toEqual({ discarded: 'draft_discarded', undo: 'undo' }); + // Not before the Undo time is over. + expect(onDiscardDraft).not.toHaveBeenCalled(); + commit(); expect(onDiscardDraft).toHaveBeenCalledWith('draft-1', { accountId: undefined, localAccountId: undefined }); }); + it('brings the text back on Undo, and deletes nothing', () => { + const onDiscardDraft = vi.fn(); + const onRestoreDiscarded = vi.fn(); + render( {}} />); + + fireEvent.click(screen.getByText('discard')); + const restore = discardWithUndo.mock.calls[0][2] as () => void; + restore(); + + expect(onRestoreDiscarded).toHaveBeenCalledWith(expect.objectContaining({ subject: 'Lunch', draftId: 'draft-1', to: 'bob@example.com' })); + expect(onDiscardDraft).not.toHaveBeenCalled(); + }); + + it('has the main window say it for a composer in its own window', () => { + const onDraftDiscarded = vi.fn(); + const onDiscardDraft = vi.fn(); + render( {}} />); + + fireEvent.click(screen.getByText('discard')); + + expect(onDraftDiscarded).toHaveBeenCalledWith('draft-1', { accountId: undefined, localAccountId: undefined }); + expect(discardWithUndo).not.toHaveBeenCalled(); + expect(onDiscardDraft).not.toHaveBeenCalled(); + }); + it('closes an empty, never saved composer without asking', () => { const onDiscardDraft = vi.fn(); const onClose = vi.fn(); diff --git a/components/email/__tests__/composer-own-window.test.tsx b/components/email/__tests__/composer-own-window.test.tsx index 2731b6a23..d6d312db5 100644 --- a/components/email/__tests__/composer-own-window.test.tsx +++ b/components/email/__tests__/composer-own-window.test.tsx @@ -112,6 +112,15 @@ function target(shown = true): ComposerPopOut & { handed: ComposerDraftData[]; c const DRAFT: ComposerDraftData = { to: '', cc: '', bcc: '', subject: 'Old', body: '', showCc: false, showBcc: false, selectedIdentityId: null, subAddressTag: '', mode: 'compose', draftId: null }; +describe('"Move to the main window" in quick compose', () => { + it('shows an arrow going in, not the arrows of leaving full screen', () => { + mount({ popOut: vi.fn(() => target()), popOutToMainLabel: 'Move to the main window' }); + const svg = screen.getByTestId('composer-back-to-main').querySelector('svg'); + expect(svg?.getAttribute('class')).toContain('tabler-icon-login'); + expect(svg?.getAttribute('class')).not.toContain('minimize'); + }); +}); + describe('"Open in new window" on a composer', () => { it('is not there without the host offering it: browsers stay as they are', () => { mount({}); diff --git a/components/email/__tests__/composer-plugin-surfaces.test.tsx b/components/email/__tests__/composer-plugin-surfaces.test.tsx index 817a277ad..66357fe00 100644 --- a/components/email/__tests__/composer-plugin-surfaces.test.tsx +++ b/components/email/__tests__/composer-plugin-surfaces.test.tsx @@ -1,4 +1,4 @@ -import { act, createEvent, fireEvent, render, screen } from '@testing-library/react'; +import { act, createEvent, fireEvent, render, screen, within } from '@testing-library/react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import React from 'react'; import { EmailComposer } from '../email-composer'; @@ -332,7 +332,7 @@ describe('composer-send-menu', () => { }); // compose-23: a menu with "Schedule send" as its only item. - it('opens the schedule dialog straight from the arrow when it is the only entry', () => { + it('opens the schedule dialog straight from the arrow when it is the only entry', async () => { useAuthStore.setState({ client: { hasDelayedSend: () => true, getMaxDelayedSend: () => 30 * 86400, createDraft: vi.fn() } as never, }); @@ -343,7 +343,24 @@ describe('composer-send-menu', () => { fireEvent.click(arrow); expect(screen.queryByRole('menuitem', { name: /schedule_send/ })).toBeNull(); - expect(screen.getByRole('dialog')).toHaveTextContent('schedule_send_description'); + // After the send checks, which found nothing here (compose-p2-14). + expect(await screen.findByRole('dialog')).toHaveTextContent('schedule_send_description'); + }); + + // compose-p2-14: the checks opened on top of the picked time and said + // "Send anyway" though nothing was sent then. + it('runs the send checks before the schedule dialog, and says "Schedule anyway"', async () => { + useAuthStore.setState({ + client: { hasDelayedSend: () => true, getMaxDelayedSend: () => 30 * 86400, createDraft: vi.fn() } as never, + }); + render(); + + fireEvent.click(screen.getAllByRole('button', { name: 'schedule_send' })[0]); + const warnings = await screen.findByRole('alertdialog'); + expect(screen.queryByText('schedule_send_description')).toBeNull(); + fireEvent.click(within(warnings).getByRole('button', { name: 'schedule_anyway' })); + + expect(await screen.findByText('schedule_send_description')).toBeInTheDocument(); }); it('keeps a plain Send button without plugin entries or scheduled send', () => { diff --git a/components/email/__tests__/composer-reply-focus.test.tsx b/components/email/__tests__/composer-reply-focus.test.tsx index 62bb0752e..8ac680ecf 100644 --- a/components/email/__tests__/composer-reply-focus.test.tsx +++ b/components/email/__tests__/composer-reply-focus.test.tsx @@ -1,4 +1,4 @@ -import { render, act } from '@testing-library/react'; +import { render, act, fireEvent, screen } from '@testing-library/react'; import { describe, it, expect, vi, beforeEach } from 'vitest'; import React from 'react'; import { EmailComposer } from '../email-composer'; @@ -9,17 +9,27 @@ import { useSettingsStore } from '@/stores/settings-store'; const toastError = vi.hoisted(() => vi.fn()); const editorFocus = vi.hoisted(() => vi.fn()); +const caret = vi.hoisted(() => ({ textEnd: null as number | null, selected: [] as number[], focused: 0 })); // Reports a stub editor as ready, the way the real one does once mounted. vi.mock('@/components/email/rich-text-editor', () => ({ RichTextEditor: ({ onEditorReady }: { onEditorReady?: (editor: unknown) => void }) => { React.useEffect(() => { - onEditorReady?.({ commands: { focus: editorFocus, setContent: () => {} }, isDestroyed: false }); + const chain = { + setTextSelection: (pos: number) => { caret.selected.push(pos); return chain; }, + focus: () => { caret.focused += 1; return chain; }, + run: () => true, + }; + onEditorReady?.({ commands: { focus: editorFocus, setContent: () => {} }, isDestroyed: false, isEditable: true, state: {}, chain: () => chain, on: () => {}, off: () => {} }); }, [onEditorReady]); return React.createElement('div', { 'data-testid': 'rich-text-editor' }); }, })); +vi.mock('@/components/email/reply-quote-collapse', async (importOriginal) => ({ + ...(await importOriginal()), + userTextEnd: () => caret.textEnd, +})); vi.mock('@/components/plugins/plugin-slot', () => ({ PluginSlot: () => null })); vi.mock('@/components/ui/avatar', () => ({ Avatar: () => null })); vi.mock('@/components/identity/sub-address-helper', () => ({ SubAddressHelper: () => null })); @@ -234,3 +244,41 @@ describe('composer initial focus', () => { expect(document.activeElement?.tagName).toBe('TEXTAREA'); }); }); + +// compose-p2-9: the white space under the text is the message too. +describe('a click in the empty space under the text', () => { + beforeEach(() => { + editorFocus.mockClear(); + caret.textEnd = null; + caret.selected = []; + caret.focused = 0; + useSettingsStore.setState({ plainTextMode: false }); + }); + + const emptySpace = () => screen.getByTestId('rich-text-editor').parentElement!.parentElement!; + + it('puts the caret at the end of the text above the folded quote', () => { + caret.textEnd = 7; + render(); + editorFocus.mockClear(); + const event = fireEvent.mouseDown(emptySpace(), { button: 0 }); + expect(event).toBe(false); + expect(caret.selected).toEqual([7]); + expect(caret.focused).toBe(1); + }); + + it('puts the caret at the end of the body when nothing is folded', () => { + render(); + fireEvent.mouseDown(emptySpace(), { button: 0 }); + expect(editorFocus).toHaveBeenCalledWith('end'); + }); + + it('leaves clicks on buttons alone', () => { + caret.textEnd = 7; + render(); + const button = document.createElement('button'); + emptySpace().appendChild(button); + fireEvent.mouseDown(button, { button: 0 }); + expect(caret.selected).toEqual([]); + }); +}); diff --git a/components/email/__tests__/composer-template-reply.test.tsx b/components/email/__tests__/composer-template-reply.test.tsx index d2d5abc3e..bcb2f5b92 100644 --- a/components/email/__tests__/composer-template-reply.test.tsx +++ b/components/email/__tests__/composer-template-reply.test.tsx @@ -147,8 +147,9 @@ vi.mock('@/stores/contact-store', () => { // ─── Misc dependency mocks ──────────────────────────────────────────────────── +const toastSuccess = vi.hoisted(() => ({ calls: [] as unknown[][] })); vi.mock('@/stores/toast-store', () => ({ - toast: { info: () => {}, error: () => {}, success: () => {} }, + toast: { info: () => {}, error: () => {}, success: (...args: unknown[]) => { toastSuccess.calls.push(args); } }, })); vi.mock('@/lib/plugin-hooks', () => ({ @@ -341,6 +342,17 @@ describe('applying a template to a reply (#911)', () => { expect(screen.queryByTestId('quick-save-template')).not.toBeInTheDocument(); }); + // compose-p2-15: the dialog closed with no sign the template was kept. + it('says "Template saved"', async () => { + useTemplateStore.setState({ templates: [] }); + toastSuccess.calls = []; + await openReply(); + const dialog = await openNameDialog(); + fireEvent.change(within(dialog).getByLabelText('template_name'), { target: { value: 'Quick answer' } }); + fireEvent.click(within(dialog).getByText('save')); + await waitFor(() => expect(toastSuccess.calls).toContainEqual(['template_saved'])); + }); + it('carries the name over into the full editor', async () => { await openReply(); const dialog = await openNameDialog(); diff --git a/components/email/__tests__/composer-windows-layout.test.tsx b/components/email/__tests__/composer-windows-layout.test.tsx index a5a5dd5a4..9c03feea7 100644 --- a/components/email/__tests__/composer-windows-layout.test.tsx +++ b/components/email/__tests__/composer-windows-layout.test.tsx @@ -232,6 +232,8 @@ describe('full screen', () => { expect(root).toHaveAttribute('data-maximized'); expect(root.className).toMatch(/(^|\s)fixed(\s|$)/); expect(root.className).toContain('inset-0'); + // The folder sidebar sits at z-50 (compose-p2-5): at 40 it covered the composer's left part. + expect(root.className).toMatch(/(^|\s)z-50(\s|$)/); fireEvent.click(screen.getByRole('button', { name: 'restore' })); expect(root).not.toHaveAttribute('data-maximized'); diff --git a/components/email/__tests__/reply-quote-collapse.test.ts b/components/email/__tests__/reply-quote-collapse.test.ts index 86c22986c..eeb00d1a8 100644 --- a/components/email/__tests__/reply-quote-collapse.test.ts +++ b/components/email/__tests__/reply-quote-collapse.test.ts @@ -5,7 +5,7 @@ import Paragraph from '@tiptap/extension-paragraph'; import { trailingParagraphBreakRule } from '../paragraph-breaks'; import { QuotedHtml, buildQuotedHtmlBlock, serializeEditorContent } from '../quoted-html'; import { SignatureBlock, buildSignatureBlock } from '../signature-block'; -import { ReplyQuoteCollapse, markReplyQuoteHeader } from '../reply-quote-collapse'; +import { ReplyQuoteCollapse, markReplyQuoteHeader, userTextEnd } from '../reply-quote-collapse'; const HEADER = markReplyQuoteHeader('
On Monday, Bob wrote:
'); const ORIGINAL = '

Original message

Earlier reply
'; @@ -168,3 +168,49 @@ describe('reply quote visibility', () => { expect(toggle()).toHaveAttribute('aria-expanded', 'false'); }); }); + +// compose-p2-3: a click under the folded quote used to put the caret on the +// empty last line, below the hidden original, where the text went unseen. +describe('a click in a reply with a folded quote', () => { + const click = (e: Editor, pos: number) => { + let handled = false; + e.view.someProp('handleClick', (handler) => { handled = handler(e.view, pos, new MouseEvent('click')) || handled; return handled; }); + return handled; + }; + const lastPos = (e: Editor) => e.state.doc.content.size - 1; + + it('puts the caret at the end of the text above the quote', () => { + const e = mount(); + expect(e.state.doc.lastChild?.type.name).toBe('paragraph'); + expect(click(e, lastPos(e))).toBe(true); + expect(e.state.selection.from).toBe(1 + 'My response'.length); + expect(toggle()).toHaveAttribute('aria-expanded', 'false'); + }); + + it('keeps the click where it was once the quote is shown', () => { + const e = mount(); + toggle().click(); + expect(click(e, lastPos(e))).toBe(false); + }); + + it('keeps a click on a line the user can see below the quote', () => { + const e = mount(`

My response

${HEADER}${QUOTE}

Postscript

`); + expect(click(e, lastPos(e) - 2)).toBe(false); + }); + + it('keeps a click in the text above the quote', () => { + const e = mount(); + expect(click(e, 3)).toBe(false); + }); + + it.each(['above', 'below'])('ends the text before a signature %s the quote', (position) => { + const signature = buildSignatureBlock('My signature'); + const e = mount(`

My response

${position === 'above' ? signature : ''}${HEADER}${QUOTE}${position === 'below' ? signature : ''}`); + expect(userTextEnd(e.state)).toBe(1 + 'My response'.length); + }); + + it('has no end of text in a body with neither quote nor signature', () => { + const e = mount('

Just text

'); + expect(userTextEnd(e.state)).toBeNull(); + }); +}); diff --git a/components/email/__tests__/rich-text-editor-link-dialog.test.tsx b/components/email/__tests__/rich-text-editor-link-dialog.test.tsx index c15a51ce4..23d7ac5a2 100644 --- a/components/email/__tests__/rich-text-editor-link-dialog.test.tsx +++ b/components/email/__tests__/rich-text-editor-link-dialog.test.tsx @@ -29,11 +29,50 @@ describe('Insert link', () => { fireEvent.click(screen.getByTitle('link')); expect(prompt).not.toHaveBeenCalled(); - const dialog = screen.getByRole('dialog', { name: 'insert_link' }); - fireEvent.change(dialog.querySelector('input')!, { target: { value: 'example.com/docs' } }); + screen.getByRole('dialog', { name: 'insert_link' }); + expect(screen.getByRole('textbox', { name: 'link_text' })).toHaveValue('docs'); + fireEvent.change(screen.getByRole('textbox', { name: 'link' }), { target: { value: 'example.com/docs' } }); fireEvent.click(screen.getByRole('button', { name: 'save' })); - expect(editor.getHTML()).toContain('href="https://example.com/docs"'); + expect(editor.getHTML()).toContain('docs here'); + }); + + // compose-p2-7: with nothing selected Save used to add nothing. + it('inserts the text as a link when nothing is selected', async () => { + const editor = await setup('

See it

'); + act(() => { editor.commands.setTextSelection(4); }); + + fireEvent.click(screen.getByTitle('link')); + expect(screen.getByRole('textbox', { name: 'link_text' })).toHaveValue(''); + fireEvent.change(screen.getByRole('textbox', { name: 'link_text' }), { target: { value: 'our docs' } }); + fireEvent.change(screen.getByRole('textbox', { name: 'link' }), { target: { value: 'example.com/docs' } }); + fireEvent.click(screen.getByRole('button', { name: 'save' })); + + expect(editor.getHTML()).toMatch(/See]*href="https:\/\/example\.com\/docs"[^>]*>our docs<\/a> it/); + }); + + it('shows the address as the link when the text is left empty', async () => { + const editor = await setup('

See it

'); + act(() => { editor.commands.setTextSelection(4); }); + + fireEvent.click(screen.getByTitle('link')); + fireEvent.change(screen.getByRole('textbox', { name: 'link' }), { target: { value: 'https://example.com' } }); + fireEvent.click(screen.getByRole('button', { name: 'save' })); + + expect(editor.getHTML()).toMatch(/See
]*href="https:\/\/example\.com"[^>]*>https:\/\/example\.com<\/a> it/); + }); + + it('edits the text of a link the caret is in', async () => { + const editor = await setup('

docs here

'); + act(() => { editor.commands.setTextSelection(2); }); + + fireEvent.click(screen.getByTitle('link')); + expect(screen.getByRole('textbox', { name: 'link_text' })).toHaveValue('docs'); + expect(screen.getByRole('textbox', { name: 'link' })).toHaveValue('https://example.com'); + fireEvent.change(screen.getByRole('textbox', { name: 'link_text' }), { target: { value: 'the docs' } }); + fireEvent.click(screen.getByRole('button', { name: 'save' })); + + expect(editor.getHTML()).toMatch(/]*href="https:\/\/example\.com"[^>]*>the docs<\/a> here/); }); it('opens on Ctrl+K in the text, as in Gmail, Outlook and Word', async () => { diff --git a/components/email/__tests__/thread-conversation-drafts.test.tsx b/components/email/__tests__/thread-conversation-drafts.test.tsx new file mode 100644 index 000000000..80bc7f7ed --- /dev/null +++ b/components/email/__tests__/thread-conversation-drafts.test.tsx @@ -0,0 +1,54 @@ +// compose-p2-6: on a phone the conversation listed a reply draft as an +// ordinary message, expanded at the top with Reply, Reply all and Forward. +// It is marked Draft and offers Edit and Discard instead. +import { describe, expect, it, vi } from 'vitest'; +import { fireEvent, render, screen } from '@testing-library/react'; + +vi.mock('@/hooks/use-wopi-status', () => ({ useWopiStatus: () => ({ enabled: false }), canWopiOpen: () => false })); +vi.mock('@/hooks/use-own-domain-address', () => ({ useOwnDomainAddress: () => () => false })); +vi.stubGlobal('ResizeObserver', class { observe() {} unobserve() {} disconnect() {} }); + +const { ThreadConversationView } = await import('@/components/email/thread-conversation-view'); + +const base = { + threadId: 't1', mailboxIds: { inbox: true }, to: [{ email: 'me@example.org' }], + subject: 's', size: 1, hasAttachment: false, htmlBody: [], textBody: [], attachments: [], bodyValues: {}, +}; +const received = { ...base, id: 'e1', keywords: { $seen: true }, from: [{ name: 'Ann', email: 'ann@t.example' }], receivedAt: '2026-11-01T10:00:00Z', preview: 'question' }; +const draft = { ...base, id: 'd1', keywords: { $seen: true, $draft: true }, from: [{ name: 'Me', email: 'me@example.org' }], receivedAt: '2026-11-02T10:00:00Z', preview: 'my answer' }; + +function renderView(handlers: Record) { + render( + {}} + onReply={() => {}} + onReplyAll={() => {}} + onForward={() => {}} + {...handlers} + />, + ); +} + +describe('a draft in a phone conversation', () => { + it('is marked Draft, and the newest received message is the one open', () => { + renderView({}); + expect(screen.getAllByTestId('conversation-draft-label')).toHaveLength(1); + // Only the received message is open, with its Reply. + expect(screen.getAllByRole('button', { name: /email_viewer.reply$/ })).toHaveLength(1); + expect(screen.queryByRole('button', { name: /email_viewer.edit_draft/ })).toBeNull(); + }); + + it('offers Edit and Discard instead of Reply once opened', () => { + const onEditDraft = vi.fn(); + const onDiscardDraft = vi.fn(); + renderView({ onEditDraft, onDiscardDraft }); + fireEvent.click(screen.getByText('my answer')); + expect(screen.getAllByRole('button', { name: /email_viewer.reply$/ })).toHaveLength(1); + fireEvent.click(screen.getByRole('button', { name: /email_viewer.edit_draft/ })); + fireEvent.click(screen.getByRole('button', { name: /email_composer.discard/ })); + expect(onEditDraft).toHaveBeenCalledWith(expect.objectContaining({ id: 'd1' })); + expect(onDiscardDraft).toHaveBeenCalledWith(expect.objectContaining({ id: 'd1' })); + }); +}); diff --git a/components/email/__tests__/viewer-quick-reply-back.test.tsx b/components/email/__tests__/viewer-quick-reply-back.test.tsx index 24daa4e08..df22850a8 100644 --- a/components/email/__tests__/viewer-quick-reply-back.test.tsx +++ b/components/email/__tests__/viewer-quick-reply-back.test.tsx @@ -63,19 +63,6 @@ describe('quick reply', () => { }); }); -// mail-p2-12: toasts covered the right half of the quick reply box. -describe('quick reply and toasts', () => { - it('counts as a bottom bar, so toasts sit above it', async () => { - document.documentElement.style.removeProperty('--bottom-controls-height'); - const { unmount } = render(); - await act(async () => { await new Promise((r) => setTimeout(r, 30)); }); - expect(document.querySelector('[data-quick-reply-box]')).not.toBeNull(); - expect(document.documentElement.style.getPropertyValue('--bottom-controls-height')).not.toBe(''); - unmount(); - expect(document.documentElement.style.getPropertyValue('--bottom-controls-height')).toBe(''); - }); -}); - // mail-p2-8: Undo send on a quick reply brings its text back into this box. describe('quick reply after Undo send', () => { it('takes the undone text back into the box of the message it answered', async () => { diff --git a/components/email/__tests__/viewer-quick-reply-words.test.tsx b/components/email/__tests__/viewer-quick-reply-words.test.tsx index f980a7c93..2262a4ba1 100644 --- a/components/email/__tests__/viewer-quick-reply-words.test.tsx +++ b/components/email/__tests__/viewer-quick-reply-words.test.tsx @@ -85,3 +85,18 @@ describe('quick reply wording', () => { expect(onReply).toHaveBeenCalledWith('Thanks, will do'); }); }); + +// compose-p2-17: the toasts lift over the box by its height (toast.tsx). +describe('quick reply box and the toasts', () => { + it('marks the box and gives the page its height, and takes both back when it goes', async () => { + const height = vi.spyOn(HTMLElement.prototype, 'offsetHeight', 'get').mockReturnValue(96); + const { unmount } = render(); + await act(async () => { await new Promise((r) => setTimeout(r, 10)); }); + + expect(document.querySelector('[data-quick-reply-box]')).not.toBeNull(); + expect(document.documentElement.style.getPropertyValue('--quick-reply-height')).toBe('96px'); + unmount(); + expect(document.documentElement.style.getPropertyValue('--quick-reply-height')).toBe(''); + height.mockRestore(); + }); +}); diff --git a/components/email/__tests__/viewer-reply-draft.test.tsx b/components/email/__tests__/viewer-reply-draft.test.tsx new file mode 100644 index 000000000..b3dd05f39 --- /dev/null +++ b/components/email/__tests__/viewer-reply-draft.test.tsx @@ -0,0 +1,82 @@ +import { render, act, fireEvent, screen } from '@testing-library/react'; +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import type { Email, Mailbox } from '@/lib/jmap/types'; +import { clearAllHooks } from '@/lib/plugin-hooks'; +import { useAuthStore } from '@/stores/auth-store'; + +// compose-p2-6: a reply saved as a draft was nowhere to be seen on the +// message it answers. The reader shows it under the message, marked Draft, +// with Edit and Discard, where the quick reply box would be. + +vi.mock('next-intl', () => ({ + useTranslations: () => (key: string, values?: Record) => + values ? `${key}:${JSON.stringify(values)}` : key, + useLocale: () => 'en', + useFormatter: () => ({ + dateTime: (d: Date | string) => String(d), + relativeTime: (d: Date | string) => String(d), + number: (n: number) => String(n), + }), +})); +vi.mock('@/hooks/use-media-query', () => ({ + useDeviceDetection: () => ({ isMobile: false, isTablet: false, isDesktop: true }), + useMediaQuery: () => false, +})); +vi.mock('@/components/tour/tour-provider', () => ({ + useTour: () => ({ activeTour: null, startTour: vi.fn(), endTour: vi.fn(), registerStep: vi.fn() }), +})); +vi.mock('@/components/plugins/plugin-slot', () => ({ PluginSlot: () => null })); +vi.mock('@/hooks/use-plugin-slot-offers', () => ({ usePluginSlotOffers: () => [] })); +vi.stubGlobal('ResizeObserver', class { observe() {} unobserve() {} disconnect() {} }); + +const { EmailViewer } = await import('../email-viewer'); + +const mailboxes = [ + { id: 'inbox', name: 'Inbox', role: 'inbox', parentId: null, myRights: { mayAddItems: true } }, +] as unknown as Mailbox[]; + +const message = { + id: 'm1', blobId: 'b1', threadId: 't1', mailboxIds: { inbox: true }, keywords: { $seen: true }, + from: [{ name: 'Ben Carter', email: 'ben.carter@example.com' }], to: [{ name: 'Me', email: 'me@example.org' }], + subject: 'Hello', receivedAt: '2026-01-01T00:00:00Z', preview: 'Hello', hasAttachment: false, size: 100, + textBody: [{ partId: '1', type: 'text/plain' }], htmlBody: [{ partId: '1', type: 'text/plain' }], attachments: [], + bodyValues: { '1': { value: 'Plain body' } }, +} as unknown as Email; + +beforeEach(() => { + clearAllHooks(); + useAuthStore.setState({ identities: [{ id: 'me', email: 'me@example.org', name: 'Me' }] } as never); +}); + +async function renderViewer(replyDraft: { preview?: string; onEdit: () => void; onDiscard: () => void } | null) { + render(); + await act(async () => { await new Promise((r) => setTimeout(r, 10)); }); +} + +describe('a reply draft under its message', () => { + it('shows Draft with its text, Edit and Discard, instead of the quick reply box', async () => { + const onEdit = vi.fn(); + const onDiscard = vi.fn(); + await renderViewer({ preview: 'my answer', onEdit, onDiscard }); + const card = screen.getByTestId('reply-draft'); + expect(card.textContent).toContain('draft'); + expect(card.textContent).toContain('my answer'); + expect(screen.queryByPlaceholderText(/^quick_reply_to/)).toBeNull(); + fireEvent.click(screen.getByTestId('reply-draft-edit')); + fireEvent.click(screen.getByTestId('reply-draft-discard')); + expect(onEdit).toHaveBeenCalledTimes(1); + expect(onDiscard).toHaveBeenCalledTimes(1); + }); + + // compose-p2-17: toasts lift over it as over the quick reply box. + it('counts as the quick reply box for the toasts', async () => { + await renderViewer({ preview: 'my answer', onEdit: vi.fn(), onDiscard: vi.fn() }); + expect(screen.getByTestId('reply-draft')).toHaveAttribute('data-quick-reply-box'); + }); + + it('keeps the quick reply box when there is none', async () => { + await renderViewer(null); + expect(screen.queryByTestId('reply-draft')).toBeNull(); + expect(screen.getByPlaceholderText(/^quick_reply_to/)).toBeTruthy(); + }); +}); diff --git a/components/email/email-composer.tsx b/components/email/email-composer.tsx index 71bfccf51..dd5845507 100644 --- a/components/email/email-composer.tsx +++ b/components/email/email-composer.tsx @@ -38,6 +38,7 @@ import { Minimize2, Trash2, ExternalLink, + LogIn, ReplyAll, Reply, Forward, @@ -69,10 +70,10 @@ import { buildReplySubject, buildForwardSubject } from "@/lib/subject-prefix"; import { isFilePreviewable } from "@/lib/file-preview"; import { isEditableEventTarget } from "@/lib/keyboard"; import { isSingleKeyShortcutOff } from "@/lib/single-key-shortcuts"; -import { markReplyQuoteHeader } from "@/components/email/reply-quote-collapse"; +import { markReplyQuoteHeader, userTextEnd } from "@/components/email/reply-quote-collapse"; import { attachmentIcon } from "@/components/email/attachment-chips"; import { attachmentsForDisplay } from "@/lib/compose/attachment-order"; -import { showDraftSavedToast } from "@/lib/compose/draft-close-toast"; +import { discardWithUndo, showDraftSavedToast } from "@/lib/compose/draft-close-toast"; import { buildQuotedHtmlBlock, serializeEditorContent } from "@/components/email/quoted-html"; import { containsEmbeddedSignature } from "@/components/email/signature-block"; import { @@ -414,6 +415,11 @@ interface EmailComposerProps { */ onDiscardDraft?: (draftId: string, draft?: { accountId?: string; localAccountId?: string }) => void; onSaveState?: (data: ComposerDraftData) => void; + /** + * Undo after the bin: opens a composer again with what this one held. The + * draft on the server is still there then. + */ + onRestoreDiscarded?: (data: ComposerDraftData) => void; /** * Offers "Open in new window". Called in the click, since a browser only * opens a window for a user action: the host opens it and answers with what @@ -453,6 +459,8 @@ interface EmailComposerProps { * this one is gone before a toast here could be read. */ onDraftKept?: (draftId: string, where: { accountId?: string; localAccountId?: string }) => void; + /** The bin closed the window: another window says "Draft discarded" with Undo, and deletes it after. */ + onDraftDiscarded?: (draftId: string, where: { accountId?: string; localAccountId?: string }) => void; }; /** The subject as typed, for a host that shows it (a Pro compose tab's title). */ onSubjectChange?: (subject: string) => void; @@ -615,6 +623,7 @@ export function EmailComposer({ requestCloseRef, onDiscardDraft, onSaveState, + onRestoreDiscarded, popOut, popOutToMainLabel, docked = false, @@ -1271,7 +1280,9 @@ export function EmailComposer({ const [previewAttachment, setPreviewAttachment] = useState(null); // What the checks before sending found (no subject, no text, placeholders, // a missing attachment, open proofreading issues), asked about in one dialog. - const [sendWarnings, setSendWarnings] = useState<{ items: SendWarning[]; delayedUntil?: string } | null>(null); + // `schedule`: asked before the schedule dialog, which opens on "Schedule anyway". + const [sendWarnings, setSendWarnings] = useState<{ items: SendWarning[]; delayedUntil?: string; schedule?: boolean } | null>(null); + const checkThenScheduleRef = useRef<() => void>(() => {}); // Open proofreading issues, once a checker asked to warn about them. const proofreadingConfirmedRef = useRef(false); const [showScheduleDialog, setShowScheduleDialog] = useState(false); @@ -1467,6 +1478,19 @@ export function EmailComposer({ // when the user switches identity in "above quote" mode without rebuilding // the whole body (which would lose user edits to the surrounding draft). const editorRef = useRef(null); + // The white space under the text is the message too (compose-p2-9): a + // click there puts the caret at the end of the user's text, above a folded + // quote and the signature, instead of dropping the focus. + const focusBodyFromEmptySpace = (event: React.MouseEvent) => { + const editor = editorRef.current; + const target = event.target as HTMLElement; + if (event.button !== 0 || !editor || editor.isDestroyed || !editor.isEditable) return; + if (target.closest('.ProseMirror, button, input, textarea, select, a, label, [role="toolbar"], [role="dialog"], [data-plugin-slot]')) return; + event.preventDefault(); + const end = userTextEnd(editor.state); + if (end === null) editor.commands.focus('end'); + else editor.chain().setTextSelection(end).focus().run(); + }; // Set while the composer itself swaps the signature in the editor. const signatureSwapRef = useRef(false); // Set once a reply's body got its initial focus, so switching formats later @@ -1557,9 +1581,11 @@ export function EmailComposer({ // eslint-disable-next-line react-hooks/exhaustive-deps }, [signatureIdentity?.id, signatureContent, signatureSeparatorEnabled, signaturePosition, mode, plainTextMode, pluginSignatureRevision, autoSignatureEnabled]); + // The send checks run first, so they don't open on top of the picked time + // saying "Send anyway" when nothing is sent now (compose-p2-14). const openScheduleDialog = useCallback(() => { - setShowScheduleDialog(true); closeSendMenu(); + checkThenScheduleRef.current(); }, [closeSendMenu]); // `autoSelectReplyIdentity` fused two behaviours: matching one of the user's @@ -1854,9 +1880,13 @@ export function EmailComposer({ const addTrustedSender = useSettingsStore((s) => s.addTrustedSender); const trustedSendersAddressBook = useSettingsStore((s) => s.trustedSendersAddressBook); // "Save as template" keeps it with the account the message is written from. + // It says so: the dialog closing was the only sign before (compose-p2-15). const addTemplate = useCallback( - (data: Parameters['add']>[0]) => personalTemplatesFor(composingAccountId).add(data), - [composingAccountId], + (data: Parameters['add']>[0]) => { + personalTemplatesFor(composingAccountId).add(data); + toast.success(tSend('template_saved')); + }, + [composingAccountId, tSend], ); // The admin may leave users only organisation and team templates. const composingTemplates = useTemplateSources(composingAccountId); @@ -3848,10 +3878,12 @@ export function EmailComposer({ else editor.commands.focus(); }; - const handleSend = async ({ warningsConfirmed = false, delayedUntil }: { + const handleSend = async ({ warningsConfirmed = false, delayedUntil, checkOnly = false }: { /** "Send anyway" in the warnings dialog: don't check those again. */ warningsConfirmed?: boolean; delayedUntil?: string; + /** Only the checks, then the schedule dialog instead of a send. */ + checkOnly?: boolean; } = {}) => { if (isSendingRef.current) return; @@ -3998,10 +4030,14 @@ export function EmailComposer({ } if (warnings.length > 0) { - setSendWarnings({ items: warnings, delayedUntil }); + setSendWarnings({ items: warnings, delayedUntil, ...(checkOnly ? { schedule: true } : {}) }); return; } } + if (checkOnly) { + setShowScheduleDialog(true); + return; + } // Checks other features register (lib/outgoing/send-pipeline.ts), such // as the external-recipient confirm. They may ask the user, so a second @@ -4486,6 +4522,8 @@ export function EmailComposer({ }; + checkThenScheduleRef.current = () => void handleSend({ checkOnly: true }); + // A host can hand a follow-up to requestCloseRef - "close this session, then // do that". It runs only once the composer really closes, never when the // guard dialog is cancelled, and never before onClose has had its say. @@ -4694,11 +4732,14 @@ export function EmailComposer({ title={popOutToMainLabel ?? tWindows('open_in_window')} data-testid={popOutToMainLabel ? "composer-back-to-main" : "composer-open-in-window"} > - {popOutToMainLabel ? : } + {/* Into the main window: an arrow going in, not the inward arrows of leaving full screen. */} + {popOutToMainLabel ? : } ); - const handleDiscardAndClose = () => { + // `keepDraft`: the bin's discard, which deletes the draft once its Undo is + // over, not here. + const handleDiscardAndClose = ({ keepDraft = false }: { keepDraft?: boolean } = {}) => { cancelSaveAndClose(); sendCancelledRef.current = true; explicitCloseRef.current = true; @@ -4716,7 +4757,7 @@ export function EmailComposer({ // From belongs to: switching From doesn't move the draft until it is // saved again, and the same id names another message on another server. const discardedDraftId = draftIdRef.current; - if (discardedDraftId && onDiscardDraft) { + if (discardedDraftId && onDiscardDraft && !keepDraft) { onDiscardDraft(discardedDraftId, { accountId: draftAccountIdRef.current, localAccountId: draftLocalAccountIdRef.current, @@ -4752,6 +4793,11 @@ export function EmailComposer({ // Discard deletes the draft, also one that has no unsaved changes, such as // a scheduled message reopened with "Cancel and edit". It used to share the // X button's path, which closed such a composer and kept the draft. + // It asks nothing (compose-p2-10): the composer goes at once with "Draft + // discarded · Undo", as Discard on the "Draft saved" toast does, and the + // draft is deleted once Undo is no longer offered. Undo brings the composer + // back with its text where the host can; elsewhere the last saved draft + // stays in Drafts. A window of its own has the main window say it. const handleDiscardClick = () => { if (saveCloseAttemptRef.current?.saving) return; cancelSaveAndClose(); @@ -4760,7 +4806,22 @@ export function EmailComposer({ return; } afterCloseRef.current = null; - openCloseDialog('discard'); + const draftId = draftIdRef.current; + const where = { accountId: draftAccountIdRef.current, localAccountId: draftLocalAccountIdRef.current }; + const snapshot = snapshotStateRef.current(); + const discard = onDiscardDraft; + const restore = onRestoreDiscarded; + const windowDiscarded = ownWindowRef.current?.onDraftDiscarded; + handleDiscardAndClose({ keepDraft: true }); + if (windowDiscarded) { + if (draftId) windowDiscarded(draftId, where); + return; + } + discardWithUndo( + () => { if (draftId) discard?.(draftId, where); }, + { discarded: tUx('draft_discarded'), undo: tUx('undo') }, + restore ? () => restore(snapshot) : undefined, + ); }; // X, Escape, another message, a host's tab: one rule, as drafts save @@ -4962,7 +5023,8 @@ export function EmailComposer({ "flex h-full bg-background relative", className, // Over everything but dialogs (z-60) and toasts; below the desktop app's window controls. - maximized && "fixed inset-0 z-40 h-auto pt-[var(--titlebar-row-height)]", + // At the folder sidebar's z-50 and after it in the page, so over it (compose-p2-5). + maximized && "fixed inset-0 z-50 h-auto pt-[var(--titlebar-row-height)]", )} data-maximized={maximized || undefined} onKeyDownCapture={handleComposerKeyDown} @@ -5515,7 +5577,7 @@ export function EmailComposer({ -
+
{wantsPluginDraft && ( )} @@ -5647,12 +5709,13 @@ export function EmailComposer({

)}
{attachmentsForDisplay(attachments).map(({ att, index }) => { @@ -6156,7 +6219,8 @@ export function EmailComposer({ setShowScheduleDialog(false)} - onSchedule={(delayedUntil) => handleSend({ delayedUntil })} + // Checked before the dialog opened (openScheduleDialog). + onSchedule={(delayedUntil) => handleSend({ delayedUntil, warningsConfirmed: true })} supported={!!composerClient?.hasDelayedSend()} maxDelayedSend={composerClient?.getMaxDelayedSend() ?? 0} disabled={!canSend || isSending || isSavingAndClosing} @@ -6167,6 +6231,7 @@ export function EmailComposer({ { const first = sendWarnings?.items[0]; setSendWarnings(null); @@ -6184,7 +6249,7 @@ export function EmailComposer({ }} onSendAnyway={(dontAskAgain) => { if (!sendWarnings) return; - const { items, delayedUntil } = sendWarnings; + const { items, delayedUntil, schedule } = sendWarnings; for (const warning of items) { if (warning.kind === 'subject') { emptySubjectConfirmedRef.current = true; @@ -6199,7 +6264,8 @@ export function EmailComposer({ } } setSendWarnings(null); - handleSend({ warningsConfirmed: true, delayedUntil }); + if (schedule) setShowScheduleDialog(true); + else handleSend({ warningsConfirmed: true, delayedUntil }); }} /> @@ -6215,7 +6281,7 @@ export function EmailComposer({ - {closeDialogKind === 'close' && ( @@ -6828,6 +6894,14 @@ export function RecipientChipInput({ !isEditing && "focus:outline-none focus:ring-2 focus:ring-primary focus:border-primary" )} onContextMenu={isEditing ? undefined : (e) => handleContextMenu(e, i, chip)} + // A click opens the chip's menu too (address, Edit, Move to, + // Remove), as Gmail and Outlook do; it did nothing visible. + onClick={isEditing ? undefined : (e) => { + if (e.target instanceof Element && e.target.closest('button')) return; + // Not on to the field, whose click puts the caret in the input. + e.stopPropagation(); + openChipMenu(i); + }} data-invalid={isInvalid || undefined} title={isInvalid ? t('invalid_recipient') : undefined} role="listitem" @@ -6944,7 +7018,10 @@ export function RecipientChipInput({ onKeyDown={handleKeyDown} onPaste={handlePaste} onBlur={handleBlur} - className="flex-1 min-w-[120px] border-0 outline-none h-7 text-sm bg-transparent text-foreground placeholder:text-muted-foreground [&::-webkit-search-cancel-button]:appearance-none [&::-webkit-search-decoration]:appearance-none" + // focus-inset: the keyboard focus ring goes inside the box. Drawn + // outside, the field's own scroller cut it to a line along the top + // and the end (compose-p2-18, a pop-out focuses To from a key). + className="focus-inset flex-1 min-w-[120px] border-0 outline-none h-7 text-sm bg-transparent text-foreground placeholder:text-muted-foreground [&::-webkit-search-cancel-button]:appearance-none [&::-webkit-search-decoration]:appearance-none" role="combobox" aria-expanded={activeAutoField === field && autocompleteResults.length > 0} aria-autocomplete="list" diff --git a/components/email/email-viewer.tsx b/components/email/email-viewer.tsx index cfa9d09b3..02879d38d 100644 --- a/components/email/email-viewer.tsx +++ b/components/email/email-viewer.tsx @@ -310,6 +310,11 @@ interface EmailViewerProps { mvInlineComposer?: React.ReactNode; /** A reply or forward to this message is open under it: no quick reply box as well. */ replyComposerOpen?: boolean; + /** + * A reply to this message saved as a draft (compose-p2-6): shown under it, + * marked Draft, with Edit and Discard, in place of the quick reply box. + */ + replyDraft?: { preview?: string; onEdit: () => void; onDiscard: () => void } | null; onEditDraft?: () => void; onCancelScheduledForEdit?: () => void; /** Stop a scheduled message from going out; it goes back to Drafts. */ @@ -1468,6 +1473,7 @@ export function EmailViewer({ onForwardConversationEmail, mvInlineComposer, replyComposerOpen, + replyDraft, onEditDraft, onCancelScheduledForEdit, onCancelScheduledSend, @@ -1492,6 +1498,7 @@ export function EmailViewer({ const tWindows = useTranslations('pwaWindows'); const tComposer = useTranslations('email_composer'); const tWords = useTranslations('compose_words'); + const tList = useTranslations('email_list'); const tNotifications = useTranslations('notifications'); const tCommon = useTranslations('common'); const tFiles = useTranslations('files'); @@ -1827,16 +1834,7 @@ export function EmailViewer({ const [quickReplyText, setQuickReplyText] = useState(""); const quickReplyRef = useRef(null); const [isQuickReplyFocused, setIsQuickReplyFocused] = useState(false); - const quickReplyBoxRef = useRef(null); - // Toasts ("Archived · Undo", "Sending in 5 seconds") sit above the quick - // reply box while it is on screen, not over it (mail-p2-12). - const [quickReplyBoxShown, setQuickReplyBoxShown] = useState(false); - const quickReplyBarRef = useBottomControls(quickReplyBoxShown); - const setQuickReplyBox = useCallback((el: HTMLDivElement | null) => { - quickReplyBoxRef.current = el; - setQuickReplyBoxShown(!!el); - quickReplyBarRef(el); - }, [quickReplyBarRef]); + const quickReplyBoxRef = useRef(null); // Focused, the box grows by its buttons: bring them up, they'd sit below the fold. useEffect(() => { if (isQuickReplyFocused) quickReplyBoxRef.current?.scrollIntoView?.({ block: 'nearest' }); @@ -3705,8 +3703,25 @@ export function EmailViewer({ return () => { cancelAnimationFrame(frame); clearTimeout(timer); }; }, [replyComposerOpen, email?.id]); // eslint-disable-line react-hooks/exhaustive-deps -- once per reply opened - const showQuickReply = !!email && quickReplyEnabled && !mvReplyRow && !replyComposerOpen && !isDraft && !isScheduled && !isBodyLoading && !isInJunkFolder + const showReplyDraft = !!email && !!replyDraft && !mvReplyRow && !replyComposerOpen && !isDraft && !isScheduled; + const showQuickReply = !!email && quickReplyEnabled && !mvReplyRow && !replyComposerOpen && !showReplyDraft && !isDraft && !isScheduled && !isBodyLoading && !isInJunkFolder && (!effectiveEmailContent.isHtml || iframeReady); + // Toasts sit above the quick reply box, as above a composer's footer + // (compose-p2-17): its height for toast.tsx, as it grows when focused. + useEffect(() => { + // The reply draft's card takes the box's place, and its ref. + const box = quickReplyBoxRef.current; + if (!(showQuickReply || showReplyDraft) || !box || typeof ResizeObserver === 'undefined') return; + const root = document.documentElement; + const update = () => root.style.setProperty('--quick-reply-height', `${box.offsetHeight}px`); + update(); + const observer = new ResizeObserver(update); + observer.observe(box); + return () => { + observer.disconnect(); + root.style.removeProperty('--quick-reply-height'); + }; + }, [showQuickReply, showReplyDraft]); // The plain-text body, where reader-above-quote mounts between text and quote. const [plainBodyEl, setPlainBodyEl] = useState(null); // Read aloud (browser speech): the body as shown, HTML frame or plain text. @@ -6401,8 +6416,31 @@ ${printWatermark ? printWatermark.html : ''}
)} + {/* The reply already started on this message, as Gmail shows it. */} + {showReplyDraft && replyDraft && ( +
+
+ + + {tList('draft')} + + {replyDraft.preview} + + + + +
+
+ )} + {/* Quick Reply Section - hidden for drafts and while loading a new email */} - {showQuickReply && (
+ {showQuickReply && (
void; + /** `text` is what the link shows; empty means the address itself. */ + onSubmit: (link: { text: string; href: string }) => void; + /** The selected text, or the link's own text when editing one. */ + defaultText: string; + defaultHref: string; + /** Offers "Remove link" when editing a link. */ + onRemove?: () => void; +} + +/** + * Insert link (compose-p2-7): "Text" and "Link", as Gmail and Outlook ask. The + * selection fills Text; with nothing selected the text (or the address) goes + * in as a new link. + */ +export function LinkDialog({ isOpen, onClose, onSubmit, defaultText, defaultHref, onRemove }: LinkDialogProps) { + const t = useTranslations("email_composer.toolbar"); + const tCommon = useTranslations("common"); + const id = useId(); + const [text, setText] = useState(defaultText); + const [href, setHref] = useState(defaultHref); + const textRef = useRef(null); + const hrefRef = useRef(null); + // With text already there, the address is what is left to give. + const firstField = defaultText ? hrefRef : textRef; + + useEffect(() => { + if (!isOpen) return; + setText(defaultText); + setHref(defaultHref); + }, [isOpen, defaultText, defaultHref]); + + const address = href.trim(); + const error = /\s/.test(address) ? t("link_invalid") : null; + const canSubmit = address.length > 0 && !error; + const errorId = `${id}-error`; + + const submit = (event?: React.FormEvent) => { + event?.preventDefault(); + if (!canSubmit) return; + try { + onSubmit({ text, href: address }); + } finally { + onClose(); + } + }; + + return ( + + {onRemove && ( + + )} + + + + } + > +
+
+ + setText(e.target.value)} /> +
+
+ + setHref(e.target.value)} + placeholder={t("link_address")} + aria-invalid={error ? true : undefined} + aria-describedby={error ? errorId : undefined} + className={error ? "border-destructive focus-visible:border-destructive" : undefined} + /> + {error && ( + + )} +
+
+
+ ); +} diff --git a/components/email/reply-quote-collapse.ts b/components/email/reply-quote-collapse.ts index 5dbd658f2..b97485888 100644 --- a/components/email/reply-quote-collapse.ts +++ b/components/email/reply-quote-collapse.ts @@ -2,7 +2,7 @@ import { Extension } from '@tiptap/core'; import type { Node as PMNode } from '@tiptap/pm/model'; -import { Plugin, PluginKey, Selection } from '@tiptap/pm/state'; +import { Plugin, PluginKey, Selection, TextSelection, type EditorState } from '@tiptap/pm/state'; import { Decoration, DecorationSet } from '@tiptap/pm/view'; export const REPLY_QUOTE_START_ATTRIBUTE = 'data-reply-quote-start'; @@ -59,6 +59,55 @@ function quoteRanges(doc: PMNode): QuoteRange[] { return ranges; } +const isSignature = (node: PMNode) => node.type.name === 'signatureBlock' || Boolean(node.attrs['data-signature-block']); + +function collapsedRanges(state: EditorState): QuoteRange[] { + const expanded = quoteKey.getState(state)?.expanded ?? new Set(); + return quoteRanges(state.doc).filter((range) => !expanded.has(range.from)); +} + +/** + * Where the user's own text ends: the end of the last paragraph above the + * folded quote or the signature, whichever comes first. Null when the body + * has neither, so the end of the body is the end of the text. + */ +export function userTextEnd(state: EditorState): number | null { + const ranges = quoteRanges(state.doc); + let boundary: number | null = collapsedRanges(state)[0]?.from ?? null; + state.doc.forEach((node, pos) => { + if (isSignature(node) && (boundary === null || pos < boundary)) boundary = pos; + }); + if (boundary === null) return null; + let end: number | null = null; + state.doc.forEach((node, pos) => { + if (pos + node.nodeSize > boundary! || !node.isTextblock || isSignature(node)) return; + if (ranges.some((range) => pos >= range.from && pos < range.to)) return; + end = pos + node.nodeSize - 1; + }); + return end; +} + +/** + * A click that lands under a folded quote (on the empty line the editor keeps + * at the end) would write below the hidden original, where the user can't see + * it. It goes to the end of their own text above the quote instead + * (compose-p2-3). Lines the user can see below the quote keep their click. + */ +function clickBelowCollapsedQuote(state: EditorState, pos: number): boolean { + const ranges = collapsedRanges(state); + const first = ranges[0]; + if (!first || pos < first.from) return false; + const $pos = state.doc.resolve(pos); + const topPos = $pos.depth > 0 ? $pos.before(1) : pos; + let hiddenOrEmpty = true; + state.doc.forEach((node, nodePos) => { + if (nodePos < first.from || nodePos > topPos) return; + if (ranges.some((range) => nodePos >= range.from && nodePos < range.to)) return; + if (!node.isTextblock || isSignature(node) || node.content.size > 0) hiddenOrEmpty = false; + }); + return hiddenOrEmpty; +} + /** Visibility is a view decoration, never a document edit or an undo step. */ export const ReplyQuoteCollapse = Extension.create<{ show: string; hide: string }>({ name: 'replyQuoteCollapse', @@ -107,6 +156,13 @@ export const ReplyQuoteCollapse = Extension.create<{ show: string; hide: string }, }, props: { + handleClick(view, pos) { + if (!clickBelowCollapsedQuote(view.state, pos)) return false; + const end = userTextEnd(view.state); + if (end === null) return false; + view.dispatch(view.state.tr.setSelection(TextSelection.create(view.state.doc, end))); + return true; + }, decorations(state) { const expanded = quoteKey.getState(state)?.expanded ?? new Set(); const decorations: Decoration[] = []; diff --git a/components/email/rich-text-editor.tsx b/components/email/rich-text-editor.tsx index 952a9da30..e0a9720a3 100644 --- a/components/email/rich-text-editor.tsx +++ b/components/email/rich-text-editor.tsx @@ -32,7 +32,8 @@ import { RecipientMention, RecipientMentionList, type RecipientMentionListHandle import { MentionChipCard, setMentionRecipients } from "@/components/email/mention-chip"; import { mentionSuggestions, type MentionCandidate, type MentionContact } from "@/lib/recipient-mentions"; import { cn } from "@/lib/utils"; -import { PromptDialog } from "@/components/ui/prompt-dialog"; +import { getMarkRange } from "@tiptap/core"; +import { LinkDialog } from "@/components/email/link-dialog"; import { ImageAltDialog } from "@/components/email/image-alt-dialog"; /** A typed address without a scheme ("example.com") becomes a web link. */ @@ -741,26 +742,43 @@ export function RichTextEditor({ if (editor) setMentionRecipients(editor, mentionCandidates ? mentionCandidates.map((c) => c.email) : null); }, [editor, mentionCandidates]); - // Insert link asks for the address in the app's own dialog; on a link it - // starts from the current address and offers "Remove link". - // The selection is kept from when the dialog opened: the dialog takes the - // focus, and with it the editor's selection. - const [linkDialog, setLinkDialog] = useState<{ href: string; from: number; to: number } | null>(null); + // Insert link asks for the text and the address in the app's own dialog + // (compose-p2-7); on a link it starts from the link's text and address and + // offers "Remove link". The range is kept from when the dialog opened: the + // dialog takes the focus, and with it the editor's selection. + const [linkDialog, setLinkDialog] = useState<{ href: string; text: string; from: number; to: number } | null>(null); const addLink = useCallback(() => { if (!editor) return; const previousUrl = editor.getAttributes("link").href as string | undefined; - const { from, to } = editor.state.selection; - setLinkDialog({ href: previousUrl ?? "", from, to }); + let { from, to } = editor.state.selection; + // The caret in a link edits the whole link. + const linkType = editor.schema.marks.link; + if (previousUrl && from === to && linkType) { + const range = getMarkRange(editor.state.doc.resolve(from), linkType); + if (range) ({ from, to } = range); + } + const text = editor.state.doc.textBetween(from, to, " "); + setLinkDialog({ href: previousUrl ?? "", text, from, to }); }, [editor]); addLinkRef.current = addLink; - const applyLink = useCallback((url: string) => { + const applyLink = useCallback(({ text, href }: { text: string; href: string }) => { if (!editor || !linkDialog) return; - editor - .chain() - .focus() - .setTextSelection({ from: linkDialog.from, to: linkDialog.to }) + const label = text.trim() ? text : href; + const { from, to } = linkDialog; + const chain = editor.chain().focus(); + if (from === to || label !== linkDialog.text) { + // Nothing selected, or the text changed: the text goes in as the link. + chain + .insertContentAt({ from, to }, { type: "text", text: label, marks: [{ type: "link", attrs: { href } }] }) + .setTextSelection(from + label.length) + .unsetMark("link") + .run(); + return; + } + chain + .setTextSelection({ from, to }) .extendMarkRange("link") - .setLink({ href: url }) + .setLink({ href }) .run(); }, [editor, linkDialog]); const removeLink = useCallback(() => { @@ -776,7 +794,6 @@ export function RichTextEditor({ const tToolbar = useTranslations("email_composer.toolbar"); const tWindows = useTranslations("compose_windows"); - const tCommon = useTranslations("common"); const [tableMenuOpen, setTableMenuOpen] = useState(false); const tableWrapperRef = useRef(null); const [colorMenuOpen, setColorMenuOpen] = useState(false); @@ -1465,16 +1482,13 @@ export function RichTextEditor({ document.body )} - setLinkDialog(null)} - title={linkDialog?.href ? tToolbar("edit_link") : tToolbar("insert_link")} - placeholder={tToolbar("link_address")} - defaultValue={linkDialog?.href ?? ""} - confirmText={tCommon("save")} - validate={(value) => (/\s/.test(value) ? tToolbar("link_invalid") : null)} - onSubmit={(value) => applyLink(withLinkScheme(value))} - extraAction={linkDialog?.href ? { label: tToolbar("remove_link"), onClick: removeLink } : undefined} + defaultText={linkDialog?.text ?? ""} + defaultHref={linkDialog?.href ?? ""} + onSubmit={({ text, href }) => applyLink({ text, href: withLinkScheme(href) })} + onRemove={linkDialog?.href ? removeLink : undefined} /> void; /** "Send anyway". `dontAskAgain`: the box under a single warning that has a setting. */ onSendAnyway: (dontAskAgain: boolean) => void; + /** Asked before Schedule send: the button says "Schedule anyway". */ + scheduling?: boolean; } /** The warnings that can be switched off in Settings (subject and placeholders). */ @@ -30,7 +32,7 @@ const HAS_SETTING = new Set(["subject", "placeholders"]); * own title and text, several are listed in one dialog with one "Send anyway" * (two dialogs in a row asked about each in turn). */ -export function SendWarningsDialog({ warnings, onBack, onSendAnyway }: SendWarningsDialogProps) { +export function SendWarningsDialog({ warnings, onBack, onSendAnyway, scheduling = false }: SendWarningsDialogProps) { const t = useTranslations("email_composer"); const tSend = useTranslations("compose_send"); const tProofreading = useTranslations("proofreading"); @@ -89,7 +91,7 @@ export function SendWarningsDialog({ warnings, onBack, onSendAnyway }: SendWarni backLabel = tProofreading("send_warning.review"); sendLabel = tProofreading("send_warning.send"); } else { - title = tSend("warnings_title"); + title = tSend(scheduling ? "schedule_warnings_title" : "warnings_title"); body = (
    {items.map((w) => ( @@ -113,6 +115,9 @@ export function SendWarningsDialog({ warnings, onBack, onSendAnyway }: SendWarni ); } + // Nothing goes out now: the message is scheduled (compose-p2-14). + if (scheduling) sendLabel = tSend("schedule_anyway"); + return ( 0} diff --git a/components/email/thread-conversation-view.tsx b/components/email/thread-conversation-view.tsx index cb3480049..c9b1687d8 100644 --- a/components/email/thread-conversation-view.tsx +++ b/components/email/thread-conversation-view.tsx @@ -49,6 +49,8 @@ import { Download, Eye, CalendarClock, + Pencil, + Trash2, } from "@/components/icons"; import { formatScheduledSendAt } from "@/lib/scheduled-send-label"; import { useTranslations } from "next-intl"; @@ -91,6 +93,9 @@ interface ThreadConversationViewProps { onReply?: (email: Email) => void; onReplyAll?: (email: Email) => void; onForward?: (email: Email) => void; + /** A draft in the conversation (compose-p2-6): Edit and Discard take Reply's place. */ + onEditDraft?: (email: Email) => void; + onDiscardDraft?: (email: Email) => void; onDownloadAttachment?: ConversationAttachmentHandler; /** Routing captured when this conversation was opened. */ blobSource?: EmailBlobContext; @@ -196,6 +201,8 @@ export function ThreadConversationView({ onReply, onReplyAll, onForward, + onEditDraft, + onDiscardDraft, onDownloadAttachment, blobSource, onMarkAsRead, @@ -230,7 +237,7 @@ export function ThreadConversationView({ // Also expand all unread emails ordered.forEach(email => { - if (!email.keywords?.$seen) { + if (!email.keywords?.$seen && !email.keywords?.$draft) { idsToExpand.add(email.id); } }); @@ -297,7 +304,9 @@ export function ThreadConversationView({
    - {ordered.map((email) => ( + {ordered.map((email) => { + const draft = !!email.keywords?.$draft; + return (
    toggleExpanded(email.id)} onAllowExternal={() => externalContent.allow(email.id)} onTrustSender={externalContent.trustSender(email)} - onReply={onReply ? () => onReply(email) : undefined} - onReplyAll={onReplyAll ? () => onReplyAll(email) : undefined} - onForward={onForward ? () => onForward(email) : undefined} + isDraft={draft} + onEditDraft={draft && onEditDraft ? () => onEditDraft(email) : undefined} + onDiscardDraft={draft && onDiscardDraft ? () => onDiscardDraft(email) : undefined} + onReply={!draft && onReply ? () => onReply(email) : undefined} + onReplyAll={!draft && onReplyAll ? () => onReplyAll(email) : undefined} + onForward={!draft && onForward ? () => onForward(email) : undefined} onDownloadAttachment={onDownloadAttachment} blobSource={blobSource} onMarkAsRead={onMarkAsRead} mailboxRole={mailboxRole} />
    - ))} + ); + })}
@@ -349,6 +362,9 @@ interface EmailCardProps { onReply?: () => void; onReplyAll?: () => void; onForward?: () => void; + isDraft?: boolean; + onEditDraft?: () => void; + onDiscardDraft?: () => void; onDownloadAttachment?: ConversationAttachmentHandler; /** Routing captured when this conversation was opened. */ blobSource?: EmailBlobContext; @@ -387,6 +403,9 @@ function EmailCard({ onReply, onReplyAll, onForward, + isDraft = false, + onEditDraft, + onDiscardDraft, onDownloadAttachment, blobSource, onMarkAsRead, @@ -442,6 +461,11 @@ function EmailCard({ + {isDraft && ( + + {t('email_list.draft')} + + )} {email.isScheduled && ( @@ -507,6 +531,34 @@ function EmailCard({ in the single reader's More panel on phones. Long names (Arabic "Reply all") wrap to a second line instead of being cut. */}
+ {onEditDraft && ( + + )} + {onDiscardDraft && ( + + )} {onReply && ( , +})); +// As the real composer: it hands its state (its own mode, untouched) to the +// host as it unmounts without an explicit close, and offers its close. +vi.mock('@/components/email/email-composer', async () => { + const { useEffect, useRef } = await import('react'); + return { + EmailComposer: ({ mode, onSaveState, onClose, requestCloseRef, onRestoreDiscarded }: { + mode: string; + onRestoreDiscarded?: (data: Record) => void; + onSaveState: (data: Record) => void; + onClose: () => void; + requestCloseRef?: { current: unknown }; + }) => { + const closed = useRef(false); + useEffect(() => { + stub.mounts.push(mode); + stub.restore = onRestoreDiscarded ?? null; + // The old host moved the composer between dock and pane for ever + // (React error 185 in the browser); stop it here instead of hanging. + if (stub.mounts.length > 40) throw new Error('composer remount loop'); + if (requestCloseRef && stub.close !== 'none') { + requestCloseRef.current = (afterClose?: () => void) => { + stub.closes.push(mode); + if (stub.close === 'fails') return; + closed.current = true; + onClose(); + afterClose?.(); + }; + } + return () => { + if (requestCloseRef) requestCloseRef.current = null; + if (closed.current) return; + onSaveState({ to: '', cc: '', bcc: '', subject: '', body: '', mode, draftId: null, unedited: true }); + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + return
stub composer
; + }, + }; +}); +vi.mock('@/components/search/mv-search-form', () => ({ + MvSearchForm: ({ onSearch }: { onSearch: () => void }) => , +})); +vi.mock('@/components/email/email-viewer', () => ({ + EmailViewer: ({ onReply, onReplyAll, onForward }: { onReply: () => void; onReplyAll: () => void; onForward: () => void }) => ( +
+ message viewer + + + +
+ ), +})); +vi.mock('@/components/layout/navigation-rail', () => ({ NavigationRail: () => null })); +vi.mock('@/components/layout/calendar-event-notification-toaster', () => ({ CalendarEventNotificationToaster: () => null })); +vi.mock('@/components/layout/share-notification-toaster', () => ({ ShareNotificationToaster: () => null })); +vi.mock('@/components/layout/mobile-header', () => ({ MobileHeader: () => null })); +vi.mock('@/components/layout/mv-side-panel', () => ({ MvSidePanel: () => null })); +vi.mock('@/components/email/message-list-tabs', () => ({ useMessageListPanelProps: (id: string) => ({ id }), MessageListTabs: () => null })); +vi.mock('@/components/search/search-box', () => ({ SearchBox: () => null })); +vi.mock('@/components/tour/tour-provider', () => ({ useTour: () => ({ activeTour: null, registerStep: vi.fn() }) })); +vi.mock('@/components/plugins/plugin-slot', () => ({ PluginSlot: () => null })); +vi.mock('@/hooks/use-plugin-slot-offers', () => ({ usePluginSlotOffers: () => [] })); +vi.mock('@/hooks/use-config', () => ({ useConfig: () => ({ appName: 'Mail' }) })); +vi.mock('@/hooks/use-identity-sync', () => ({ useIdentitySync: () => {} })); +vi.mock('@/hooks/use-pro-multi-account-identities', () => ({ useProMultiAccountIdentities: () => [] })); +vi.mock('@/hooks/use-pro-multi-account-mailboxes', () => ({ useProMultiAccountMailboxes: () => {} })); +vi.mock('@/hooks/use-wopi-status', () => ({ useWopiStatus: () => null, canWopiOpen: () => false })); +vi.mock('@/hooks/use-browser-navigation', () => ({ useBrowserNavigation: () => {} })); +vi.mock('@/hooks/use-media-query', () => ({ + useDeviceDetection: () => device.current, + useMediaQuery: () => false, + useIsDesktop: () => true, +})); +vi.mock('@/lib/push-bindings', () => ({ reconcilePushBindings: () => {}, releasePushBindings: () => {} })); +vi.mock('@/components/email/email-list', () => ({ + EmailList: () => null, +})); + +const { MailApp } = await import('../mail-app'); + +const inbox = { id: 'inbox', name: 'Inbox', role: 'inbox', totalEmails: 0, unreadEmails: 0 } as Mailbox; +const MESSAGE = { + id: 'm1', threadId: 't1', mailboxIds: { inbox: true }, keywords: { $seen: true }, + from: [{ name: 'Ann', email: 'ann@example.org' }], to: [{ email: 'a@example.org' }], + subject: 'Plans', receivedAt: '2026-11-01T10:00:00Z', preview: 'Hi', size: 10, + hasAttachment: false, textBody: [], htmlBody: [], bodyValues: {}, +} as never; + +beforeEach(() => { + device.current = { isMobile: false, isTablet: false, isDesktop: true }; + stub.close = 'none'; + stub.closes = []; + stub.mounts = []; + stub.restore = null; + vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('Unexpected network request'))); + vi.stubGlobal('ResizeObserver', class { observe() {} unobserve() {} disconnect() {} }); + usePluginStore.setState({ initializePlugins: vi.fn().mockResolvedValue(undefined) }); + useThemeStore.setState({ syncServerThemes: vi.fn().mockResolvedValue(undefined) }); + const client = { + getAccountId: () => 'acc', getUsername: () => 'a@example.org', + getSieveAccountId: () => null, hasDelayedSend: () => false, getSession: () => null, + getEmail: vi.fn().mockResolvedValue(null), + }; + useAuthStore.setState({ + isAuthenticated: true, isLoading: false, client: client as never, activeAccountId: 'login-a', identities: [], + getClientForAccount: () => client as never, + getAllConnectedClients: () => new Map([['login-a', client]]) as never, + }); + useSettingsStore.setState({ enableUnifiedMailbox: false, interfaceLayout: 'default', mailLayout: 'split' } as never); + useEmailStore.setState({ + emails: [MESSAGE], selectedEmail: MESSAGE, selectedMailbox: 'inbox', selectedKeyword: null, mailboxes: [inbox], + viewingAccountId: null, accountMailboxes: {}, isUnifiedView: false, unifiedRole: null, + isScheduledView: false, isLoadingEmail: false, isLoading: false, searchQuery: '', + searchFilters: { ...DEFAULT_SEARCH_FILTERS }, searchMailboxId: '', isAdvancedSearchOpen: false, + selectedEmailKeys: new Set(), unreadSection: null, + fetchMailboxes: vi.fn().mockResolvedValue(undefined), fetchEmails: vi.fn().mockResolvedValue(undefined), + fetchQuota: vi.fn().mockResolvedValue(undefined), fetchTagCounts: vi.fn().mockResolvedValue(undefined), + refreshScheduledMetadata: vi.fn().mockResolvedValue(undefined), + } as never); + useToastStore.getState().clearToasts(); +}); +afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllGlobals(); + useToastStore.getState().clearToasts(); +}); + +const composerMode = () => screen.getByTestId('stub-composer').getAttribute('data-mode'); + +describe('Compose while a reply is docked (compose-p2-1)', () => { + for (const action of ['stub reply', 'stub forward']) { + it(`opens a new message in the pane after ${action}`, async () => { + render(); + fireEvent.click(await screen.findByText(action)); + const reply = await screen.findByTestId('stub-composer'); + expect(reply.closest('[data-reply-dock]')).not.toBeNull(); + + fireEvent.click(screen.getByText('stub compose')); + await waitFor(() => expect(composerMode()).toBe('compose')); + // The new message takes the pane, not the dock, and stays put. + expect(screen.getByTestId('stub-composer').closest('[data-reply-dock]')).toBeNull(); + const mounted = stub.mounts.length; + await act(async () => { await new Promise((r) => setTimeout(r, 20)); }); + expect(stub.mounts.length).toBe(mounted); + expect(composerMode()).toBe('compose'); + }); + } +}); + +describe('another composer while one is open (compose-p2-2)', () => { + it('closes the reply through its own close (save, "Draft saved") before Compose opens', async () => { + stub.close = 'saves'; + render(); + fireEvent.click(await screen.findByText('stub reply')); + await screen.findByTestId('stub-composer'); + + fireEvent.click(screen.getByText('stub compose')); + await waitFor(() => expect(composerMode()).toBe('compose')); + expect(stub.closes).toEqual(['reply']); + }); + + for (const [action, mode] of [['stub reply all', 'replyAll'], ['stub forward', 'forward']] as const) { + it(`closes the reply through its own close before ${action} opens`, async () => { + stub.close = 'saves'; + render(); + fireEvent.click(await screen.findByText('stub reply')); + await screen.findByTestId('stub-composer'); + + fireEvent.click(screen.getByText(action)); + await waitFor(() => expect(composerMode()).toBe(mode)); + expect(stub.closes).toEqual(['reply']); + }); + } + + it('closes a new message before another new message opens', async () => { + stub.close = 'saves'; + render(); + fireEvent.click(screen.getByText('stub compose')); + await screen.findByTestId('stub-composer'); + const mounted = stub.mounts.length; + + fireEvent.click(screen.getByText('stub compose')); + await waitFor(() => expect(stub.mounts.length).toBe(mounted + 1)); + expect(stub.closes).toEqual(['compose']); + }); + + it('keeps the open composer when its save fails', async () => { + stub.close = 'fails'; + render(); + fireEvent.click(await screen.findByText('stub reply')); + await screen.findByTestId('stub-composer'); + const mounted = stub.mounts.length; + + fireEvent.click(screen.getByText('stub compose')); + await act(async () => { await new Promise((r) => setTimeout(r, 20)); }); + expect(stub.closes).toEqual(['reply']); + expect(stub.mounts.length).toBe(mounted); + expect(composerMode()).toBe('reply'); + }); +}); + +// compose-p2-10: Undo after the bin brings the composer back. +describe('Undo after the bin', () => { + it('opens the discarded text again, closing whatever is open first', async () => { + stub.close = 'saves'; + render(); + fireEvent.click(screen.getByText('stub compose')); + await screen.findByTestId('stub-composer'); + const restore = stub.restore!; + + act(() => restore({ to: 'bob@example.org', cc: '', bcc: '', subject: 'Back', body: 'kept', mode: 'forward', draftId: 'd1' })); + await waitFor(() => expect(composerMode()).toBe('forward')); + expect(stub.closes).toEqual(['compose']); + }); +}); diff --git a/components/mail/__tests__/mail-app-drafts.test.tsx b/components/mail/__tests__/mail-app-drafts.test.tsx new file mode 100644 index 000000000..980410488 --- /dev/null +++ b/components/mail/__tests__/mail-app-drafts.test.tsx @@ -0,0 +1,160 @@ +import React from 'react'; +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import type { Mailbox } from '@/lib/jmap/types'; +import { useAuthStore } from '@/stores/auth-store'; +import { useEmailStore } from '@/stores/email-store'; +import { useSettingsStore } from '@/stores/settings-store'; +import { usePluginStore } from '@/stores/plugin-store'; +import { useThemeStore } from '@/stores/theme-store'; +import { useToastStore } from '@/stores/toast-store'; +import { DEFAULT_SEARCH_FILTERS } from '@/lib/jmap/search-utils'; + +// Drafts reopen where people look for them (compose-p2-6, compose-p2-8): +// a click on a draft opens it in the composer, and Reply on a message with a +// reply draft opens that draft instead of starting a second one. + +const device = vi.hoisted(() => ({ current: { isMobile: false, isTablet: false, isDesktop: true } })); +const DRAFT_ROW = vi.hoisted(() => ({ + id: 'd1', threadId: 't1', mailboxIds: { drafts: true }, keywords: { $seen: true, $draft: true }, + from: [{ email: 'a@example.org' }], to: [{ email: 'ann@example.org' }], + subject: 'Re: Plans', receivedAt: '2026-11-02T10:00:00Z', preview: 'my answer', size: 10, hasAttachment: false, +})); + +vi.mock('@/components/layout/mv-top-bar', () => ({ MvTopBar: () => null })); +vi.mock('@/components/layout/sidebar', () => ({ Sidebar: () => null })); +vi.mock('@/components/email/email-composer', () => ({ + EmailComposer: ({ mode, initialData }: { mode: string; initialData?: { draftId?: string } | null }) => ( +
stub composer
+ ), +})); +vi.mock('@/components/search/mv-search-form', () => ({ + MvSearchForm: ({ onSearch }: { onSearch: () => void }) => , +})); +vi.mock('@/components/email/email-viewer', () => ({ + EmailViewer: ({ onReply, replyDraft }: { onReply: () => void; replyDraft?: { preview?: string; onEdit: () => void } | null }) => ( +
+ message viewer + + {replyDraft && } +
+ ), +})); +vi.mock('@/components/layout/navigation-rail', () => ({ NavigationRail: () => null })); +vi.mock('@/components/layout/calendar-event-notification-toaster', () => ({ CalendarEventNotificationToaster: () => null })); +vi.mock('@/components/layout/share-notification-toaster', () => ({ ShareNotificationToaster: () => null })); +vi.mock('@/components/layout/mobile-header', () => ({ MobileHeader: () => null })); +vi.mock('@/components/layout/mv-side-panel', () => ({ MvSidePanel: () => null })); +vi.mock('@/components/email/message-list-tabs', () => ({ useMessageListPanelProps: (id: string) => ({ id }), MessageListTabs: () => null })); +vi.mock('@/components/search/search-box', () => ({ SearchBox: () => null })); +vi.mock('@/components/tour/tour-provider', () => ({ useTour: () => ({ activeTour: null, registerStep: vi.fn() }) })); +vi.mock('@/components/plugins/plugin-slot', () => ({ PluginSlot: () => null })); +vi.mock('@/hooks/use-plugin-slot-offers', () => ({ usePluginSlotOffers: () => [] })); +vi.mock('@/hooks/use-config', () => ({ useConfig: () => ({ appName: 'Mail' }) })); +vi.mock('@/hooks/use-identity-sync', () => ({ useIdentitySync: () => {} })); +vi.mock('@/hooks/use-pro-multi-account-identities', () => ({ useProMultiAccountIdentities: () => [] })); +vi.mock('@/hooks/use-pro-multi-account-mailboxes', () => ({ useProMultiAccountMailboxes: () => {} })); +vi.mock('@/hooks/use-wopi-status', () => ({ useWopiStatus: () => null, canWopiOpen: () => false })); +vi.mock('@/hooks/use-browser-navigation', () => ({ useBrowserNavigation: () => {} })); +vi.mock('@/hooks/use-media-query', () => ({ + useDeviceDetection: () => device.current, + useMediaQuery: () => false, + useIsDesktop: () => true, +})); +vi.mock('@/lib/push-bindings', () => ({ reconcilePushBindings: () => {}, releasePushBindings: () => {} })); +vi.mock('@/components/email/email-list', () => ({ + EmailList: ({ onEmailSelect }: { onEmailSelect: (email: unknown) => void }) => ( + + ), +})); + +const { MailApp } = await import('../mail-app'); + +const inbox = { id: 'inbox', name: 'Inbox', role: 'inbox', totalEmails: 0, unreadEmails: 0 } as Mailbox; +const drafts = { id: 'drafts', name: 'Drafts', role: 'drafts', totalEmails: 1, unreadEmails: 0 } as Mailbox; +const MESSAGE = { + id: 'm1', threadId: 't1', mailboxIds: { inbox: true }, keywords: { $seen: true }, + from: [{ name: 'Ann', email: 'ann@example.org' }], to: [{ email: 'a@example.org' }], + subject: 'Plans', receivedAt: '2026-11-01T10:00:00Z', preview: 'Hi', size: 10, + hasAttachment: false, textBody: [], htmlBody: [], bodyValues: {}, messageId: ['plans@example.org'], +} as never; +const FULL_DRAFT = { + ...DRAFT_ROW, textBody: [{ partId: '1', type: 'text/plain' }], htmlBody: [], bodyValues: { 1: { value: 'my answer' } }, + inReplyTo: ['plans@example.org'], +}; + +type Client = Record & { getEmail: ReturnType }; +let client: Client; + +beforeEach(() => { + device.current = { isMobile: false, isTablet: false, isDesktop: true }; + vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('Unexpected network request'))); + vi.stubGlobal('ResizeObserver', class { observe() {} unobserve() {} disconnect() {} }); + usePluginStore.setState({ initializePlugins: vi.fn().mockResolvedValue(undefined) }); + useThemeStore.setState({ syncServerThemes: vi.fn().mockResolvedValue(undefined) }); + client = { + getAccountId: () => 'acc', getUsername: () => 'a@example.org', + getSieveAccountId: () => null, hasDelayedSend: () => false, getSession: () => null, + getEmail: vi.fn(async (id: string) => (id === 'd1' ? { ...FULL_DRAFT } : null)), + getThread: vi.fn(async () => ({ id: 't1', emailIds: ['m1', 'd1'] })), + getSomeEmails: vi.fn(async () => [{ ...(MESSAGE as object) }, { ...DRAFT_ROW }]), + }; + useAuthStore.setState({ + isAuthenticated: true, isLoading: false, client: client as never, activeAccountId: 'login-a', identities: [], + getClientForAccount: () => client as never, + getAllConnectedClients: () => new Map([['login-a', client]]) as never, + }); + useSettingsStore.setState({ enableUnifiedMailbox: false, interfaceLayout: 'default', mailLayout: 'split' } as never); + useEmailStore.setState({ + emails: [MESSAGE], selectedEmail: MESSAGE, selectedMailbox: 'inbox', selectedKeyword: null, mailboxes: [inbox, drafts], + viewingAccountId: null, accountMailboxes: {}, isUnifiedView: false, unifiedRole: null, + isScheduledView: false, isLoadingEmail: false, isLoading: false, searchQuery: '', + searchFilters: { ...DEFAULT_SEARCH_FILTERS }, searchMailboxId: '', isAdvancedSearchOpen: false, + selectedEmailKeys: new Set(), unreadSection: null, + fetchMailboxes: vi.fn().mockResolvedValue(undefined), fetchEmails: vi.fn().mockResolvedValue(undefined), + fetchQuota: vi.fn().mockResolvedValue(undefined), fetchTagCounts: vi.fn().mockResolvedValue(undefined), + refreshScheduledMetadata: vi.fn().mockResolvedValue(undefined), + } as never); + useToastStore.getState().clearToasts(); +}); +afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllGlobals(); + useToastStore.getState().clearToasts(); +}); + +describe('a draft in the list (compose-p2-8)', () => { + it('opens in the composer on a click', async () => { + render(); + fireEvent.click(await screen.findByText('stub draft row')); + const composer = await screen.findByTestId('stub-composer'); + expect(composer).toHaveAttribute('data-draft', 'd1'); + expect(composer).toHaveAttribute('data-mode', 'compose'); + }); +}); + +describe('a message with a reply draft (compose-p2-6)', () => { + it('shows the draft under the message', async () => { + render(); + expect(await screen.findByText('stub reply draft: my answer')).toBeInTheDocument(); + }); + + it('opens that draft on Reply instead of a new reply', async () => { + render(); + await screen.findByText('stub reply draft: my answer'); + fireEvent.click(screen.getByText('stub reply')); + await waitFor(() => expect(screen.getByTestId('stub-composer')).toHaveAttribute('data-draft', 'd1')); + // Under the message it answers, as a new reply is, not over it. + expect(screen.getByTestId('stub-composer').closest('[data-reply-dock]')).not.toBeNull(); + }); + + it('starts a new reply when the conversation has no reply to this message', async () => { + client.getEmail = vi.fn(async (id: string) => (id === 'd1' ? { ...FULL_DRAFT, inReplyTo: ['other@example.org'] } : null)); + render(); + await waitFor(() => expect(client.getEmail).toHaveBeenCalled()); + expect(screen.queryByText(/stub reply draft/)).toBeNull(); + fireEvent.click(screen.getByText('stub reply')); + await waitFor(() => expect(screen.getByTestId('stub-composer')).toHaveAttribute('data-mode', 'reply')); + expect(screen.getByTestId('stub-composer')).toHaveAttribute('data-draft', ''); + }); +}); diff --git a/components/mail/__tests__/mail-app-menu-selection.test.tsx b/components/mail/__tests__/mail-app-menu-selection.test.tsx new file mode 100644 index 000000000..9234ef35e --- /dev/null +++ b/components/mail/__tests__/mail-app-menu-selection.test.tsx @@ -0,0 +1,183 @@ +import React from 'react'; +import { act, cleanup, render, waitFor } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import type { Email, Mailbox } from '@/lib/jmap/types'; +import { useAuthStore } from '@/stores/auth-store'; +import { useEmailStore } from '@/stores/email-store'; +import { useSettingsStore } from '@/stores/settings-store'; +import { usePluginStore } from '@/stores/plugin-store'; +import { useThemeStore } from '@/stores/theme-store'; +import { useToastStore } from '@/stores/toast-store'; +import { DEFAULT_SEARCH_FILTERS } from '@/lib/jmap/search-utils'; +import { resetDesktopCommands, runDesktopCommand } from '@/lib/desktop/commands'; +import { useMoveDialogStore } from '@/components/email/move-to-dialog'; + +// The desktop app's Message menu with several messages selected: each line acts on all +// of them, or isn't offered. Reply to one of seven, or Move for the open one only, acts on +// mail nobody picked (usability pass 2, desktop-p2-3). + +const seen = vi.hoisted(() => ({ sourceEmailId: undefined as string | undefined })); + + +vi.mock('@/components/email/email-composer', async () => { + const { useEffect, useRef, useState } = await import('react'); + const { registerComposeFlush } = await import('@/lib/compose-flush-registry'); + return { + EmailComposer: ({ initialData, onSaveState, onSend, sourceEmailId }: { + initialData?: { subject?: string; mode?: string } | null; + onSaveState: (data: { subject: string; mode?: string }) => void; + onSend: (data: { to: string[]; cc: string[]; bcc: string[]; subject: string; body: string }) => Promise; + sourceEmailId?: string; + }) => { + seen.sourceEmailId = sourceEmailId; + useEffect(() => registerComposeFlush(async () => {}), []); + const [subject, setSubject] = useState(initialData?.subject ?? ''); + const initial = useRef(subject); + const latest = useRef(subject); + latest.current = subject; + useEffect(() => () => { + if (latest.current !== initial.current) onSaveState({ subject: latest.current, mode: initialData?.mode }); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + return ( + <> + setSubject(e.target.value)} /> + + + ); + }, + }; +}); +vi.mock('@/components/layout/mv-top-bar', () => ({ MvTopBar: () => null })); +vi.mock('@/components/layout/sidebar', () => ({ Sidebar: () => null })); +vi.mock('@/components/search/mv-search-form', () => ({ MvSearchForm: () => null })); +vi.mock('@/components/email/email-viewer', () => ({ EmailViewer: () =>
message viewer
})); +vi.mock('@/components/layout/navigation-rail', () => ({ NavigationRail: () => null })); +vi.mock('@/components/layout/calendar-event-notification-toaster', () => ({ CalendarEventNotificationToaster: () => null })); +vi.mock('@/components/layout/share-notification-toaster', () => ({ ShareNotificationToaster: () => null })); +vi.mock('@/components/layout/mobile-header', () => ({ MobileHeader: () => null })); +vi.mock('@/components/layout/mv-side-panel', () => ({ MvSidePanel: () => null })); +vi.mock('@/components/email/message-list-tabs', () => ({ useMessageListPanelProps: (id: string) => ({ id }), MessageListTabs: () => null })); +vi.mock('@/components/search/search-box', () => ({ SearchBox: () => null })); +vi.mock('@/components/tour/tour-provider', () => ({ useTour: () => ({ activeTour: null, registerStep: vi.fn() }) })); +vi.mock('@/components/plugins/plugin-slot', () => ({ PluginSlot: () => null })); +vi.mock('@/hooks/use-plugin-slot-offers', () => ({ usePluginSlotOffers: () => [] })); +vi.mock('@/hooks/use-config', () => ({ useConfig: () => ({ appName: 'Mail' }) })); +vi.mock('@/hooks/use-identity-sync', () => ({ useIdentitySync: () => {} })); +vi.mock('@/hooks/use-pro-multi-account-identities', () => ({ useProMultiAccountIdentities: () => [] })); +vi.mock('@/hooks/use-pro-multi-account-mailboxes', () => ({ useProMultiAccountMailboxes: () => {} })); +vi.mock('@/hooks/use-wopi-status', () => ({ useWopiStatus: () => null, canWopiOpen: () => false })); +vi.mock('@/hooks/use-browser-navigation', () => ({ useBrowserNavigation: () => {} })); +// A compact desktop: rail and folders beside the list, the composer in the pane. +const device = vi.hoisted(() => ({ current: { isMobile: false, isCompact: true, isDesktop: true } })); +vi.mock('@/hooks/use-media-query', () => ({ + useDeviceDetection: () => device.current, + useMediaQuery: () => false, + useIsDesktop: () => true, + atLeast: (px: number) => `(width >= ${px}px)`, + PHONE_BELOW: 600, +})); +vi.mock('@/lib/push-bindings', () => ({ reconcilePushBindings: () => {}, releasePushBindings: () => {} })); +vi.mock('@/components/email/email-list', () => ({ EmailList: () =>
message list
})); + +const { MailApp } = await import('../mail-app'); + +const inbox = { id: 'inbox', name: 'Inbox', role: 'inbox', totalEmails: 3, unreadEmails: 0, myRights: { mayRemoveItems: true, mayAddItems: true } } as unknown as Mailbox; +const later = { id: 'later', name: 'Read later', role: null, totalEmails: 0, unreadEmails: 0, myRights: { mayRemoveItems: true, mayAddItems: true } } as unknown as Mailbox; +const message = (id: string) => ({ id, threadId: `t-${id}`, subject: `Subject ${id}`, receivedAt: '2026-10-31T10:00:00Z', keywords: { $seen: true }, mailboxIds: { inbox: true } }) as unknown as Email; +const [a, b, c] = ['a', 'b', 'c'].map(message); + +let reported: Record = {}; +let named: string[] = []; +let batchMoveToMailbox: ReturnType; + +beforeEach(() => { + vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('Unexpected network request'))); + vi.stubGlobal('ResizeObserver', class { observe() {} unobserve() {} disconnect() {} }); + vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: false, addEventListener() {}, removeEventListener() {}, addListener() {}, removeListener() {} }))); + reported = {}; + named = []; + (window as unknown as { bulwarkDesktop: unknown }).bulwarkDesktop = { + version: 1, + platform: 'win32', + menu: { setState: (state: Record) => { reported = state; }, onCommand: () => () => {} }, + windows: { setMenuName: (name: string) => { named.push(name); } }, + }; + usePluginStore.setState({ initializePlugins: vi.fn().mockResolvedValue(undefined) }); + useThemeStore.setState({ syncServerThemes: vi.fn().mockResolvedValue(undefined) }); + const client = { + getAccountId: () => 'acc', getUsername: () => 'a@example.org', + getSieveAccountId: () => null, hasDelayedSend: () => false, getSession: () => null, + }; + useAuthStore.setState({ + isAuthenticated: true, isLoading: false, client: client as never, activeAccountId: 'login-a', identities: [], + getClientForAccount: () => client as never, + getAllConnectedClients: () => new Map([['login-a', client]]) as never, + }); + useSettingsStore.setState({ enableUnifiedMailbox: false, interfaceLayout: 'default', mailLayout: 'split', proInterface: false } as never); + batchMoveToMailbox = vi.fn().mockResolvedValue(true); + useEmailStore.setState({ + emails: [a, b, c], selectedEmail: a, selectedMailbox: 'inbox', selectedKeyword: null, mailboxes: [inbox, later], + viewingAccountId: null, accountMailboxes: {}, isUnifiedView: false, unifiedRole: null, + isScheduledView: false, isLoadingEmail: false, isLoading: false, searchQuery: '', + searchFilters: { ...DEFAULT_SEARCH_FILTERS }, searchMailboxId: '', isAdvancedSearchOpen: false, + selectedEmailKeys: new Set(['a', 'b', 'c']), unreadSection: null, threadEmailsCache: new Map(), error: null, + fetchMailboxes: vi.fn().mockResolvedValue(undefined), fetchEmails: vi.fn().mockResolvedValue(undefined), + fetchQuota: vi.fn().mockResolvedValue(undefined), fetchTagCounts: vi.fn().mockResolvedValue(undefined), + refreshScheduledMetadata: vi.fn().mockResolvedValue(undefined), + fetchEmailContent: vi.fn().mockResolvedValue(undefined), + refreshCurrentMailbox: vi.fn().mockResolvedValue(undefined), + batchMoveToMailbox, + } as never); +}); +afterEach(() => { + cleanup(); + resetDesktopCommands(); + useMoveDialogStore.setState({ request: null }); + delete (window as unknown as { bulwarkDesktop?: unknown }).bulwarkDesktop; + vi.restoreAllMocks(); + vi.unstubAllGlobals(); +}); + +describe('the Message menu with three messages selected', () => { + it('offers no Reply, Reply all, Forward or Star, which would act on one of them', async () => { + render(); + await waitFor(() => expect(reported['message.archive']).toBe(true)); + expect(reported['message.reply']).toBe(false); + expect(reported['message.replyAll']).toBe(false); + expect(reported['message.forward']).toBe(false); + expect(reported['message.star']).toBe(false); + expect(reported['message.openWindow']).toBe(false); + expect(reported['message.move']).toBe(true); + }); + + it('Move to… moves all three, and the toast says how many', async () => { + render(); + await waitFor(() => expect(reported['message.move']).toBe(true)); + act(() => { runDesktopCommand('message.move'); }); + const request = useMoveDialogStore.getState().request; + expect(request?.emails.map((email) => email.id)).toEqual(['a', 'b', 'c']); + await act(async () => { request!.onMove('later'); }); + await waitFor(() => expect(batchMoveToMailbox).toHaveBeenCalledWith(expect.anything(), 'later', undefined, expect.any(Array))); + await waitFor(() => expect(useToastStore.getState().toasts.map((toast) => toast.title)).toContain('moved_count_to')); + }); + + it('with one message open and none selected, Reply and Move are for that one', async () => { + useEmailStore.setState({ selectedEmailKeys: new Set() } as never); + render(); + await waitFor(() => expect(reported['message.reply']).toBe(true)); + expect(reported['message.move']).toBe(true); + act(() => { runDesktopCommand('message.move'); }); + expect(useMoveDialogStore.getState().request).toBeNull(); + expect(batchMoveToMailbox).not.toHaveBeenCalled(); + }); +}); + +describe('the Window menu name of the main window', () => { + it('is the folder, not the message open in it, so it never reads like the window of that message', async () => { + useEmailStore.setState({ selectedEmailKeys: new Set() } as never); + render(); + await waitFor(() => expect(named.at(-1)).toBe('sidebar.mailboxes.inbox')); + expect(named).not.toContain('Subject a'); + }); +}); diff --git a/components/mail/__tests__/undo-send-toast.test.tsx b/components/mail/__tests__/undo-send-toast.test.tsx index 92d7e83e3..d3c87a094 100644 --- a/components/mail/__tests__/undo-send-toast.test.tsx +++ b/components/mail/__tests__/undo-send-toast.test.tsx @@ -114,11 +114,26 @@ describe('undo send toast', () => { await waitFor(() => expect(undoToast()).toBeDefined()); const toast = undoToast()!; expect(toast.title).toBe('email_viewer.sending_in'); - // 30 s is the setting, but only 10 s are left of the window. - expect(toast.duration).toBeLessThan(10_000); + // 30 s is the setting, but only 10 s are left of the window. The toast + // itself stays a moment longer, to say "Sent" once Undo is over. + expect(toast.duration).toBeLessThanOrEqual(10_000); expect(toast.pauseOnHover).toBe(false); }); + // compose-p2-12: once Undo is over the toast says the message went. + it('turns into "Sent" with View before the server releases the message', async () => { + render(); + sendDelayedBy(2_500); + + await waitFor(() => expect(undoToast()).toBeDefined()); + const id = undoToast()!.id; + await waitFor(() => { + const toast = useToastStore.getState().toasts.find((t) => t.id === id); + expect(toast?.title).toBe('compose_send.sent'); + expect(toast?.action?.label).toBe('compose_send.view'); + }, { timeout: 3000 }); + }); + // compose-23: "Email scheduled for sending" with "Undo send" said neither // when it goes nor that the button cancels it. it('says when a scheduled message goes, with Cancel and Send now', async () => { diff --git a/components/mail/mail-app.tsx b/components/mail/mail-app.tsx index 508c8481c..af504abb9 100644 --- a/components/mail/mail-app.tsx +++ b/components/mail/mail-app.tsx @@ -56,9 +56,10 @@ import { useRemoveFromFolder } from "@/hooks/use-remove-from-folder"; import { groupSearchScopeFolders, SEARCH_SCOPE_ALL_FOLDERS } from "@/lib/search-scope-folders"; import { toast } from "@/stores/toast-store"; import { discardWithUndo } from "@/lib/compose/draft-close-toast"; +import { findReplyDraft, threadDrafts } from "@/lib/reply-drafts"; import { cancelFailureToast, partlyRefusedWarning, rescheduleFailureToast, rescheduledToast } from "@/lib/send-failure-message"; import { formatScheduledSendAt } from "@/lib/scheduled-send-label"; -import { startSendProgress } from "@/lib/outgoing/send-progress-toast"; +import { runUndoSendCountdown, startSendProgress, UNDO_TOAST_SLACK_MS } from "@/lib/outgoing/send-progress-toast"; import { formatRejectedRecipients, RescheduleRestoredError } from "@/lib/jmap/client"; import { subscribePushStateChanges } from "@/lib/push-events"; import { createMailPushListener } from "@/lib/mail-push-listener"; @@ -163,7 +164,8 @@ import { deliveryAddresses, resolveComposeAccountEmail } from "@/lib/reply-ident import { useProMultiAccountIdentities } from "@/hooks/use-pro-multi-account-identities"; import { Filter, X, Mail, MailOpen, PenSquare, CheckSquare, Square, AlertTriangle, ArrowLeft, RefreshCw, Reply, ReplyAll, Forward, Archive, Trash2, FolderInput, ShieldAlert, ShieldCheck, Folder, Upload, Star } from "@/components/icons"; import { useRegisterCommands } from "@/lib/command-registry"; -import { MoveToDialog, MoveToDialogHost } from "@/components/email/move-to-dialog"; +import { MoveToDialog, MoveToDialogHost, useMoveDialogStore } from "@/components/email/move-to-dialog"; +import { useDesktopWindowName } from "@/lib/desktop/window-name"; import { SearchResultCount } from "@/components/email/search-result-count"; import { ResizeHandle } from "@/components/layout/resize-handle"; import { Button } from "@/components/ui/button"; @@ -174,7 +176,7 @@ import { useOtherAccountsUnread } from "@/hooks/use-all-inboxes-unread"; import { usePluginStore } from "@/stores/plugin-store"; import { AppTopBannerSlot } from "@/components/plugins/app-top-banner-slot"; import { canDownload } from "@/lib/device-policy"; -import { consumePendingMailto, subscribeToPendingMailto } from "@/lib/protocol-handlers/session"; +import { consumePendingMailto, mailLinkAccountId, subscribeToPendingMailto } from "@/lib/protocol-handlers/session"; import { setNotificationReplyOpener } from "@/lib/pwa-notify/page-actions"; import { setMailLinkOpener } from "@/lib/desktop/mail-links"; import { requestTabReply } from "@/lib/pwa-notify/tab-reply"; @@ -328,7 +330,9 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) { composerSessionRef.current = composerSessionId; const composerHostRef = useRef('pane'); // The compose session docked under its message (dockedReply). - const dockedSessionRef = useRef(null); + const [dockedSession, setDockedSession] = useState(null); + // A reply draft opened again from its message (compose-p2-6): it docks too. + const [resumedReplySession, setResumedReplySession] = useState(null); const showComposerRef = useRef(showComposer); showComposerRef.current = showComposer; // Fields a plugin filled in through onBeforeCompose for the composer about @@ -343,6 +347,15 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) { // already uses the same seam), so entry points that replace the session can // ask before discarding unsaved text. const composerRequestCloseRef = useRef<((afterClose?: () => void) => void) | null>(null); + // One composer at a time (compose-p2-2). Whatever opens a composer closes + // the one on screen first, the way its X does: it saves and says "Draft + // saved" with Discard, then the new one opens. When that save fails the old + // composer stays with its question, and this never settles: nothing opens. + const closeOpenComposer = useCallback(() => new Promise((resolve) => { + const requestClose = composerRequestCloseRef.current; + if (showComposerRef.current && requestClose) requestClose(resolve); + else resolve(); + }), []); const { dialogProps: confirmDialogProps, confirm: confirmDialog } = useConfirmDialog(); const { dialogProps: promptDialogProps, prompt: promptDialog } = usePromptDialog(); const { showAppsModal, inlineApp, loadedApps, handleManageApps, handleInlineApp, closeInlineApp, closeAppsModal } = useSidebarApps(); @@ -384,6 +397,13 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) { threadId: string; emailId: string; startedAt: number; promise: Promise; } | null>(null); const mvConversationOpenSeqRef = useRef(0); + // compose-p2-6: a reply to the open message saved as a draft. The reader + // shows it under the message, and Reply opens it again. The conversation + // fetch notes the thread's drafts; a scan reads them fresh after a composer + // closed or a draft went. + const [replyDraft, setReplyDraft] = useState<{ emailId: string; draft: Email; source: DraftSource } | null>(null); + const [replyDraftScan, setReplyDraftScan] = useState<{ emailId: string; n: number } | null>(null); + const conversationDraftsRef = useRef<{ threadId: string; emailId: string; drafts: Email[] } | null>(null); const [conversationEmails, setConversationEmails] = useState([]); const [isLoadingConversation, setIsLoadingConversation] = useState(false); const [rateLimitSecondsLeft, setRateLimitSecondsLeft] = useState(null); @@ -1205,12 +1225,7 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) { } }, onCompose: () => { - void withComposeGate('compose', {}, () => { - startFreshComposerSession(); - setComposerMode('compose'); - setShowComposer(true); - if (isMobile) setActiveView('viewer'); - }); + void handleCompose(); }, onFocusSearch: () => { if (isScheduledView) return; @@ -1408,7 +1423,26 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) { // The desktop app's menu bar: the same handlers as the keys, and what's enabled // from what's on screen (lib/desktop/commands.ts). const desktopTarget = !showComposer && (!!selectedEmail || selectedEmailKeys.size > 0); - const desktopSingle = !showComposer && !!selectedEmail; + // With several selected, a menu line acts on all of them or isn't offered: Reply to one + // of seven, or Move for the open one only, would act on mail nobody picked. + const desktopMulti = selectedEmailKeys.size > 1; + const desktopSingle = !showComposer && !!selectedEmail && !desktopMulti; + const tListExtra = useTranslations('mail_list_extra'); + /** Message > Move to… on the selection, as the selection bar's Move does: one toast with the count. */ + const moveSelectionTo = async (mailboxId: string) => { + if (!client) return; + const count = selectedEmailKeys.size; + const restore = restoreBatchesForSelection(client); + const receipts: CrossAccountMoveReceipt[] = []; + const destination = mailboxes.find((m) => m.id === mailboxId); + await runBatchEmailAction(() => useEmailStore.getState().batchMoveToMailbox(client, mailboxId, undefined, receipts), { + success: destination + ? tListExtra('moved_count_to', { count, mailbox: getMailboxPath(destination, mailboxes) }) + : tNotifications('emails_moved', { count }), + error: tNotifications('move_failed'), + undo: undoMoveAction(client, restore, undo, receipts), + }); + }; const mailLayoutSetting = useSettingsStore((s) => s.mailLayout); const layoutFixed = interfaceLayout === 'mountain-view'; // A shared folder you may only read from: nothing can leave it. @@ -1426,7 +1460,15 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) { 'message.markRead': () => void keyboardHandlers.onMarkAsRead?.(), 'message.markUnread': () => void keyboardHandlers.onMarkAsUnread?.(), 'message.star': () => void keyboardHandlers.onToggleStar?.(), - 'message.move': () => { if (selectedEmail) setMoveDialogEmail(selectedEmail); }, + 'message.move': () => { + if (shortcutsTargetSelection) { + const state = useEmailStore.getState(); + const picked = resolveSelectedEmails({ emails: state.emails, threadEmailsCache: state.threadEmailsCache, selectedEmailKeys }); + if (picked.length > 0) useMoveDialogStore.getState().open({ emails: picked, onMove: (mailboxId) => void moveSelectionTo(mailboxId) }); + } else if (selectedEmail) { + setMoveDialogEmail(selectedEmail); + } + }, 'message.archive': keyboardHandlers.onArchive ? () => void keyboardHandlers.onArchive?.() : undefined, 'message.spam': () => void keyboardHandlers.onToggleSpam?.(), 'message.delete': () => void keyboardHandlers.onDelete?.(), @@ -1450,7 +1492,7 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) { 'message.markRead': desktopTarget && !(selectedEmail && selectedEmailKeys.size === 0 && selectedEmail.keywords?.$seen), 'message.markUnread': desktopTarget && !(selectedEmail && selectedEmailKeys.size === 0 && !selectedEmail.keywords?.$seen), 'message.star': desktopSingle, - 'message.move': desktopSingle && desktopMayRemove, + 'message.move': desktopTarget && desktopMayRemove, 'message.archive': desktopTarget && archiveActionEnabled && desktopMayRemove, 'message.spam': desktopTarget && desktopMayRemove, 'message.delete': desktopTarget && desktopMayRemove, @@ -1545,6 +1587,12 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) { return mailTitleContext({ composer, subject, mailbox: mailboxLine }, { showSubject: subjectInTabTitle }); }, [showComposer, composerMode, selectedEmail, selectedMailbox, mailboxes, t, subjectInTabTitle, otherAccountsUnread, isUnifiedView]); useDocumentTitle(titleContext); + // The Window menu names this window by its folder, never by the open message (desktop-p2-5). + const windowView = useMemo(() => { + const mailbox = selectedMailbox ? mailboxes.find(mb => mb.id === selectedMailbox) : undefined; + return mailbox ? localizeMailboxName(mailbox.role, mailbox.name, (k) => t(`sidebar.mailboxes.${k}`)) : t('sidebar.mail'); + }, [selectedMailbox, mailboxes, t]); + useDesktopWindowName(windowView, { withAccount: true }); // When this page is rendered inside the Pro shell as the Mail tab body, // we hoist every "show composer" intent into its own Pro tab and reset @@ -1730,8 +1778,8 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) { // A mail link from another program, in the desktop app: a compose window of its own, // as Outlook and Thunderbird do, and the main window stays where it was. Plugins get // their say first. False when it has to open here instead. - const openMailtoInWindow = useCallback(async (pending: DraftRequest): Promise => { - if (!pending.fromOs || pending.initialFiles?.length || !hasDesktopWindows() || !popoutsAvailable()) return false; + const openMailtoInWindow = useCallback(async (pending: DraftRequest, accountId?: string): Promise => { + if (!pending.fromOs || !hasDesktopWindows() || !popoutsAvailable()) return false; let prefill: ComposePrefill | null = null; if (emailHooks.onBeforeCompose.size > 0) { prefill = await runBeforeCompose(composeOptionsFor('compose', { @@ -1743,12 +1791,15 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) { // A plugin said no: nothing opens, here or there. if (!prefill) return true; } - const opened = openComposerWindow(useAuthStore.getState().activeAccountId); + // The account the link goes out from, in its own window: the main window keeps the one it shows. + const opened = openComposerWindow(accountId ?? useAuthStore.getState().activeAccountId); if (!opened) return false; void opened.handOver({ mode: 'compose', initialData: mailtoComposerDraft(pending, useSettingsStore.getState().plainTextMode), prefill: prefill && Object.keys(prefill).length > 0 ? prefill : null, + // Send to and Open with: the files go along (desktop-p2-6). + ...(pending.initialFiles?.length ? { initialFiles: pending.initialFiles } : {}), }); return true; }, [identities, t]); @@ -1780,6 +1831,10 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) { }, [openMailtoInWindow, openMailtoHere]); const openMailtoForAccount = useCallback(async (pending: DraftRequest, accountId: string) => { + if (await openMailtoInWindow(pending, accountId)) { + setPendingMailtoAccountChoice(null); + return; + } setIsProtocolAccountSwitching(true); try { if (useAuthStore.getState().activeAccountId !== accountId) { @@ -1790,7 +1845,7 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) { } finally { setIsProtocolAccountSwitching(false); } - }, [openMailtoDraft, switchAccount]); + }, [openMailtoDraft, openMailtoInWindow, switchAccount]); // onMailtoIntercept: a plugin may stop a mailto: from opening the composer. const mailtoAllowed = useCallback(async (pending: ParsedMailto & { href?: string }): Promise => { @@ -1803,17 +1858,10 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) { }); }, []); - // A draft that comes from outside: which account it goes out from. + // A draft that comes from outside goes out from the default account, as in Outlook and + // Thunderbird, with no question: the composer's From changes it (desktop-p2-8). const routeOutsideDraft = useCallback(async (pending: DraftRequest): Promise => { - const protocolAccounts = getMailtoProtocolAccounts(); - if (protocolAccounts.length > 1) { - // The question is asked in this window: bring it up. - if (pending.fromOs) getDesktopBridge()?.windows?.focus?.(); - setPendingMailtoAccountChoice(pending); - return; - } - - const accountId = protocolAccounts[0]?.id ?? activeAccountId; + const accountId = mailLinkAccountId(getMailtoProtocolAccounts(), useAccountStore.getState().defaultAccountId, activeAccountId); if (accountId) { await openMailtoForAccount(pending, accountId); return; @@ -1871,6 +1919,7 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) { body: handoff.body ?? '', initialFiles: handoff.files, unedited: true, + ...(handoff.fromOs ? { fromOs: true } : {}), }); }; @@ -2888,11 +2937,51 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) { setPendingDraft(null); }, []); + // A new message, from every Compose and New message there is. + const handleCompose = async (onOpen?: () => void) => { + await closeOpenComposer(); + await withComposeGate('compose', {}, () => { + startFreshComposerSession(); + setComposerMode('compose'); + setShowComposer(true); + if (isMobile) setActiveView('viewer'); + onOpen?.(); + }); + }; + // A minimised composer's edits live only in pendingDraft. Before an // automatic sign-out it is opened again and saves them itself. useMinimisedComposerFlush(!showComposer && pendingDraft?.unsaved === true, () => setShowComposer(true)); + // Reply on a message with a reply draft opens that draft (compose-p2-6). + // After a composer closed (it may have saved that very draft under a new + // id) the drafts are read fresh. + const resumeReplyDraft = async (open: Email | null, composerWasOpen: boolean): Promise => { + if (!client || !open || open.keywords?.$draft || mvShell || isScheduledView) return false; + let found = replyDraft?.emailId === open.id ? replyDraft : null; + // A phone's conversation holds its drafts in full. + const phoneConversation = isMobile && conversationEmails.some((e) => e.id === open.id); + if (composerWasOpen || phoneConversation) { + const { client: threadClient, accountId, clientAccountId } = resolveEmailBlobContext(open, client); + if (!threadClient) return false; + const drafts = phoneConversation && !composerWasOpen + ? conversationEmails + : await threadDrafts(threadClient, open.threadId, accountId).catch(() => []); + const draft = await findReplyDraft(drafts, open, (id) => threadClient.getEmail(id, accountId)); + found = draft ? { + emailId: open.id, draft, + source: { accountId, localAccountId: clientAccountId ?? activeAccountId ?? undefined }, + } : null; + } + if (!found) return false; + await handleEditDraft(found.draft, found.source, { underMessage: true }); + return true; + }; + const handleReply = async (draftText?: string) => { + const composerWasOpen = showComposer; + await closeOpenComposer(); + if (!draftText && await resumeReplyDraft(selectedEmail, composerWasOpen)) return; if (selectedEmail) { const formerSelected = { ...selectedEmail }; const enrichedEmail = await emailHooks.onBeforeComposeOpenToReply.transform(selectedEmail); @@ -2924,13 +3013,16 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) { * undone or cancelled - the account it was sent from (a group or shared one * for mail sent from its identity) and the login that sent it. */ - const handleEditDraft = async (email?: Email, source?: DraftSource) => { + // `underMessage`: a reply draft resumed from the message it answers docks + // under that message, as a new reply does (compose-p2-6). + const handleEditDraft = async (email?: Email, source?: DraftSource, { underMessage = false }: { underMessage?: boolean } = {}) => { if (!client) return; const draftCandidate = email && typeof email === 'object' && typeof email.id === 'string' ? email : selectedEmail; let draft = draftCandidate; if (!draft) return; + await closeOpenComposer(); // The login and account the draft lives in (resolveDraftSource). The // composer removes the old version there when it saves, sends or @@ -2972,7 +3064,9 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) { // Increment session ID to force the composer to remount with fresh state, // even if it was already open (e.g. right-clicking a draft while composing). - setComposerSessionId(id => id + 1); + const nextSession = composerSessionRef.current + 1; + setComposerSessionId(nextSession); + setResumedReplySession(underMessage ? nextSession : null); setPendingDraft(composerDataFromDraft(draft, { accountId, localAccountId, @@ -3155,10 +3249,11 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) { // A message scheduled for later says when it goes, and offers Cancel // where a send-delay window offers Undo send. - toast.success(isUndoWindow + const undoToastId = toast.success(isUndoWindow ? t('email_viewer.sending_in', { seconds: Math.round(remainingMs / 1000) }) : t('compose_send.scheduled_for', { when: formatScheduledSendAt(pending.sendAt, useSettingsStore.getState().timeFormat) }), { - duration: undoDurationMs, + // An undo window turns into "Sent" as Undo ends (runUndoSendCountdown). + duration: isUndoWindow ? undoDurationMs + UNDO_TOAST_SLACK_MS : undoDurationMs, pauseOnHover: false, secondaryAction: (pending.emailId && pending.identityId) ? { @@ -3236,6 +3331,23 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) { }, }); + // Counts down, then "Sent" with View (compose-p2-12). + if (isUndoWindow) { + const sentId = pending.emailId; + const viewable = sentId && undoClient === client; + const ownerAccountId = pending.submissionAccountId && pending.submissionAccountId !== client.getAccountId() ? pending.submissionAccountId : undefined; + runUndoSendCountdown(undoToastId, { + sendAt: Date.parse(pending.sendAt), + undoEndsAt: Date.now() + undoDurationMs, + maxSeconds: sendDelaySeconds, + sendingIn: (seconds) => t('email_viewer.sending_in', { seconds }), + sent: t('compose_send.sent'), + view: viewable + ? { label: t('compose_send.view'), onClick: () => void applyMailDeepLinkRef.current({ kind: 'message', id: sentId, ownerAccountId }) } + : undefined, + }); + } + const timer = setTimeout(() => { const current = useEmailStore.getState().pendingUndoSend; if (current?.submissionId === pending.submissionId) { @@ -3254,6 +3366,9 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) { }, [cancelUndoSend, clearPendingUndoSend, client, fetchScheduledEmails, isScheduledView, pendingUndoSend?.submissionId, sendDelaySeconds, t, tComposer, tViewer]); const handleReplyAll = async (draftText?: string) => { + const composerWasOpen = showComposer; + await closeOpenComposer(); + if (!draftText && await resumeReplyDraft(selectedEmail, composerWasOpen)) return; if (selectedEmail) { const formerSelected = { ...selectedEmail }; const enrichedEmail = await emailHooks.onBeforeComposeOpenToReplyAll.transform(selectedEmail); @@ -3343,6 +3458,7 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) { }, [isEmbedded]); const handleForward = async () => { + await closeOpenComposer(); if (selectedEmail) { const formerSelected = { ...selectedEmail }; const enrichedEmail = await emailHooks.onBeforeComposeOpenToForward.transform(selectedEmail); @@ -3389,6 +3505,7 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) { // unselected row. See the list context-menu wiring below. const handleForwardAsAttachment = async (email: Email | null = selectedEmail) => { if (!email) return; + await closeOpenComposer(); email = await emailHooks.onBeforeComposeOpenToForwardAsAttachment.transform(email); // Same filename options "Export as .eml" uses (see emailFilenameOptions // in email-viewer.tsx), so the two actions produce consistent filenames @@ -3457,6 +3574,7 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) { const handleBatchForwardAsAttachment = async () => { const selected = resolveSelectedEmails(useEmailStore.getState()); if (selected.length < 2) return; // menu only offers this for >1; guards future wiring + await closeOpenComposer(); const { emailDownloadTemplate, @@ -4858,6 +4976,10 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) { } const scheduledSubmissionByEmailId = useEmailStore.getState().scheduledSubmissionByEmailId; const annotated = annotateScheduledEmails(emails, scheduledSubmissionByEmailId); + conversationDraftsRef.current = { + threadId: ref.threadId, emailId: ref.id, + drafts: annotated.filter((e) => e.id !== ref.id && e.keywords?.$draft), + }; return annotated .filter((e) => e.id === ref.id || !e.keywords?.$draft) .sort((a, b) => a.receivedAt.localeCompare(b.receivedAt)); @@ -4927,6 +5049,62 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) { }); }; + // The open message's reply draft (compose-p2-6). Not in Mountain View, which + // has its own conversation, nor on a phone, whose conversation lists drafts. + const replyDraftMessageIds = String(selectedEmail?.messageId ?? ''); + useEffect(() => { + const open = selectedEmail; + if (!client || !open || open.keywords?.$draft || mvShell || isMobile || isScheduledView || !replyDraftMessageIds) { + setReplyDraft(null); + return; + } + const fresh = replyDraftScan?.emailId === open.id; + const noted = conversationDraftsRef.current; + const known = noted && noted.threadId === open.threadId && noted.emailId === open.id ? noted.drafts : null; + if (!fresh && !known) { + // The conversation isn't here yet: keep what this message had. + setReplyDraft((prev) => (prev?.emailId === open.id ? prev : null)); + return; + } + if (!fresh && known?.length === 0) { + setReplyDraft(null); + return; + } + const { client: threadClient, accountId, clientAccountId } = resolveEmailBlobContext(open, client); + if (!threadClient) return; + let cancelled = false; + void (async () => { + const drafts = fresh ? await threadDrafts(threadClient, open.threadId, accountId).catch(() => []) : known ?? []; + const found = await findReplyDraft(drafts, open, (id) => threadClient.getEmail(id, accountId)); + if (cancelled) return; + setReplyDraft(found ? { + emailId: open.id, + draft: { ...found, sourceClientAccountId: open.sourceClientAccountId, sourceAccountId: open.sourceAccountId }, + source: { accountId, localAccountId: clientAccountId ?? activeAccountId ?? undefined }, + } : null); + })(); + return () => { cancelled = true; }; + // eslint-disable-next-line react-hooks/exhaustive-deps -- keyed on the open message and what can change its drafts + }, [selectedEmail?.id, replyDraftMessageIds, mvConversationResult, replyDraftScan, client, mvShell, isMobile, isScheduledView]); + // A composer closing may have saved, sent or discarded a reply draft. + const scanReplyDrafts = () => { + const open = useEmailStore.getState().selectedEmail; + if (open) setReplyDraftScan((prev) => ({ emailId: open.id, n: (prev?.n ?? 0) + 1 })); + }; + const composerWasOpenRef = useRef(showComposer); + useEffect(() => { + if (composerWasOpenRef.current && !showComposer) scanReplyDrafts(); + composerWasOpenRef.current = showComposer; + }, [showComposer]); + const discardReplyDraft = () => { + const kept = replyDraft; + if (!kept) return; + setReplyDraft(null); + discardWithUndo(() => { + void handleDiscardDraft(kept.draft.id, kept.source).then(scanReplyDrafts); + }, { discarded: tComposeUx('draft_discarded'), undo: tComposeUx('undo') }, () => setReplyDraft(kept)); + }; + const patchMvConversation = (id: string, patch: (e: Email) => Email) => setMvConversationResult(prev => prev ? { ...prev, emails: prev.emails.map(e => e.id === id ? patch(e) : e), @@ -5000,14 +5178,8 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) { onImportEmail: handleImportEmailFromContextMenu, onRefreshMailboxes: handleRefreshMailboxes, onCompose: () => { - void withComposeGate('compose', {}, () => { - startFreshComposerSession(); - setComposerMode('compose'); - setShowComposer(true); - if (isMobile) { - setSidebarOpen(false); - setActiveView('viewer'); - } + void handleCompose(() => { + if (isMobile) setSidebarOpen(false); }); }, onSidebarClose: () => setSidebarOpen(false), @@ -5107,9 +5279,10 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) { // Decided as it opens and kept for the session: moving it would mount it // anew when the message goes away (another folder opened meanwhile). const dockCandidate = !mvShell && !isMobile && showComposer && !isEmbedded && !floatingComposer - && (pendingDraft?.mode ?? composerMode) !== 'compose'; - if (dockCandidate && selectedEmail && !selectedEmail.keywords?.$draft) dockedSessionRef.current = composerSessionId; - const dockedReply = dockCandidate && dockedSessionRef.current === composerSessionId; + && ((pendingDraft?.mode ?? composerMode) !== 'compose' || resumedReplySession === composerSessionId); + const dockOnOpen = dockCandidate && Boolean(selectedEmail) && !selectedEmail?.keywords?.$draft; + if (dockOnOpen && dockedSession !== composerSessionId) setDockedSession(composerSessionId); + const dockedReply = dockCandidate && (dockOnOpen || dockedSession === composerSessionId); const composerHost = floatingComposer ? 'window' : mvInlineReply ? 'inline' : dockedReply ? 'dock' : 'pane'; composerHostRef.current = composerHost; // Rows ticked beyond the open message take the reading pane (mail-p2-3): @@ -5368,6 +5541,9 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) { // Handle reply from conversation view const handleConversationReply = async (email: Email) => { + const composerWasOpen = showComposer; + await closeOpenComposer(); + if (await resumeReplyDraft(email, composerWasOpen)) return; email = await emailHooks.onBeforeComposeOpenToReply.transform(email); selectEmail(email); await prepareComposerQuoteHeader(email, 'reply'); @@ -5380,6 +5556,9 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) { }; const handleConversationReplyAll = async (email: Email) => { + const composerWasOpen = showComposer; + await closeOpenComposer(); + if (await resumeReplyDraft(email, composerWasOpen)) return; email = await emailHooks.onBeforeComposeOpenToReplyAll.transform(email); selectEmail(email); await prepareComposerQuoteHeader(email, 'replyAll'); @@ -5392,6 +5571,7 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) { }; const handleConversationForward = async (email: Email) => { + await closeOpenComposer(); email = await emailHooks.onBeforeComposeOpenToForward.transform(email); selectEmail(email); await prepareComposerQuoteHeader(email, 'forward'); @@ -5490,6 +5670,12 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) { docked={composerHost === 'dock'} sourceEmailId={answeredEmailId} onSaveState={(data) => { + // A composer whose session another one has replaced: its state + // belongs to no composer on screen. Taken as the new session's, + // it turned a new message into the old reply and moved it between + // the dock and the pane for ever (React error 185, compose-p2-1). + // Whatever opens a composer closes the old one first, which saves it. + if (composerSessionRef.current !== composerSessionId) return; setComposerPrefill(null); if (suppressComposerStateSaveSessionRef.current === composerSessionId) { suppressComposerStateSaveSessionRef.current = null; @@ -5521,6 +5707,7 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) { const outcome = await handleEmailSend(data, state); setPendingDraft(null); setComposerPrefill(null); + scanReplyDrafts(); return outcome; }} onSendFailed={(state) => { @@ -5551,7 +5738,18 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) { requestCloseRef={composerRequestCloseRef} onDiscardDraft={(draftId, draft) => { handleDiscardDraft(draftId, draft); - setPendingDraft(null); + // The bin and the toasts' Discard delete once their Undo is over, + // when another composer may be open: its draft stays. + if (composerSessionRef.current === composerSessionId) setPendingDraft(null); + }} + onRestoreDiscarded={(data) => { + void closeOpenComposer().then(() => { + startFreshComposerSession(); + setPendingDraft(data); + setComposerMode(data.mode); + setShowComposer(true); + if (isMobile) setActiveView('viewer'); + }); }} popOut={popoutsOn && !isEmbedded ? composerPopOut : undefined} /> @@ -6025,7 +6223,13 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) { }} onRescheduleScheduled={(email) => setRescheduleTarget(email)} onCancelScheduledSend={handleCancelScheduledSend} - onEmailSelect={handleEmailSelect} + // A click (or Enter) on a draft opens it in the composer, as + // Gmail and Outlook do (compose-p2-8). j/k still read it. + // Mountain View and Scheduled keep their own ways. + onEmailSelect={!mvShell && !isScheduledView && !isEmbedded ? (email) => { + if (email.keywords?.$draft) void handleEditDraft(email).catch(reportDraftOpenFailure); + else void handleEmailSelect(email); + } : handleEmailSelect} onOpenSearchResult={handleEmailSelect} onEmailPrefetch={handleEmailPrefetch} onEmailDoubleClick={!isEmbedded ? (desktopDoubleClick ? (email) => { @@ -6088,12 +6292,7 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) { }} onClearSearch={() => void handleClearSearch()} onCompose={() => { - void withComposeGate('compose', {}, () => { - startFreshComposerSession(); - setComposerMode('compose'); - setShowComposer(true); - if (isMobile) setActiveView('viewer'); - }); + void handleCompose(); }} onMarkAsRead={async (email, read) => { await markReadWithUndo(email, read).catch(toastUpdateFailure); @@ -6136,12 +6335,7 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) { button no longer sits on the list's rows. */} {!mvShell && (isMobile || isEmbedded) && )} {/* Folded, the composer stays mounted, with its text and its undo history. */} -
+
{children}
diff --git a/components/popout/__tests__/popout-compose-app.test.tsx b/components/popout/__tests__/popout-compose-app.test.tsx index d92e90439..f1bfe6f70 100644 --- a/components/popout/__tests__/popout-compose-app.test.tsx +++ b/components/popout/__tests__/popout-compose-app.test.tsx @@ -7,6 +7,7 @@ import { useAuthStore } from '@/stores/auth-store'; import { useEmailStore } from '@/stores/email-store'; import { useIdentityStore } from '@/stores/identity-store'; import { usePluginStore } from '@/stores/plugin-store'; +import { useSettingsStore } from '@/stores/settings-store'; import { emailHooks } from '@/lib/plugin-hooks'; // The composer's window: when it tells the opening window to let go, and what @@ -610,11 +611,51 @@ describe('a send held for undo', () => { expect(closeSelf).not.toHaveBeenCalled(); const sent = heard.find((message) => message.type === 'sent') as Extract | undefined; expect(sent?.notice.pendingUndoSend ?? null).toBeNull(); + // compose-p2-13: the main window asks for the Scheduled count again then. + expect(sent?.notice.releasesAt).toBe(sendAt); + }); + + // The server's time runs past the delay: "Sending in 6 seconds" for 5 s. + it('never counts from more than the delay the user picked', async () => { + const before = useSettingsStore.getState().sendDelaySeconds; + useSettingsStore.setState({ sendDelaySeconds: 5 } as never); + await sendFromWindow(5.8); + expect(screen.getByTestId('popout-sending')).toHaveAttribute('data-seconds', '5'); + useSettingsStore.setState({ sendDelaySeconds: before } as never); + }); + + // compose-24: the window sat with a greyed Send until the server answered. + it('says "Sending…" as soon as Send goes through, before the server answers', async () => { + let answer!: () => void; + useEmailStore.setState({ sendEmail: vi.fn(() => new Promise((resolve) => { answer = () => resolve({}); })) } as never); + sendAt = new Date(Date.now() + 5000).toISOString(); + window.history.replaceState(null, '', '/en/popout/compose?draft=d0&account=alice'); + render(); + await waitFor(() => expect(screen.getByTestId('composer').textContent).toBe('Before sending')); + let done: Promise = Promise.resolve(); + act(() => { done = (composer as unknown as Sending).onSend(DATA); }); + expect(screen.getByTestId('popout-sending').textContent).toMatch(/sending$/); + await act(async () => { answer(); await done; }); + }); + + it('shows the composer again with its text when the send fails', async () => { + useEmailStore.setState({ sendEmail: vi.fn(async () => { throw new Error('refused'); }) } as never); + sendAt = new Date(Date.now() + 5000).toISOString(); + window.history.replaceState(null, '', '/en/popout/compose?draft=d0&account=alice'); + render(); + await waitFor(() => expect(screen.getByTestId('composer').textContent).toBe('Before sending')); + await act(async () => { + await expect((composer as unknown as Sending).onSend(DATA)).rejects.toThrow('refused'); + }); + expect(screen.queryByTestId('popout-sending')).toBeNull(); + expect(screen.getByTestId('composer').closest('.hidden')).toBeNull(); }); it('closes once the undo time is over', async () => { await sendFromWindow(1.2); expect(closeSelf).not.toHaveBeenCalled(); + // As the main window's toast: "Sent" once Undo is over (compose-24). + await waitFor(() => expect(screen.getByTestId('popout-sending').textContent).toMatch(/(^|\.)sent$/), { timeout: 3000 }); await waitFor(() => expect(closeSelf).toHaveBeenCalled(), { timeout: 4000 }); }); @@ -629,7 +670,8 @@ describe('a send held for undo', () => { it('a message scheduled for later still goes to the main window, and the window closes', async () => { await sendFromWindow(3600); - expect(screen.queryByTestId('popout-sending')).toBeNull(); + // "Sending…" may still show as the window goes, but no Undo here. + expect(screen.queryByRole('button', { name: 'undo_send' })).toBeNull(); expect(closeSelf).toHaveBeenCalled(); const sent = heard.find((message) => message.type === 'sent') as Extract | undefined; expect(sent?.notice.pendingUndoSend?.submissionId).toBe('sub1'); diff --git a/components/popout/__tests__/popout-host.test.tsx b/components/popout/__tests__/popout-host.test.tsx index 559272ea5..14634634d 100644 --- a/components/popout/__tests__/popout-host.test.tsx +++ b/components/popout/__tests__/popout-host.test.tsx @@ -309,6 +309,23 @@ describe('PopoutHost', () => { expect(useToastStore.getState().toasts).toHaveLength(1); }); + // compose-p2-13: the Scheduled count kept a pop-out's undo-held send + // until the page was reloaded, since nothing reports the release. + it('asks for the Scheduled count again once a send held in a pop-out has gone', async () => { + const refreshScheduledMetadata = vi.fn(async () => {}); + useEmailStore.setState({ refreshScheduledMetadata: refreshScheduledMetadata as never }); + render(); + await settle(); + popout.post({ type: 'sent', requestId: 'r1', notice: { accountId: 'alice', scheduled: true, releasesAt: new Date(Date.now() + 100).toISOString() } }); + popout.post({ type: 'sent', requestId: 'r2', notice: { accountId: 'alice', scheduled: true, releasesAt: '2030-01-01T00:00:00Z' } }); + await settle(); + expect(refreshScheduledMetadata).not.toHaveBeenCalled(); + await settle(700); + // Once, for the held one; the one scheduled for 2030 stays in the count. + expect(refreshScheduledMetadata).toHaveBeenCalledTimes(1); + expect(refreshScheduledMetadata).toHaveBeenCalledWith(client); + }); + it('says once that a closed pop-out kept its draft, with Discard', async () => { render(<>); await settle(); @@ -320,6 +337,18 @@ describe('PopoutHost', () => { expect(toasts[0].action?.label).toBe('email_composer.discard'); }); + // compose-p2-10: the window's bin. + it('says a pop-out discarded its draft, with Undo', async () => { + render(); + await settle(); + popout.post({ type: 'draft-kept', requestId: 'k2', notice: { draftId: 'd1', localAccountId: 'alice', discarded: true } }); + await settle(); + const toasts = useToastStore.getState().toasts; + expect(toasts).toHaveLength(1); + expect(toasts[0].title).toBe('compose_ux.draft_discarded'); + expect(toasts[0].action?.label).toBe('compose_ux.undo'); + }); + it('refreshes the list and counts when a pop-out changed mail, once for a burst', async () => { render(); await settle(); diff --git a/components/popout/popout-compose-app.tsx b/components/popout/popout-compose-app.tsx index 5f8f5433b..f1e36f8f9 100644 --- a/components/popout/popout-compose-app.tsx +++ b/components/popout/popout-compose-app.tsx @@ -5,11 +5,14 @@ import { useTranslations } from "next-intl"; import { EmailComposer, type ComposerDraftData } from "@/components/email/email-composer"; import { ErrorBoundary, ComposerErrorFallback } from "@/components/error"; import { useDocumentTitle } from "@/hooks/use-document-title"; +import { useDesktopWindowName } from "@/lib/desktop/window-name"; import { useAccountStore } from "@/stores/account-store"; import { useAuthStore } from "@/stores/auth-store"; import { useEmailStore } from "@/stores/email-store"; import { usePluginStore } from "@/stores/plugin-store"; import { toast } from "@/stores/toast-store"; +import { useSettingsStore } from "@/stores/settings-store"; +import { secondsUntilSend } from "@/lib/outgoing/send-progress-toast"; import { formatRejectedRecipients } from "@/lib/jmap/client"; import { debug } from "@/lib/debug"; import { composerSendOptions } from "@/lib/outgoing/composer-send-options"; @@ -67,6 +70,17 @@ interface ReopenTarget { ownerAccountId?: string; } +/** "Sending…" or "Sent", where the composer was, with the send icon. */ +function SendStatus({ text, seconds, children }: { text: string; seconds?: number; children?: React.ReactNode }) { + return ( +
+
+ ); +} + /** * A send held for undo, shown in the window it was sent from: that's where the * user is looking, and quick compose is used with the main window out of sight. @@ -79,6 +93,7 @@ function SendingWithUndo({ held, onUndone, onGone }: { onGone: () => void; }) { const tViewer = useTranslations("email_viewer"); + const tSend = useTranslations("compose_send"); const [now, setNow] = useState(() => Date.now()); const [busy, setBusy] = useState(false); const sendAt = Date.parse(held.sendAt); @@ -122,17 +137,18 @@ function SendingWithUndo({ held, onUndone, onGone }: { onUndone(held.isSmime ? null : restored); }; - const seconds = Math.max(0, Math.ceil((sendAt - now) / 1000)); + // As the main window's toast counts: never past the delay the user picked. + const seconds = secondsUntilSend(sendAt, now, useSettingsStore.getState().sendDelaySeconds); + // Once Undo is over, "Sent" for the moment before the window goes, as the + // main window's toast says it. return ( -
-
+ ); } @@ -313,6 +329,9 @@ function PopoutComposer({ payload, handoffId, onReopen }: { const [sessionKey] = useState(() => `popout-${handoffId ?? Date.now().toString(36)}`); const mode = payload.initialData?.mode ?? payload.mode; + // The Window menu names a composer by its subject, or "New message" before there is one. + const [subject, setSubject] = useState(payload.initialData?.subject ?? ""); + useDesktopWindowName(subject.trim() || t("email_composer.new_message")); useDocumentTitle( mode === "reply" ? t("email_composer.reply") : mode === "replyAll" ? t("email_composer.reply_all") @@ -320,7 +339,11 @@ function PopoutComposer({ payload, handoffId, onReopen }: { : t("email_composer.new_message"), ); - const handleSend = useCallback(async (data: SendData) => { + // "Sending…" from the moment Send goes through, as the main window says it + // (compose-24); the composer waited greyed out for the server before. It + // stays mounted behind, and comes back with the text if the send fails. + const [sending, setSending] = useState(false); + const sendFromWindow = useCallback(async (data: SendData) => { if (!client) return false; const sendClient = data.localAccountId ? (useAuthStore.getState().getClientForAccount(data.localAccountId) ?? client) @@ -377,6 +400,7 @@ function PopoutComposer({ payload, handoffId, onReopen }: { filingError: !!result.filingError, rejectedRecipients, pendingUndoSend: keepHere ? null : withLogin, + releasesAt: keepHere?.sendAt, }); // No main window to say so, and this is the only notice these get (#1123). if (!taken && (result.filingError || rejectedRecipients)) { @@ -385,6 +409,16 @@ function PopoutComposer({ payload, handoffId, onReopen }: { await new Promise((resolve) => setTimeout(resolve, WARNING_READ_MS)); } }, [client, mode, payload.sourceEmailId, payload.sourceEmailSource, t]); + const handleSend = useCallback(async (data: SendData) => { + if (!client) return false; + if (!data.delayedUntil) setSending(true); + try { + return await sendFromWindow(data); + } catch (error) { + setSending(false); + throw error; + } + }, [client, sendFromWindow]); const handleDiscardDraft = useCallback(async (draftId: string, draft?: { accountId?: string; localAccountId?: string }) => { if (!client) return; @@ -487,6 +521,9 @@ function PopoutComposer({ payload, handoffId, onReopen }: { onDraftKept: (draftId: string, where: { accountId?: string; localAccountId?: string }) => { announceDraftKept({ draftId, ...where, localAccountId: where.localAccountId ?? useAuthStore.getState().activeAccountId ?? undefined }); }, + onDraftDiscarded: (draftId: string, where: { accountId?: string; localAccountId?: string }) => { + announceDraftKept({ draftId, ...where, localAccountId: where.localAccountId ?? useAuthStore.getState().activeAccountId ?? undefined, discarded: true }); + }, onDraftSaved: (draftId: string, where: { accountId?: string; localAccountId?: string } = {}) => { const active = useAuthStore.getState().activeAccountId; announceMailChanged(active); @@ -506,12 +543,16 @@ function PopoutComposer({ payload, handoffId, onReopen }: { if (held) return ; return ( + <> + {sending && } +
+
+ ); } diff --git a/components/popout/popout-host.tsx b/components/popout/popout-host.tsx index 4e73f3ad6..cc12175d3 100644 --- a/components/popout/popout-host.tsx +++ b/components/popout/popout-host.tsx @@ -8,7 +8,7 @@ import { useAccountStore } from "@/stores/account-store"; import { useAuthStore } from "@/stores/auth-store"; import { useEmailStore } from "@/stores/email-store"; import { toast } from "@/stores/toast-store"; -import { showDraftSavedToast } from "@/lib/compose/draft-close-toast"; +import { discardWithUndo, showDraftSavedToast } from "@/lib/compose/draft-close-toast"; import { newPopoutId, openPopoutChannel, type PopoutChannel, type PopoutMessage, type PopoutSentNotice, type RescuedDraft, type SharedAccountSession } from "@/lib/popout/channel"; import { takeOverMoved } from "@/lib/popout/moved-undo"; import { keepRescuedDraft } from "@/lib/popout/rescued-drafts"; @@ -24,6 +24,10 @@ const LIST_CHANGE_DEBOUNCE_MS = 400; const CLAIM_HOLD_MS = 15_000; /** How long a window remembers which draft id a rescue became, for a reload of the pop-out. */ const RESCUE_MEMORY_MS = 60_000; +/** The Scheduled count is asked again this long after the server let a held send go. */ +const RELEASE_REFRESH_MS = 3000; +/** Longer holds are messages scheduled for later, which stay in the count. */ +const UNDO_HOLD_MS = 120_000; /** The sessions this window can lend. Empty until it is signed in, and in the demo. */ function shareableSessions(): SharedAccountSession[] { @@ -112,8 +116,26 @@ export function PopoutHost() { }, REFRESH_THROTTLE_MS); }; + // The Scheduled count holds a send while the server holds it. Nothing + // reports the release (compose-p2-13): ask again once it is out. + const releaseTimers = new Set>(); + const refreshScheduled = () => { + const client = useAuthStore.getState().client; + if (client) void useEmailStore.getState().refreshScheduledMetadata(client); + }; + const refreshScheduledAfter = (releasesAt: string) => { + const wait = Date.parse(releasesAt) - Date.now(); + if (!Number.isFinite(wait) || wait > UNDO_HOLD_MS) return; + const timer = setTimeout(() => { + releaseTimers.delete(timer); + refreshScheduled(); + }, Math.max(0, wait) + RELEASE_REFRESH_MS); + releaseTimers.add(timer); + }; + const takeOverSent = (notice: PopoutSentNotice) => { const translate = tRef.current; + if (notice.releasesAt) refreshScheduledAfter(notice.releasesAt); if (notice.filingError) toast.warning(translate("email_composer.send_filing_warning")); if (notice.rejectedRecipients) { toast.warning(translate("email_composer.send_some_recipients_rejected"), { message: notice.rejectedRecipients, duration: 15000 }); @@ -180,10 +202,10 @@ export function PopoutHost() { break; case "draft-kept": { // Said here, as the pop-out closes with its Escape or X. - const { draftId, accountId, localAccountId } = message.notice; + const { draftId, accountId, localAccountId, discarded } = message.notice; claimOnce(`bulwark-popout-kept:${message.requestId}`, () => { const tr = tRef.current; - showDraftSavedToast(() => { + const discard = () => { const auth = useAuthStore.getState(); const login = localAccountId ? auth.getClientForAccount(localAccountId) : auth.client; if (!login) { @@ -191,12 +213,16 @@ export function PopoutHost() { return; } void login.deleteEmail(draftId, accountId).catch((error: unknown) => console.error("Failed to discard draft:", error)); - }, { + }; + const labels = { saved: tr("email_composer.draft_saved"), discard: tr("email_composer.discard"), discarded: tr("compose_ux.draft_discarded"), undo: tr("compose_ux.undo"), - }); + }; + // The window's bin: Undo leaves the draft in Drafts. + if (discarded) discardWithUndo(discard, labels); + else showDraftSavedToast(discard, labels); }); break; } @@ -272,6 +298,7 @@ export function PopoutHost() { stopAccounts(); if (refreshTimer) clearTimeout(refreshTimer); if (listTimer) clearTimeout(listTimer); + for (const timer of releaseTimers) clearTimeout(timer); channel?.close(); }; }, [available]); diff --git a/components/popout/popout-message-app.tsx b/components/popout/popout-message-app.tsx index 74273e0c7..01cffd00d 100644 --- a/components/popout/popout-message-app.tsx +++ b/components/popout/popout-message-app.tsx @@ -5,6 +5,7 @@ import { useTranslations } from "next-intl"; import { Button } from "@/components/ui/button"; import { ProEmailView } from "@/components/pro/pro-email-tab-body"; import { useDocumentTitle } from "@/hooks/use-document-title"; +import { useDesktopWindowName } from "@/lib/desktop/window-name"; import { useAuthStore } from "@/stores/auth-store"; import { useEmailStore } from "@/stores/email-store"; import { usePolicyStore } from "@/stores/policy-store"; @@ -105,6 +106,8 @@ function PopoutMessage({ emailId, accountId, ownerAccountId, fromLink }: { email const [subject, setSubject] = useState(null); const subjectInTitle = usePolicyStore((s) => s.loaded && s.isFeatureEnabled("tabTitleSubjectEnabled")); useDocumentTitle(subjectInTitle ? subject : null); + // Kept out where the organisation keeps subjects out of titles: the shell then says "Message". + useDesktopWindowName(subjectInTitle ? subject : null); // Folders first: without them Delete has no Trash to move to, Archive has no // button yet, and the toolbar moves under the pointer once they arrive. diff --git a/components/protocol/protocol-account-picker.tsx b/components/protocol/protocol-account-picker.tsx index 9bc672a4a..bb594ce9e 100644 --- a/components/protocol/protocol-account-picker.tsx +++ b/components/protocol/protocol-account-picker.tsx @@ -167,7 +167,7 @@ export function ProtocolAccountPicker({ {t("switching_account")} ) : ( - {t("select_account_note")} + )}