fix: fold the formatting toolbar away on a phone behind a Formatting button

This commit is contained in:
Linus Rath
2026-10-11 20:21:47 +02:00
parent f025b2101d
commit e3f0f6cb38
4 changed files with 243 additions and 2 deletions
@@ -0,0 +1,212 @@
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';
// ─── Heavy component mocks (mirrors reply-addressing.test.tsx) ────────────────
const toastError = vi.hoisted(() => vi.fn());
// Shows whether the composer asked for the toolbar to be folded away.
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 }),
}));
// ─── Store mocks ──────────────────────────────────────────────────────────────
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 };
});
const updateSetting = vi.fn();
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: (...args: unknown[]) => updateSetting(...args),
};
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 };
});
// ─── Misc dependency mocks ────────────────────────────────────────────────────
vi.mock('@/stores/toast-store', () => ({
toast: { info: () => {}, error: toastError, success: () => {} },
}));
vi.mock('@/lib/plugin-hooks', () => ({
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 },
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 }));
// ─── Tests ────────────────────────────────────────────────────────────────────
// On a phone the formatting toolbar took two rows above the text.
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,
};
describe('formatting toolbar on a phone', () => {
beforeEach(() => {
toastError.mockClear();
updateSetting.mockClear();
});
it('is folded away until the Formatting button is pressed', () => {
render(<EmailComposer initialData={DATA} />);
const editor = screen.getByTestId('rich-text-editor');
expect(editor).toHaveAttribute('data-collapsed', 'true');
fireEvent.click(screen.getByRole('button', { name: 'formatting' }));
expect(editor).toHaveAttribute('data-collapsed', 'false');
});
});
+17 -1
View File
@@ -5,7 +5,7 @@ import { useFocusTrap } from "@/hooks/use-focus-trap";
import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { X, Paperclip, Send, Save, Check, Loader2, AlertCircle, FileText, BookmarkPlus, CalendarClock, ChevronDown, Search, Users, SlidersHorizontal, LayoutTemplate, Upload, FolderOpen } from "@/components/icons";
import { X, Paperclip, Send, Save, Check, Loader2, AlertCircle, FileText, BookmarkPlus, CalendarClock, ChevronDown, Search, Users, SlidersHorizontal, LayoutTemplate, Upload, FolderOpen, Type } from "@/components/icons";
import { ComposerToolbarMenu, ComposerToolbarMenuItem, ComposerToolbarMenuCheckItem } from "@/components/email/composer-toolbar-menu";
import { cn, formatFileSize, formatDateTime, generateUUID } from "@/lib/utils";
import { schedulePresets } from "@/lib/schedule-presets";
@@ -700,6 +700,8 @@ export function EmailComposer({
const [filesPicker, setFilesPicker] = useState<{ client: IJMAPClient; accountId?: string } | null>(null);
const [showSaveAsTemplate, setShowSaveAsTemplate] = useState(false);
const [showCloseDialog, setShowCloseDialog] = useState(false);
// The formatting toolbar is folded away on a phone until asked for.
const [showFormattingOnMobile, setShowFormattingOnMobile] = useState(false);
// "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');
@@ -3391,6 +3393,7 @@ export function EmailComposer({
onImageUpload={handleImageUpload}
placeholder={t('body_placeholder')}
hasError={validationErrors.body}
collapseToolbarOnMobile={!showFormattingOnMobile}
onEditorReady={(ed) => {
editorRef.current = ed;
if (!replyFocusedRef.current && (mode === 'reply' || mode === 'replyAll')) {
@@ -3548,6 +3551,19 @@ export function EmailComposer({
<span className="hidden sm:inline text-sm">{t('attach')}</span>
</Button>
)}
{!plainTextMode && (
<Button
variant="ghost"
size="icon"
onClick={() => setShowFormattingOnMobile((v) => !v)}
className={cn("h-9 w-9 md:hidden", showFormattingOnMobile && "bg-accent text-accent-foreground")}
title={t('formatting')}
aria-label={t('formatting')}
aria-pressed={showFormattingOnMobile}
>
<Type className="w-4 h-4" />
</Button>
)}
{templatesEnabled && (
<ComposerToolbarMenu icon={LayoutTemplate} label={t('templates_menu')} testId="composer-templates-menu">
{(close) => <>
+13 -1
View File
@@ -89,6 +89,11 @@ interface RichTextEditorProps {
onEditorReady?: (editor: Editor) => void;
/** Recipients an "@" in the text offers to mention; none turns it off. */
mentionCandidates?: MentionCandidate[];
/**
* Hide the formatting toolbar on a phone. It wraps onto two rows there and,
* with the address fields, left little room for the text above the keyboard.
*/
collapseToolbarOnMobile?: boolean;
}
function ToolbarButton({
@@ -180,6 +185,7 @@ export function RichTextEditor({
hasError,
onEditorReady,
mentionCandidates,
collapseToolbarOnMobile = false,
}: RichTextEditorProps) {
const rtlEditingSupport = useSettingsStore((st) => st.rtlEditingSupport);
const tComposer = useTranslations("email_composer");
@@ -431,7 +437,13 @@ export function RichTextEditor({
body text scrolling underneath stays hidden instead of showing
through, which a backdrop blur alone did not guarantee (browsers
that skip backdrop-filter drew the text sharp under the buttons). */}
<div className="sticky top-0 z-20 flex flex-wrap items-center gap-0.5 px-3 py-1.5 border-b border-border/50 bg-[color-mix(in_oklab,var(--color-muted)_30%,var(--color-background))]">
<div
data-testid="rich-text-toolbar"
className={cn(
"sticky top-0 z-20 flex flex-wrap items-center gap-0.5 px-3 py-1.5 border-b border-border/50 bg-[color-mix(in_oklab,var(--color-muted)_30%,var(--color-background))]",
collapseToolbarOnMobile && "max-md:hidden"
)}
>
{/* Font size - two baseline-aligned A's read as "size" at a glance;
once a size is chosen the button shows that number instead. */}
<div ref={fontSizeWrapperRef} className="relative">
+1
View File
@@ -628,6 +628,7 @@
"bcc": "BCC",
"subject": "Subject",
"body_placeholder": "Write your message...",
"formatting": "Formatting",
"send": "Send",
"cancel": "Cancel",
"attach": "Attach",