fix: give pop-out and quick compose windows the main composer's layout, with Send bottom right and Discard as a bin

This commit is contained in:
Linus Rath
2026-11-04 06:04:28 +01:00
parent 5a020cf2f9
commit 94bb55765d
2 changed files with 258 additions and 15 deletions
@@ -0,0 +1,240 @@
import { render, screen, within } from '@testing-library/react';
import { describe, it, expect, vi } from 'vitest';
import React from 'react';
import { EmailComposer } from '../email-composer';
// One layout in every composer: Send at the bottom end, Discard as a bin left
// of it, the formatting toolbar showing. A pop-out or quick compose window is
// narrower than a tablet, and used to get the phone's layout: Send in the
// header, Discard where Send was, the toolbar behind a button.
vi.mock('@/components/email/rich-text-editor', () => ({
RichTextEditor: ({ collapseToolbarOnMobile }: { collapseToolbarOnMobile?: boolean }) =>
React.createElement('div', { 'data-testid': 'rich-text-editor', 'data-collapsed': String(!!collapseToolbarOnMobile) }),
}));
vi.mock('@/components/plugins/plugin-slot', () => ({ PluginSlot: () => null }));
vi.mock('@/components/ui/avatar', () => ({ Avatar: () => null }));
vi.mock('@/components/identity/sub-address-helper', () => ({ SubAddressHelper: () => null }));
vi.mock('@/components/templates/template-picker', () => ({ TemplatePicker: () => null }));
vi.mock('@/components/templates/template-form', () => ({ TemplateForm: () => null }));
vi.mock('@/components/files/file-preview-modal', () => ({ FilePreviewModal: () => null }));
vi.mock('@/hooks/use-focus-trap', () => ({
useFocusTrap: () => ({ current: null }),
}));
vi.mock('@/hooks/use-pro-multi-account-identities', () => ({
useProMultiAccountIdentities: () => ({ enabled: false, groups: [], allIdentities: [] }),
stripCrossAccountIdentityPrefix: (id: string) => ({ localAccountId: null, rawId: id }),
}));
vi.mock('@/stores/auth-store', () => {
const state = {
client: null,
identities: [],
primaryIdentity: null,
isAuthenticated: false,
isDemoMode: false,
activeAccountId: null,
connectionLost: false,
getClientForAccount: () => undefined,
getAllConnectedClients: () => new Map(),
syncIdentities: () => {},
refreshIdentities: async () => {},
};
const hook = (sel?: (s: typeof state) => unknown) =>
typeof sel === 'function' ? sel(state) : state;
hook.getState = () => state;
hook.setState = (p: Partial<typeof state>) => Object.assign(state, p);
return { useAuthStore: hook };
});
vi.mock('@/stores/identity-store', () => {
const state = {
identities: [{ id: 'id-me', email: 'me@example.com', name: 'Me' }],
defaultIdentityId: 'id-me',
};
const hook = (sel?: (s: typeof state) => unknown) =>
typeof sel === 'function' ? sel(state) : state;
hook.getState = () => state;
hook.setState = (p: Partial<typeof state>) => Object.assign(state, p);
return { useIdentityStore: hook };
});
vi.mock('@/stores/account-store', () => {
const state = { accounts: [], getAccountById: () => undefined };
const hook = (sel?: (s: typeof state) => unknown) =>
typeof sel === 'function' ? sel(state) : state;
hook.getState = () => state;
hook.setState = (p: Partial<typeof state>) => Object.assign(state, p);
return { useAccountStore: hook };
});
vi.mock('@/stores/email-store', () => {
const state = {
draftSaveEnabled: false,
sendRawEmail: async () => ({ sent: true }),
};
const hook = (sel?: (s: typeof state) => unknown) =>
typeof sel === 'function' ? sel(state) : state;
hook.getState = () => state;
hook.setState = (p: Partial<typeof state>) => Object.assign(state, p);
return { useEmailStore: hook };
});
vi.mock('@/stores/settings-store', () => {
const state = {
timeFormat: '24h',
plainTextMode: false,
subAddressDelimiter: '+',
autoSelectReplyIdentity: true,
attachmentReminderEnabled: false,
attachmentReminderKeywords: [],
emptySubjectWarningEnabled: true,
sendDelaySeconds: 0,
signaturePosition: 'above_quote',
signatureSeparatorEnabled: false,
requestReadReceiptDefault: false,
addTrustedSender: () => {},
trustedSendersAddressBook: null,
updateSetting: () => {},
};
const hook = (sel?: (s: typeof state) => unknown) =>
typeof sel === 'function' ? sel(state) : state;
hook.getState = () => state;
hook.setState = (p: Partial<typeof state>) => Object.assign(state, p);
return { useSettingsStore: hook };
});
vi.mock('@/stores/contact-store', () => {
const state = {
contacts: [],
getAutocomplete: async () => [],
addToTrustedSendersBook: async () => {},
};
const hook = (sel?: (s: typeof state) => unknown) =>
typeof sel === 'function' ? sel(state) : state;
hook.getState = () => state;
hook.setState = (p: Partial<typeof state>) => Object.assign(state, p);
return { useContactStore: hook };
});
vi.mock('@/stores/template-store', () => {
const state = { templates: [], addTemplate: async () => {} };
const hook = (sel?: (s: typeof state) => unknown) =>
typeof sel === 'function' ? sel(state) : state;
hook.getState = () => state;
hook.setState = (p: Partial<typeof state>) => Object.assign(state, p);
return { useTemplateStore: hook };
});
vi.mock('@/stores/toast-store', () => ({
toast: { info: () => {}, error: () => {}, success: () => {}, warning: () => {} },
}));
vi.mock('@/lib/plugin-hooks', () => ({
identityHooks: {
onSignatureRender: { size: 0, transform: async (value: unknown) => value },
onIdentitySelect: { size: 0, emit: async () => {} },
},
templateHooks: {
onTemplateRender: { size: 0, transform: async (value: unknown) => value },
onTemplateApply: { size: 0, emit: async () => {} },
},
emailHooks: {
onComposerOpen: { call: async () => [] },
onRecipientChange: { call: async () => [] },
getRecipientSuggestions: { call: async () => [] },
onRecipientChipsChange: { transform: async (chips: unknown) => chips },
onDraftChange: { emit: () => {} },
onBeforeDraftAutoSave: { transform: async (draft: unknown) => draft },
onBeforeEmailSend: { intercept: async () => true, interceptOutcome: async () => 'allowed' },
onComposeSend: { takeOver: async () => 'default' },
onTransformOutgoingEmail: { transform: async (email: unknown) => email },
},
contactHooks: {
search: { call: async () => [] },
onProvideRecipientSuggestions: { transform: async (initial: unknown) => initial },
},
}));
vi.mock('@/lib/email-sanitization', () => ({
sanitizeSignatureHtml: (v: string) => v,
sanitizeEmailHtml: (v: string) => v,
parseHtmlSafely: (html: string) => new DOMParser().parseFromString(html, 'text/html'),
}));
vi.mock('@/lib/email-threading', () => ({
computeReplyThreadingHeaders: () => ({ inReplyTo: [], references: [] }),
}));
vi.mock('@/lib/signature-utils', () => ({
appendPlainTextSignature: (body: string) => body,
getPlainTextSignature: () => '',
}));
vi.mock('@/lib/sub-addressing', () => ({ generateSubAddress: () => '' }));
vi.mock('@/lib/debug', () => ({ debug: { log: () => {}, warn: () => {}, error: () => {} } }));
vi.mock('@/components/email/quoted-html', () => ({
buildQuotedHtmlBlock: () => '',
serializeEditorContent: () => '',
}));
vi.mock('@/lib/template-utils', () => ({ substitutePlaceholders: (s: string) => s }));
const DATA = {
to: 'bob@example.com',
cc: '',
bcc: '',
subject: 'Lunch',
body: '<p>Hello there</p>',
showCc: false,
showBcc: false,
selectedIdentityId: 'id-me',
subAddressTag: '',
mode: 'compose' as const,
draftId: null,
};
const footer = () => document.querySelector<HTMLElement>('[data-composer-footer]')!;
const header = () => document.querySelector<HTMLElement>('[data-composer-header]')!;
describe('a composer in a window of its own', () => {
it('has one Send, at the bottom end, with Discard as a bin right before it', () => {
render(<EmailComposer initialData={DATA} ownWindow={{}} />);
const sends = screen.getAllByTestId('composer-send');
expect(sends).toHaveLength(1);
expect(footer()).toContainElement(sends[0]);
expect(sends[0].className).not.toMatch(/(^|\s)hidden(\s|$)/);
expect(within(header()).queryByTestId('composer-send')).toBeNull();
const discard = screen.getByTestId('composer-discard');
expect(discard.querySelector('svg')).not.toBeNull();
// Right before Send, in the same group.
expect(discard.nextElementSibling).toBe(sends[0]);
});
it('shows the formatting toolbar, with no button to fold it away', () => {
render(<EmailComposer initialData={DATA} ownWindow={{}} />);
expect(screen.getByTestId('rich-text-editor')).toHaveAttribute('data-collapsed', 'false');
expect(screen.queryByRole('button', { name: 'formatting' })).toBeNull();
});
it('keeps the close button where the main window has it', () => {
render(<EmailComposer initialData={DATA} ownWindow={{}} />);
expect(screen.getByTestId('composer-close').className).not.toContain('order-first');
});
});
describe('a composer in the main window', () => {
it('keeps the phone layout for a phone: Send in the header there, toolbar folded', () => {
render(<EmailComposer initialData={DATA} />);
expect(within(header()).getByTestId('composer-send')).toBeInTheDocument();
expect(screen.getByTestId('rich-text-editor')).toHaveAttribute('data-collapsed', 'true');
expect(screen.getByRole('button', { name: 'formatting' })).toBeInTheDocument();
});
it('shows Discard as a bin too, with its name for screen readers', () => {
render(<EmailComposer initialData={DATA} />);
const discard = screen.getByTestId('composer-discard');
expect(discard).toHaveAccessibleName('discard');
expect(discard.querySelector('svg')).not.toBeNull();
expect(within(discard).getByText('discard').className).toContain('sr-only');
});
});
+18 -15
View File
@@ -1196,6 +1196,9 @@ export function EmailComposer({
// bar folded away behind "Aa" until asked for.
const mvWindow = useMvComposeWindow();
const [mvShowFormatting, setMvShowFormatting] = useState(false);
// A pop-out or quick compose window is narrower than a tablet, but it is a
// window on a computer: it keeps the main window's layout, not the phone's.
const phoneLayout = !ownWindow;
// "close" (X, Escape): save or discard. "discard" (the Discard button): the
// user already chose, so only confirm it.
const [closeDialogKind, setCloseDialogKind] = useState<'close' | 'discard'>('close');
@@ -4825,25 +4828,25 @@ export function EmailComposer({
{saveStatus === 'saving' && (
<div className="flex items-center gap-1 text-xs text-muted-foreground">
<Save className="w-3 h-3 animate-pulse" />
<span className="hidden md:inline">{t('saving')}</span>
<span className={phoneLayout ? "hidden md:inline" : undefined}>{t('saving')}</span>
</div>
)}
{saveStatus === 'saved' && (
<div className="flex items-center gap-1 text-xs text-emerald-600 dark:text-emerald-400">
<Check className="w-3 h-3" />
<span className="hidden md:inline">{savedOnDevice ? tOfflineDrafts('saved_on_device') : t('draft_saved')}</span>
<span className={phoneLayout ? "hidden md:inline" : undefined}>{savedOnDevice ? tOfflineDrafts('saved_on_device') : t('draft_saved')}</span>
</div>
)}
{saveStatus === 'error' && (
<div className="flex items-center gap-1 text-xs text-red-600 dark:text-red-400">
<X className="w-3 h-3" />
<span className="hidden md:inline">{t('save_failed')}</span>
<span className={phoneLayout ? "hidden md:inline" : undefined}>{t('save_failed')}</span>
</div>
)}
</div>
</div>
{/* Mobile: keep scheduled send reachable without consuming footer space. */}
{composerClient?.hasDelayedSend() || hasSendMenuActions ? (
{phoneLayout && (composerClient?.hasDelayedSend() || hasSendMenuActions ? (
<div className="relative inline-flex md:hidden">
<Button
onClick={() => handleSend()}
@@ -4883,14 +4886,14 @@ export function EmailComposer({
<Send className="w-4 h-4 me-1.5" />
{t('send')}
</Button>
)}
))}
{rightPanelToggle}
{popOutButton("hidden md:grid h-8 w-8 place-items-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground", "w-4 h-4")}
{popOutButton(cn(phoneLayout ? "hidden md:grid" : "grid", "h-8 w-8 place-items-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground"), "w-4 h-4")}
{/* Close at the top end (R4). On a phone it moves to the start, as
the phone's mail apps have it, with Send at the end. */}
<IconButton
onClick={() => handleClose()}
className="-me-2 max-md:order-first max-md:me-0 max-md:-ms-2 max-md:h-11 max-md:w-11"
className={phoneLayout ? "-me-2 max-md:order-first max-md:me-0 max-md:-ms-2 max-md:h-11 max-md:w-11" : "-me-2"}
label={tCommon('close')}
data-testid="composer-close"
data-own-window-close={ownWindow ? "" : undefined}
@@ -5300,7 +5303,7 @@ export function EmailComposer({
ariaInvalid={validationErrors.body}
ariaDescribedBy={`${fieldIdBase}-body-error`}
defaultTextStyle={composeStyle}
collapseToolbarOnMobile={!showFormattingOnMobile}
collapseToolbarOnMobile={phoneLayout && !showFormattingOnMobile}
toolbarPlacement={mvWindow ? (mvShowFormatting ? 'bottom' : 'hidden') : 'top'}
onEditorReady={handleEditorReady}
mentionCandidates={recipientMentionsEnabled ? mentionCandidates : undefined}
@@ -5565,7 +5568,7 @@ export function EmailComposer({
<span className="hidden @[40rem]/composer-bar:inline text-sm">{t('attach')}</span>
</Button>
)}
{!plainTextMode && (
{!plainTextMode && (mvWindow || phoneLayout) && (
<Button
variant="ghost"
size="icon"
@@ -5704,15 +5707,15 @@ export function EmailComposer({
data-testid="composer-discard"
aria-label={t('discard')}
title={t('discard')}
className="text-muted-foreground hover:text-destructive hover:bg-destructive/10 md:@max-[26rem]/composer-bar:px-2.5 max-md:@max-[23rem]/composer-bar:px-2.5"
className="px-2.5 text-muted-foreground hover:text-destructive hover:bg-destructive/10 max-md:h-11 max-md:w-11"
>
{/* Next to Send in a narrow composer the word runs over the tools on the left. */}
<Trash2 className="hidden w-4 h-4 max-md:@max-[23rem]/composer-bar:block md:block md:@[26rem]/composer-bar:hidden" aria-hidden="true" />
<span className="max-md:@max-[23rem]/composer-bar:hidden md:hidden md:@[26rem]/composer-bar:inline">{t('discard')}</span>
{/* A bin left of Send in every composer: the word ran over the tools in a narrow one. */}
<Trash2 className="w-4 h-4" aria-hidden="true" />
<span className="sr-only">{t('discard')}</span>
</Button>
)}
{composerClient?.hasDelayedSend() || hasSendMenuActions ? (
<div data-mv-send={mvWindow ? "" : undefined} className="relative hidden md:inline-flex">
<div data-mv-send={mvWindow ? "" : undefined} className={cn("relative", phoneLayout ? "hidden md:inline-flex" : "inline-flex")}>
<Button
onClick={() => handleSend()}
disabled={!canSend || isSending || isSavingAndClosing}
@@ -5744,7 +5747,7 @@ export function EmailComposer({
title={getSendTooltip()}
data-testid="composer-send"
data-mv-send={mvWindow ? "" : undefined}
className="hidden md:inline-flex"
className={phoneLayout ? "hidden md:inline-flex" : "inline-flex"}
>
<Send className="w-4 h-4 me-2" />
{t('send')}