chore: merge the reviewed store, pop-outs and desktop core into the settings branch

Eviction now goes by the base's signal: `storeLost` and the `store-reset`
notice, with `bulwark-store-opened` as the marker and `prune-files` for files
with no key. The storage page and the lost count hang off that. What a user
picks is stored under `bulwark-offline-scope`, the key `offlineScopeFor`
reads, and `email-snapshot` follows the base's rule. `OfflineEnabled` is read
from the desktop bridge when it's there.
This commit is contained in:
Linus Rath
2026-11-03 10:40:47 +01:00
201 changed files with 11501 additions and 709 deletions
+2 -2
View File
@@ -263,7 +263,7 @@ export function AdminShell({ authenticated, isStalwartAutoLogin, configReadOnly,
const backHref = location.detail ? adminPath(location.page) : '/admin';
return (
<AdminShellContext.Provider value={contextValue}>
<div className="flex h-dvh flex-col bg-background pt-[env(safe-area-inset-top)]">
<div className="flex h-dvh flex-col bg-background pt-[var(--app-top-inset)]">
<div className="flex h-14 shrink-0 items-center gap-1 border-b border-border bg-background px-2">
{showIndex ? (
<a
@@ -361,7 +361,7 @@ export function AdminShell({ authenticated, isStalwartAutoLogin, configReadOnly,
return (
<AdminShellContext.Provider value={contextValue}>
<div className="flex h-dvh bg-background pt-[env(safe-area-inset-top)]">
<div className="flex h-dvh bg-background pt-[var(--app-top-inset)]">
{/* The same rail as mail and settings, with Admin as the current app. */}
<div className="flex w-14 shrink-0 flex-col bg-secondary" style={{ borderRight: '1px solid rgba(128, 128, 128, 0.3)' }}>
<NavigationRail collapsed adminActive />
+1 -1
View File
@@ -171,7 +171,7 @@ export function AdminSkeleton({ label, page, backLabel, searchLabel, labels, cla
<SkeletonRegion
surface="admin"
label={label}
className={cn("h-dvh bg-background pt-[env(safe-area-inset-top)]", className)}
className={cn("h-dvh bg-background pt-[var(--app-top-inset)]", className)}
>
{/* Desktop */}
<div className="hidden lg:flex h-full">
+1 -1
View File
@@ -109,7 +109,7 @@ export function ProFrameSkeleton({
<SkeletonRegion
surface="pro"
label={label}
className={cn("flex flex-col h-dvh bg-background overflow-hidden pt-[env(safe-area-inset-top)]", className)}
className={cn("flex flex-col h-dvh bg-background overflow-hidden pt-[var(--app-top-inset)]", className)}
>
<div data-pro-shell="" className="flex flex-1 overflow-hidden">
<RailSkeleton search className="flex" />
+1 -1
View File
@@ -294,7 +294,7 @@ export function AppShellSkeleton({
<SkeletonRegion
surface={surface}
label={label}
className="flex flex-col overflow-hidden pt-[env(safe-area-inset-top)] h-dvh bg-background lg:mv:bg-[var(--mv-canvas)] boot-out:hidden boot-pro-frame:hidden"
className="flex flex-col overflow-hidden pt-[var(--app-top-inset)] h-dvh bg-background lg:mv:bg-[var(--mv-canvas)] boot-out:hidden boot-pro-frame:hidden"
>
<MvTopBarSkeleton search={mvSearch} menu={mvMenu} className="hidden lg:mv:flex" />
<div className={cn("flex flex-1 min-h-0 overflow-hidden", rowClassName)}>
+3 -3
View File
@@ -2163,7 +2163,7 @@ export function CalendarApp({ linkSegments: routeSegments }: CalendarAppProps =
);
return (
<div className={cn("flex flex-col overflow-hidden pt-[env(safe-area-inset-top)]", mvShell ? "bg-[var(--mv-canvas)]" : "bg-background", isEmbedded ? "h-full" : "h-dvh")}>
<div className={cn("flex flex-col overflow-hidden pt-[var(--app-top-inset)]", mvShell ? "bg-[var(--mv-canvas)]" : "bg-background", isEmbedded ? "h-full" : "h-dvh")}>
{!isEmbedded && <SkipLink>{tShell("skip_to_content")}</SkipLink>}
<AppTopBannerSlot />
{refreshIndicator}
@@ -2221,7 +2221,7 @@ export function CalendarApp({ linkSegments: routeSegments }: CalendarAppProps =
"border-e border-border bg-secondary flex flex-col overflow-hidden flex-shrink-0",
!isResizing && "transition-[width] duration-300",
isNarrow && cn(
"absolute inset-y-0 start-0 z-50 w-72 pt-[env(safe-area-inset-top)]",
"absolute inset-y-0 start-0 z-50 w-72 pt-[var(--app-top-inset)]",
"transform transition-transform duration-300 ease-in-out",
!narrowSidebarOpen && "-translate-x-full rtl:translate-x-full"
)
@@ -2556,7 +2556,7 @@ export function CalendarApp({ linkSegments: routeSegments }: CalendarAppProps =
role="dialog"
aria-modal="true"
aria-label={editTask ? t("tasks.edit") : t("tasks.create")}
className={isPaneScoped ? "absolute inset-0 z-40 flex flex-col bg-background" : "fixed inset-0 z-50 flex flex-col bg-background"}
className={isPaneScoped ? "absolute inset-0 z-40 flex flex-col bg-background" : "fixed inset-0 z-50 flex flex-col bg-background pt-[var(--titlebar-inset)]"}
>
<TaskModal
key={editTask?.id ?? 'new-task'}
+1 -1
View File
@@ -288,7 +288,7 @@ export function EventModal({
const isPaneScoped = useIsPaneScoped();
const mobileRootClass = isPaneScoped
? "absolute inset-0 z-40 flex flex-col bg-background"
: "fixed inset-0 z-50 flex flex-col bg-background";
: "fixed inset-0 z-50 flex flex-col bg-background pt-[var(--titlebar-inset)]";
const isEdit = !!event;
const formatEventDate = useFormatEventDate();
const [mode, setMode] = useState<"view" | "edit">(isEdit && !startInEditMode ? "view" : "edit");
@@ -326,7 +326,7 @@ function CommandPalette({ onClose, onShowShortcuts }: { onClose: () => void; onS
aria-label={t("title")}
className={cn(
"w-full max-w-xl overflow-hidden rounded-lg border border-border bg-background text-foreground shadow-xl",
"max-sm:h-full max-sm:max-w-none max-sm:rounded-none max-sm:border-0 max-sm:pt-[env(safe-area-inset-top)]",
"max-sm:h-full max-sm:max-w-none max-sm:rounded-none max-sm:border-0 max-sm:pt-[var(--app-top-inset)]",
"flex flex-col",
)}
>
+2 -2
View File
@@ -1209,7 +1209,7 @@ function ContactsAppContent({ linkSegments: routeSegments }: ContactsAppProps =
};
return (
<div className={cn("flex flex-col overflow-hidden pt-[env(safe-area-inset-top)]", mvShell ? "bg-[var(--mv-canvas)]" : "bg-background", isEmbedded ? "h-full" : "h-dvh")}>
<div className={cn("flex flex-col overflow-hidden pt-[var(--app-top-inset)]", mvShell ? "bg-[var(--mv-canvas)]" : "bg-background", isEmbedded ? "h-full" : "h-dvh")}>
{!isEmbedded && <SkipLink>{tShell("skip_to_content")}</SkipLink>}
<AppTopBannerSlot />
{refreshIndicator}
@@ -1265,7 +1265,7 @@ function ContactsAppContent({ linkSegments: routeSegments }: ContactsAppProps =
"border-e border-border flex flex-col flex-shrink-0 bg-background",
!isSidebarResizing && "transition-[width] duration-300",
isNarrow && cn(
"absolute inset-y-0 start-0 z-50 w-72 pt-[env(safe-area-inset-top)]",
"absolute inset-y-0 start-0 z-50 w-72 pt-[var(--app-top-inset)]",
"transform transition-[transform,visibility] duration-300 ease-in-out",
!narrowSidebarOpen && "invisible -translate-x-full rtl:translate-x-full"
)
@@ -0,0 +1,364 @@
import React from 'react';
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { NextIntlClientProvider } from 'next-intl';
import { EmailComposer, type ComposerDraftData, type ComposerPopOut } from '../email-composer';
import { JMAPClient } from '@/lib/jmap/client';
import { useAuthStore } from '@/stores/auth-store';
import { useIdentityStore } from '@/stores/identity-store';
import { useSettingsStore } from '@/stores/settings-store';
import { useToastStore } from '@/stores/toast-store';
import en from '@/locales/en/common.json';
import { emailHooks } from '@/lib/plugin-hooks';
// Moving a draft to its own window, and a composer that is all its window
// shows. Real composer, stores and JMAP draft payloads over a synthetic server.
vi.unmock('next-intl');
vi.mock('@/components/email/rich-text-editor', () => ({ RichTextEditor: () => null }));
vi.mock('@/components/plugins/plugin-slot', () => ({ PluginSlot: () => 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-pro-multi-account-identities', () => ({
useProMultiAccountIdentities: () => ({ enabled: false, groups: [], allIdentities: [] }),
stripCrossAccountIdentityPrefix: (id: string) => ({ localAccountId: null, rawId: id }),
}));
type Props = React.ComponentProps<typeof EmailComposer>;
type Draft = { subject: string };
const original = { auth: useAuthStore.getState(), identity: useIdentityStore.getState(), settings: useSettingsStore.getState() };
let client: JMAPClient;
let creations: Draft[];
let rejectSave: boolean;
let deferSave: boolean;
let finishSave: (() => void) | undefined;
beforeEach(async () => {
creations = []; rejectSave = false; deferSave = false; finishSave = undefined;
vi.stubGlobal('fetch', vi.fn().mockResolvedValueOnce(new Response(JSON.stringify({
capabilities: { 'urn:ietf:params:jmap:core': {} },
accounts: { owner: { name: 'me@example.test', isPersonal: true, accountCapabilities: {} } },
primaryAccounts: { 'urn:ietf:params:jmap:mail': 'owner' },
apiUrl: 'https://synthetic.example.test/api', uploadUrl: 'https://synthetic.example.test/upload/{accountId}',
downloadUrl: 'https://synthetic.example.test/download/{accountId}/{blobId}/{name}', eventSourceUrl: '',
}))));
client = new JMAPClient('https://synthetic.example.test', 'me@example.test', 'synthetic-password');
await client.connect();
vi.spyOn(client, 'ping').mockResolvedValue(undefined);
vi.mocked(fetch).mockImplementation(async (_url, init) => {
const { methodCalls } = JSON.parse(String(init?.body)) as {
methodCalls: Array<[string, { create?: Record<string, Draft>; ids?: string[]; destroy?: string[] }, string]>;
};
const methodResponses = [];
for (const [method, args, id] of methodCalls) {
if (method === 'Mailbox/get') methodResponses.push([method, { list: [{ id: 'drafts', role: 'drafts' }] }, id]);
else if (method === 'Email/set' && args.create) {
const created: Record<string, { id: string }> = {};
for (const [key, draft] of Object.entries(args.create)) {
creations.push(draft);
if (deferSave) await new Promise<void>((resolve) => { finishSave = resolve; });
created[key] = { id: `saved-${creations.length}` };
}
methodResponses.push([method, rejectSave
? { notCreated: { draft: { type: 'serverFail', description: 'Synthetic refusal' } } }
: { created }, id]);
} else if (method === 'Email/get') methodResponses.push([method, { list: (args.ids ?? []).map((draftId) => ({ id: draftId, attachments: [] })) }, id]);
else if (method === 'Email/set') methodResponses.push([method, { destroyed: args.destroy ?? [] }, id]);
else methodResponses.push([method, {}, id]);
}
return new Response(JSON.stringify({ methodResponses }));
});
useAuthStore.setState({ client, activeAccountId: 'login', isAuthenticated: true, isLoading: false,
getClientForAccount: (id) => id === 'login' ? client : undefined,
getAllConnectedClients: () => new Map([['login', client]]),
});
useIdentityStore.setState({ identities: [{ id: 'me', email: 'me@example.test', name: 'Me', mayDelete: false } as never] });
useSettingsStore.setState({ defaultSendDelay: 0 } as never);
useToastStore.getState().clearToasts();
});
afterEach(() => {
cleanup();
client.disconnect();
useAuthStore.setState(original.auth);
useIdentityStore.setState(original.identity);
useSettingsStore.setState(original.settings);
vi.restoreAllMocks();
vi.unstubAllGlobals();
});
function mount(props: Partial<Props>) {
return render(
<NextIntlClientProvider locale="en" messages={en} timeZone="UTC">
<EmailComposer mode="compose" onClose={vi.fn()} {...props} />
</NextIntlClientProvider>,
);
}
const subjectField = () => screen.getByPlaceholderText(en.email_composer.subject_placeholder);
function target(shown = true): ComposerPopOut & { handed: ComposerDraftData[]; cancelled: number } {
const handed: ComposerDraftData[] = [];
const window = {
handed,
cancelled: 0,
handOver: async (data: ComposerDraftData) => { handed.push(data); return shown; },
cancel: () => { window.cancelled += 1; },
};
return window;
}
const DRAFT: ComposerDraftData = { to: '', cc: '', bcc: '', subject: 'Old', body: '', showCc: false, showBcc: false, selectedIdentityId: null, subAddressTag: '', mode: 'compose', draftId: null };
describe('"Open in new window" on a composer', () => {
it('is not there without the host offering it: browsers stay as they are', () => {
mount({});
expect(screen.queryByTestId('composer-open-in-window')).toBeNull();
});
it('opens the window inside the click, before any save', async () => {
const popOut = vi.fn(() => target());
mount({ popOut });
fireEvent.click(screen.getByTestId('composer-open-in-window'));
// Synchronously: a browser only opens a window for a user action.
expect(popOut).toHaveBeenCalledTimes(1);
await waitFor(() => expect(popOut.mock.results[0].value.handed).toHaveLength(1));
});
it('saves the text, hands over the same draft id, and closes here', async () => {
const window = target();
const onClose = vi.fn();
const onSaveState = vi.fn();
mount({ popOut: () => window, onClose, onSaveState });
fireEvent.change(subjectField(), { target: { value: 'Moves along' } });
fireEvent.click(screen.getByTestId('composer-open-in-window'));
await waitFor(() => expect(window.handed).toHaveLength(1));
const data = window.handed[0];
expect(data.subject).toBe('Moves along');
expect(creations.map((draft) => draft.subject)).toEqual(['Moves along']);
expect(data.draftId).toBe('saved-1');
expect(data.unsaved).toBe(false);
expect(onClose).toHaveBeenCalledTimes(1);
// Not left behind in the host's "continue draft" slot.
cleanup();
expect(onSaveState).not.toHaveBeenCalled();
});
it('keeps a draft that is already saved under its id, without saving again', async () => {
const window = target();
mount({
popOut: () => window,
initialData: { to: '', cc: '', bcc: '', subject: 'Old', body: '', showCc: false, showBcc: false, selectedIdentityId: null, subAddressTag: '', mode: 'compose', draftId: 'existing' },
});
fireEvent.click(screen.getByTestId('composer-open-in-window'));
await waitFor(() => expect(window.handed).toHaveLength(1));
expect(window.handed[0].draftId).toBe('existing');
expect(creations).toEqual([]);
});
it('keeps the composer and calls it off when the other window never shows it', async () => {
const window = target(false);
const onClose = vi.fn();
mount({ popOut: () => window, onClose });
fireEvent.change(subjectField(), { target: { value: 'Still here' } });
fireEvent.click(screen.getByTestId('composer-open-in-window'));
await waitFor(() => expect(window.cancelled).toBe(1));
expect(onClose).not.toHaveBeenCalled();
expect((subjectField() as HTMLInputElement).value).toBe('Still here');
expect(useToastStore.getState().toasts.map((toast) => toast.title)).toContain(en.pwaWindows.window_not_ready);
});
it('does not close here before the other window shows it, also after a failed save', async () => {
rejectSave = true;
let show: (shown: boolean) => void = () => {};
const handed: ComposerDraftData[] = [];
const onClose = vi.fn();
mount({
popOut: () => ({ cancel: vi.fn(), handOver: (data) => { handed.push(data); return new Promise((resolve) => { show = resolve; }); } }),
onClose,
});
fireEvent.change(subjectField(), { target: { value: 'Refused' } });
fireEvent.click(screen.getByTestId('composer-open-in-window'));
await waitFor(() => expect(handed).toHaveLength(1));
expect(handed[0].unsaved).toBe(true);
expect(onClose).not.toHaveBeenCalled();
show(true);
await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1));
});
it('takes the send options along', async () => {
const window = target();
mount({ popOut: () => window, initialData: { ...DRAFT, requestReadReceipt: true, requestDsn: true, requireTls: true } });
fireEvent.click(screen.getByTestId('composer-open-in-window'));
await waitFor(() => expect(window.handed).toHaveLength(1));
expect(window.handed[0]).toMatchObject({ requestReadReceipt: true, requestDsn: true, requireTls: true });
});
it('stays open and says why when the browser blocks the window', async () => {
const onClose = vi.fn();
mount({ popOut: () => null, onClose });
fireEvent.change(subjectField(), { target: { value: 'Stays' } });
fireEvent.click(screen.getByTestId('composer-open-in-window'));
await waitFor(() => expect(useToastStore.getState().toasts.map((toast) => toast.title)).toContain(en.pwaWindows.popup_blocked));
expect(onClose).not.toHaveBeenCalled();
expect((subjectField() as HTMLInputElement).value).toBe('Stays');
});
});
describe('a composer that is all its window shows', () => {
function unload() {
const event = new Event('beforeunload', { cancelable: true });
window.dispatchEvent(event);
return event;
}
it('asks before the window closes with unsaved text, and saves meanwhile', async () => {
const onUnloadState = vi.fn();
mount({ ownWindow: { onUnloadState } });
fireEvent.change(subjectField(), { target: { value: 'Not saved yet' } });
const event = unload();
expect(event.defaultPrevented).toBe(true);
expect(onUnloadState.mock.calls[0][0]).toMatchObject({ subject: 'Not saved yet', unsaved: true });
await waitFor(() => expect(creations.map((draft) => draft.subject)).toEqual(['Not saved yet']));
});
it('hands unsaved text to another window as it closes, with no prompt and no save of its own', () => {
const rescueDraft = vi.fn(() => true);
mount({ ownWindow: { rescueDraft } });
fireEvent.change(subjectField(), { target: { value: 'Rescued' } });
expect(unload().defaultPrevented).toBe(false);
expect(rescueDraft).toHaveBeenCalledTimes(1);
expect(rescueDraft.mock.calls[0]).toEqual([expect.objectContaining({ subject: 'Rescued', draftId: undefined })]);
expect(creations).toEqual([]);
});
it('replaces the version it holds when another window saves it', () => {
const rescueDraft = vi.fn(() => true);
mount({
ownWindow: { rescueDraft },
initialData: { to: '', cc: '', bcc: '', subject: 'Old', body: '', showCc: false, showBcc: false, selectedIdentityId: null, subAddressTag: '', mode: 'compose', draftId: 'saved-before' },
});
fireEvent.change(subjectField(), { target: { value: 'New' } });
unload();
expect(rescueDraft.mock.calls[0]).toEqual([expect.objectContaining({ subject: 'New', draftId: 'saved-before' })]);
});
it('asks and saves itself when no other window can take it', async () => {
const rescueDraft = vi.fn(() => false);
mount({ ownWindow: { rescueDraft } });
fireEvent.change(subjectField(), { target: { value: 'Nobody home' } });
expect(unload().defaultPrevented).toBe(true);
await waitFor(() => expect(creations.map((draft) => draft.subject)).toEqual(['Nobody home']));
});
it('does not hand it over after a failed save: that window would likely fail too, with nobody looking', async () => {
rejectSave = true;
const rescueDraft = vi.fn(() => true);
mount({ ownWindow: { rescueDraft } });
fireEvent.change(subjectField(), { target: { value: 'Server down' } });
await waitFor(() => expect(creations).toHaveLength(1), { timeout: 4000 });
await waitFor(() => expect(unload().defaultPrevented).toBe(true));
expect(rescueDraft).not.toHaveBeenCalled();
});
it('does not hand it over while the browser is offline', () => {
const onLine = vi.spyOn(navigator, 'onLine', 'get').mockReturnValue(false);
const rescueDraft = vi.fn(() => true);
mount({ ownWindow: { rescueDraft } });
fireEvent.change(subjectField(), { target: { value: 'Wi-Fi gone' } });
expect(unload().defaultPrevented).toBe(true);
expect(rescueDraft).not.toHaveBeenCalled();
onLine.mockRestore();
});
it('does not hand it over with a save running: two saves would make two drafts', async () => {
deferSave = true;
const rescueDraft = vi.fn(() => true);
mount({ ownWindow: { rescueDraft } });
fireEvent.change(subjectField(), { target: { value: 'Saving' } });
await waitFor(() => expect(creations).toHaveLength(1), { timeout: 4000 });
expect(unload().defaultPrevented).toBe(true);
expect(rescueDraft).not.toHaveBeenCalled();
finishSave?.();
});
it('asks when the window closes during a send', async () => {
let finish: () => void = () => {};
const onSend = vi.fn(() => new Promise<void>((resolve) => { finish = resolve; }));
const onClose = vi.fn();
mount({
ownWindow: {}, onSend, onClose,
initialData: { ...DRAFT, to: 'them@example.test', subject: 'Going', body: '<p>Hello</p>' },
});
fireEvent.click(screen.getAllByTestId('composer-send')[0]);
await waitFor(() => expect(onSend).toHaveBeenCalled(), { timeout: 4000 });
expect(unload().defaultPrevented).toBe(true);
finish();
await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1));
expect(unload().defaultPrevented).toBe(false);
});
it('counts text handed in unsaved as unsaved: it asks, and saves it', async () => {
const rescueDraft = vi.fn(() => false);
mount({ ownWindow: { rescueDraft }, initialData: { ...DRAFT, subject: 'Handed in', unsaved: true } });
expect(unload().defaultPrevented).toBe(true);
await waitFor(() => expect(creations.map((draft) => draft.subject)).toEqual(['Handed in']));
});
it('saves text handed in unsaved by itself, untouched', async () => {
mount({ ownWindow: {}, initialData: { ...DRAFT, subject: 'Autosaved after the move', unsaved: true } });
await waitFor(() => expect(creations.map((draft) => draft.subject)).toEqual(['Autosaved after the move']), { timeout: 4000 });
});
it('keeps the draft to itself when a plugin has a say in what is saved', async () => {
const rescueDraft = vi.fn(() => true);
const hook = emailHooks.onBeforeDraftAutoSave.register('test', (draft: unknown) => draft as never);
try {
mount({ ownWindow: { rescueDraft } });
fireEvent.change(subjectField(), { target: { value: 'Encrypted, say' } });
expect(unload().defaultPrevented).toBe(true);
expect(rescueDraft).not.toHaveBeenCalled();
} finally {
hook.dispose();
}
});
it('lets an untouched composer go without a word', () => {
mount({ ownWindow: {} });
expect(unload().defaultPrevented).toBe(false);
expect(creations).toEqual([]);
});
it('does not ask again, or save again, once the autosave has it', async () => {
const onDraftSaved = vi.fn();
mount({ ownWindow: { onDraftSaved } });
fireEvent.change(subjectField(), { target: { value: 'Autosaved' } });
await waitFor(() => expect(creations).toHaveLength(1), { timeout: 4000 });
await waitFor(() => expect(onDraftSaved).toHaveBeenCalled());
expect(unload().defaultPrevented).toBe(false);
expect(creations).toHaveLength(1);
});
it('keeps today\'s behaviour outside a window of its own: no prompt', () => {
mount({});
fireEvent.change(subjectField(), { target: { value: 'In the main window' } });
expect(unload().defaultPrevented).toBe(false);
});
it('closes itself after the send, and writes no draft on the way out', async () => {
const onClose = vi.fn();
const onSend = vi.fn(async () => {});
mount({
ownWindow: {}, onSend, onClose,
initialData: { to: 'them@example.test', cc: '', bcc: '', subject: 'Off it goes', body: '<p>Hello</p>', showCc: false, showBcc: false, selectedIdentityId: null, subAddressTag: '', mode: 'compose', draftId: null },
});
fireEvent.click(screen.getAllByTestId('composer-send')[0]);
await waitFor(() => expect(onSend).toHaveBeenCalled(), { timeout: 4000 });
await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1));
const saved = creations.length;
expect(unload().defaultPrevented).toBe(false);
expect(creations).toHaveLength(saved);
});
});
@@ -10,6 +10,7 @@ import { useSettingsStore } from '@/stores/settings-store';
import { useToastStore } from '@/stores/toast-store';
import { ToastContainer } from '@/components/ui/toast';
import en from '@/locales/en/common.json';
import { setDownloadGuard } from '@/lib/download-guard';
// Keep the actual viewer handler, translations, JMAP routing/auth/retries and
// JSZip. Stub unrelated viewer hosts, as in the other viewer component tests.
@@ -312,3 +313,147 @@ describe('Download all attachments', () => {
await p.assertZip(['report.txt', 'data.bin'], [alpha, beta]);
});
});
describe('Save all attachments to a folder', () => {
/** A folder as the picker hands it out; `failOn` makes that file's write fail. */
function fakeFolder(failOn?: string) {
const files = new Map<string, Blob | Uint8Array>();
return {
files,
name: 'Downloads',
async getFileHandle(name: string, options?: { create?: boolean }) {
if (!files.has(name) && !options?.create) throw Object.assign(new Error('missing'), { name: 'NotFoundError' });
return {
createWritable: async () => ({
write: async (data: Blob | Uint8Array) => {
if (name === failOn) throw new Error('Disk full');
files.set(name, data);
},
close: async () => {},
abort: async () => {},
}),
};
},
async removeEntry(name: string) { files.delete(name); },
};
}
function stubPicker(result: () => Promise<unknown>) {
const picker = vi.fn(result);
(window as unknown as { showDirectoryPicker?: unknown }).showDirectoryPicker = picker;
return picker;
}
const saveButton = () => screen.getByTestId('attachments-save-to-folder');
afterEach(() => {
delete (window as unknown as { showDirectoryPicker?: unknown }).showDirectoryPicker;
setDownloadGuard(null);
});
it('is not offered where the browser cannot ask for a folder, and the zip stays', async () => {
await openViewer();
expect(screen.queryByTestId('attachments-save-to-folder')).toBeNull();
expect(screen.getAllByTitle('Download all')[0]).toBeVisible();
});
it('keeps one row in a narrow pane: with two buttons, just the icons there, and always a name', async () => {
stubPicker(async () => fakeFolder());
await openViewer();
const save = saveButton();
expect(save.getAttribute('aria-label')).toBe(en.pwaWindows.save_all_to_folder);
expect(save.querySelector('span')?.className).toContain('hidden @xl:inline');
const download = screen.getAllByTitle('Download all')[0];
expect(download.getAttribute('aria-label')).toBe('Download all');
expect(download.querySelector('span')?.className).toContain('hidden @xl:inline');
expect(screen.getAllByTestId('reader-attachments')[0].className).toContain('@container');
});
it('shows the zip button as it was where there is only that one', async () => {
await openViewer();
const download = screen.getAllByTitle('Download all')[0];
expect(download.querySelector('span')?.className ?? '').not.toContain('hidden');
expect(download.textContent).toContain('Download all');
});
it('writes each attachment to the folder, names the folder, and starts no zip', async () => {
const folder = fakeFolder();
const picker = stubPicker(async () => folder);
const p = await openViewer();
p.success();
fireEvent.click(saveButton());
expect(picker).toHaveBeenCalledWith(expect.objectContaining({ mode: 'readwrite' }));
await waitFor(() => expect(useToastStore.getState().toasts).toEqual([
expect.objectContaining({ type: 'success', title: 'Saved 2 attachments to Downloads.' }),
]));
expect([...folder.files.keys()]).toEqual(['report.txt', 'data.bin']);
p.noDownload();
});
it('asks the device policy before the picker: no save-all when downloads are blocked', async () => {
const picker = stubPicker(async () => fakeFolder());
const p = await openViewer();
setDownloadGuard(() => false);
fireEvent.click(saveButton());
await act(async () => {});
expect(picker).not.toHaveBeenCalled();
expect(p.fetchMock).not.toHaveBeenCalled();
});
it('asks again before each file: a policy turning on stops the rest and says how many went', async () => {
const folder = fakeFolder();
stubPicker(async () => folder);
const p = await openViewer();
p.success();
let asked = 0;
// The click, then the first file's two checks. Off from the second file on.
setDownloadGuard(() => ++asked <= 3);
fireEvent.click(saveButton());
await waitFor(() => expect(useToastStore.getState().toasts).toEqual([
expect.objectContaining({ type: 'warning', title: 'Saved 1 of 2 attachments to Downloads.' }),
]));
expect([...folder.files.keys()]).toEqual(['report.txt']);
});
it('does nothing when the picker is closed', async () => {
stubPicker(async () => { throw Object.assign(new Error('closed'), { name: 'AbortError' }); });
const p = await openViewer();
fireEvent.click(saveButton());
await act(async () => {});
expect(p.fetchMock).not.toHaveBeenCalled();
expect(useToastStore.getState().toasts).toEqual([]);
p.noDownload();
});
it('falls back to the zip when the browser refuses the picker', async () => {
stubPicker(async () => { throw Object.assign(new Error('refused'), { name: 'SecurityError' }); });
const p = await openViewer();
p.success();
fireEvent.click(saveButton());
await waitFor(() => expect(p.downloads).toHaveLength(1), { timeout: 5000 });
await p.assertZip(['report.txt', 'data.bin'], [alpha, beta]);
});
it('says how many were saved when a write fails midway', async () => {
const folder = fakeFolder('data.bin');
stubPicker(async () => folder);
const p = await openViewer();
p.success();
fireEvent.click(saveButton());
await waitFor(() => expect(useToastStore.getState().toasts).toEqual([
expect.objectContaining({ type: 'warning', title: 'Saved 1 of 2 attachments to Downloads.' }),
]));
expect([...folder.files.keys()]).toEqual(['report.txt']);
});
it('says so when nothing could be written', async () => {
const folder = fakeFolder('report.txt');
stubPicker(async () => folder);
const p = await openViewer();
p.success();
fireEvent.click(saveButton());
await waitFor(() => expect(useToastStore.getState().toasts).toEqual([
expect.objectContaining({ type: 'error', title: 'Could not save the attachments to Downloads.' }),
]));
});
});
+275 -56
View File
@@ -3,6 +3,7 @@
import React, { useState, useEffect, useRef, useCallback, useMemo } from "react";
import { useMvComposeWindow } from "@/components/email/mv-compose-context";
import { useLocale, useTranslations } from "next-intl";
import { isServerOutage } from "@/lib/jmap/offline-hooks";
import { Button, TOUCH_HIT_AREA } from "@/components/ui/button";
import { ConfirmDialog } from "@/components/ui/confirm-dialog";
import { Dialog } from "@/components/ui/dialog";
@@ -166,6 +167,7 @@ import { htmlToPlainText as htmlToPlainTextShared } from "@/lib/html-to-text";
import { fileStorage } from "@/lib/plugin-storage";
import { usePolicyStore } from "@/stores/policy-store";
import { registerComposeFlush } from "@/lib/compose-flush-registry";
import type { RescuedDraft } from "@/lib/popout/channel";
import { toUnicodeEmail } from "@/lib/idn";
/**
@@ -257,6 +259,10 @@ export interface ComposerDraftData {
* next save/send rebuilds the draft without them - silent data loss (#849).
*/
attachments?: Array<{ blobId: string; name?: string; type?: string; size: number; cid?: string; disposition?: string; sourceAccountId?: string }>;
/** The send options picked so far; absent, the defaults. Carried to another window. */
requestReadReceipt?: boolean;
requestDsn?: boolean;
requireTls?: boolean;
/** When set, overrides the header From: and the envelope MAIL FROM, where the server allows it. */
fromOverrideEmail?: string;
fromOverrideName?: string;
@@ -289,6 +295,13 @@ export interface ComposerDraftData {
unsaved?: boolean;
}
/** The window a draft moves to; see EmailComposerProps.popOut. */
export interface ComposerPopOut {
/** True once the composer is on screen there. Until then this one keeps the text. */
handOver(data: ComposerDraftData): Promise<boolean>;
cancel(): void;
}
interface EmailComposerProps {
/**
* Submits the message. Resolves `false` when the host sent nothing (it has
@@ -352,6 +365,29 @@ interface EmailComposerProps {
*/
onDiscardDraft?: (draftId: string, draft?: { accountId?: string; localAccountId?: string }) => void;
onSaveState?: (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
* takes the draft, or null when no window opened. The composer then saves,
* hands the draft over under the same draft id, and closes here.
*/
popOut?: () => ComposerPopOut | null;
/**
* This composer is all a window shows (lib/popout). It closes itself once a
* message has gone. Closing the window with unsaved text hands the draft to
* another window to save, or asks first when there is none.
*/
ownWindow?: {
/** The state as the window unloads, for a reload to start from. */
onUnloadState?: (data: ComposerDraftData) => void;
/** A save reached the server, for other windows showing the Drafts folder. */
onDraftSaved?: () => void;
/**
* Hands a draft to another window to save as this one closes: a request
* started now wouldn't survive. False when that can't be done safely.
*/
rescueDraft?: (draft: RescuedDraft) => boolean;
};
className?: string;
initialDraftText?: string;
initialData?: ComposerDraftData | null;
@@ -504,6 +540,8 @@ export function EmailComposer({
requestCloseRef,
onDiscardDraft,
onSaveState,
popOut,
ownWindow,
className,
initialDraftText: initialDraftTextProp,
initialData: initialDataProp,
@@ -517,11 +555,13 @@ export function EmailComposer({
}: EmailComposerProps) {
const t = useTranslations('email_composer');
const tCommon = useTranslations('common');
const tWindows = useTranslations('pwaWindows');
const tQuote = useTranslations('quote_header');
const tViewer = useTranslations('email_viewer');
const tClassification = useTranslations('classification');
const tProofreading = useTranslations('proofreading');
const tOffline = useTranslations('offline');
const tOfflineNotes = useTranslations('offlineConflicts');
const tSendGuards = useTranslations('send_guards');
const timeFormat = useSettingsStore((state) => state.timeFormat);
const plainTextModeDefault = useSettingsStore((state) => state.plainTextMode);
@@ -989,11 +1029,11 @@ export function EmailComposer({
input.trim() ? [...chips, parseRecipient(input)] : chips;
const [isDraggingChipOverCc, setIsDraggingChipOverCc] = useState(false);
const [isDraggingChipOverBcc, setIsDraggingChipOverBcc] = useState(false);
const [requestReadReceipt, setRequestReadReceipt] = useState(requestReadReceiptDefault);
const [requestReadReceipt, setRequestReadReceipt] = useState(initialData?.requestReadReceipt ?? requestReadReceiptDefault);
// SMTP submission options, offered only when the server advertises the
// extension (RFC 8621 §1.3 submissionExtensions).
const [requestDsn, setRequestDsn] = useState(false);
const [requireTls, setRequireTls] = useState(false);
const [requestDsn, setRequestDsn] = useState(initialData?.requestDsn ?? false);
const [requireTls, setRequireTls] = useState(initialData?.requireTls ?? false);
// Message priority (#970): normal writes no header at all.
const [priority, setPriority] = useState<MessagePriority>(initialData?.priority ?? 'normal');
const priorityRef = useRef(priority);
@@ -1797,6 +1837,9 @@ export function EmailComposer({
if (priority !== initialPriorityRef.current) isDirtyRef.current = true;
const initialLabelChoiceRef = useRef(classification.choice);
if (classification.choice !== initialLabelChoiceRef.current) isDirtyRef.current = true;
// Text handed in that the server doesn't have yet is unsaved work, however
// little it differs from what this composer started with.
if (initialData?.unsaved && changeVersionRef.current !== savedVersionRef.current) isDirtyRef.current = true;
if (uneditedRef.current) isDirtyRef.current = false;
// Changes only the user makes, also without typing: a picked recipient, a
// removed attachment, a priority. Handed-in files move the count they're
@@ -1862,37 +1905,84 @@ export function EmailComposer({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [effectiveSessionKey]);
const rescueRequestRef = useRef<() => RescuedDraft | null>(() => null);
const closedRef = useRef(false);
// The composer as a host needs it to bring it back: after a remount, in
// another window. Read through refs, so a handler set up once stays current.
const snapshotStateRef = useRef<() => ComposerDraftData>(() => { throw new Error('Not mounted'); });
snapshotStateRef.current = () => ({
...stateRef.current,
draftAccountId: draftAccountIdRef.current,
mode,
replyTo,
priority: priorityRef.current,
classification: classificationRef.current.draftChoice,
// Edits the last save didn't cover; a minimised composer with
// none needs no save before an automatic sign-out.
unsaved: !uneditedRef.current && (changeVersionRef.current !== savedVersionRef.current || saveFailedRef.current),
...(uneditedRef.current ? { unedited: true } : {}),
requestReadReceipt,
requestDsn,
requireTls,
});
// Auto-save state on unmount (when user navigates away without explicitly closing)
useEffect(() => {
return () => {
if (explicitCloseRef.current) return;
// Kept in the host's memory across a remount, handed-in or not. Only
// the server stays out of it.
if (onSaveState && (isDirtyRef.current || uneditedRef.current)) {
const s = stateRef.current;
onSaveState({
...s,
draftAccountId: draftAccountIdRef.current,
mode,
replyTo,
priority: priorityRef.current,
classification: classificationRef.current.draftChoice,
// Edits the last save didn't cover; a minimised composer with
// none needs no save before an automatic sign-out.
unsaved: !uneditedRef.current && (changeVersionRef.current !== savedVersionRef.current || saveFailedRef.current),
...(uneditedRef.current ? { unedited: true } : {}),
});
}
if (onSaveState && (isDirtyRef.current || uneditedRef.current)) onSaveState(snapshotStateRef.current());
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// Auto-save draft to server on page close (best-effort)
const ownWindowRef = useRef(ownWindow);
ownWindowRef.current = ownWindow;
useEffect(() => {
const handleBeforeUnload = () => {
if (isDirtyRef.current) {
saveDraftRef.current();
const handleBeforeUnload = (event: BeforeUnloadEvent) => {
const own = ownWindowRef.current;
if (!own) {
if (isDirtyRef.current) {
saveDraftRef.current();
}
return;
}
// This composer closed itself: nothing left to keep.
if (closedRef.current) return;
// Closing now could stop a send halfway.
if (isSendingRef.current) {
event.preventDefault();
return;
}
// Sent, discarded or saved and closed.
if (explicitCloseRef.current || sentRef.current) return;
if (!isDirtyRef.current) return;
const state = snapshotStateRef.current();
own.onUnloadState?.(state);
if (!state.unsaved) return;
// A request started while a window closes is dropped, so another window
// saves it, but not when:
// - a plugin may change or stop what is saved, as it only runs here (and
// rescueDraft says no while plugins haven't started);
// - the last save failed or the browser is offline, so that window's
// would likely fail too, with nobody looking;
// - a save is running: its new id is unknown, and two saves make two drafts.
const canHandOver = own.rescueDraft
&& emailHooks.onBeforeDraftAutoSave.size === 0
&& !saveFailedRef.current
&& navigator.onLine !== false
&& !inflightSaveRef.current;
if (canHandOver) {
const draft = rescueRequestRef.current();
if (!draft || own.rescueDraft?.(draft)) return;
}
// Nobody can take it. The prompt keeps the window open: "stay" lets the
// save run, and "leave" is the user's own choice.
saveDraftRef.current();
event.preventDefault();
};
window.addEventListener('beforeunload', handleBeforeUnload);
return () => window.removeEventListener('beforeunload', handleBeforeUnload);
@@ -2702,28 +2792,17 @@ export function EmailComposer({
}, [previewAttachment, composerClient]);
// Auto-save draft functionality
// `auto`: the debounced save while typing. Only that one may be skipped
// by a plugin; saves on close and before send always run, or the text
// would be lost.
const saveDraftOnce = async (auto = false): Promise<string | null> => {
if (!client || !composerClient) return null;
const versionAtStart = changeVersionRef.current;
const draftRecipients = () => ({
toAddresses: expandRecipients(withInput(to, toInput)).map(r => formatRecipient(r.name, r.email)),
ccAddresses: expandRecipients(withInput(cc, ccInput)).map(r => formatRecipient(r.name, r.email)),
bccAddresses: expandRecipients(withInput(bcc, bccInput)).map(r => formatRecipient(r.name, r.email)),
});
const toAddresses = expandRecipients(withInput(to, toInput)).map(r => formatRecipient(r.name, r.email));
const ccAddresses = expandRecipients(withInput(cc, ccInput)).map(r => formatRecipient(r.name, r.email));
const bccAddresses = expandRecipients(withInput(bcc, bccInput)).map(r => formatRecipient(r.name, r.email));
if (!toAddresses.length && !subject && !(plainTextMode ? body.trim() : htmlToPlainText(body).trim())) {
return null;
}
try {
await rehomeForeignBlobs();
} catch (error) {
// The save below then fails with blobNotFound and reports it.
debug.warn('email', 'Failed to copy forwarded parts to the sending account:', error);
}
const draftHasContent = (toAddresses: string[]) =>
!!toAddresses.length || !!subject || !!(plainTextMode ? body.trim() : htmlToPlainText(body).trim());
// What a saved draft holds, as of now. No awaits: a closing window has none to spare.
const draftContent = () => {
// Prepare attachments for draft. cid/disposition ride along so inline
// parts of a re-opened draft keep matching the body's cid: references.
const uploadedAttachments = attachmentsRef.current
@@ -2757,6 +2836,82 @@ export function EmailComposer({
: appendPlainTextSignature(body, signatureIdentity, { separator: signatureSeparatorEnabled }))
: htmlToPlainText(draftHtmlBody!, imageAltText);
return { uploadedAttachments, draftHtmlBody, draftTextBody };
};
// Get the selected identity or primary identity
// Generate sub-addressed email if tag is set
const draftSender = () => {
const identityFromEmail = currentIdentity?.email
? subAddressTag
? generateSubAddress(currentIdentity.email, subAddressTag, subAddressDelimiter)
: currentIdentity.email
: undefined;
const fromEmail = (fromOverrideEnabled && fromOverrideEmail.trim())
? fromOverrideEmail.trim()
: identityFromEmail;
const fromName = (fromOverrideEnabled && fromOverrideEmail.trim())
? (fromOverrideName.trim() || undefined)
: (currentIdentity?.name || undefined);
return { fromEmail, fromName };
};
// The save below, for another window to make as this one closes. Null with nothing to save.
rescueRequestRef.current = () => {
const { toAddresses, ccAddresses, bccAddresses } = draftRecipients();
if (!draftHasContent(toAddresses)) return null;
const { uploadedAttachments, draftHtmlBody, draftTextBody } = draftContent();
const { fromEmail, fromName } = draftSender();
const login = loginFor(currentIdentityParts.localAccountId);
const previousLogin = draftLocalAccountIdRef.current;
// A version saved through another login can't be replaced from this one.
const replaces = !previousLogin || previousLogin === login;
return {
localAccountId: login,
to: toAddresses,
subject,
body: draftTextBody,
cc: ccAddresses,
bcc: bccAddresses,
identityId: currentIdentityRawId,
fromEmail,
draftId: replaces ? draftIdRef.current || undefined : undefined,
attachments: uploadedAttachments,
fromName,
htmlBody: draftHtmlBody,
inReplyTo: replyThreadingHeaders?.inReplyTo,
references: replyThreadingHeaders?.references,
options: {
priority,
previousDraftAccountId: replaces ? draftAccountIdRef.current : undefined,
classification: classificationRef.current.draftChoice,
},
state: snapshotStateRef.current(),
};
};
// `auto`: the debounced save while typing. Only that one may be skipped
// by a plugin; saves on close and before send always run, or the text
// would be lost.
const saveDraftOnce = async (auto = false): Promise<string | null> => {
if (!client || !composerClient) return null;
const versionAtStart = changeVersionRef.current;
const { toAddresses, ccAddresses, bccAddresses } = draftRecipients();
if (!draftHasContent(toAddresses)) {
return null;
}
try {
await rehomeForeignBlobs();
} catch (error) {
// The save below then fails with blobNotFound and reports it.
debug.warn('email', 'Failed to copy forwarded parts to the sending account:', error);
}
const { uploadedAttachments, draftHtmlBody, draftTextBody } = draftContent();
// Create a hash of current data to compare with last saved. Hashing the
// composed bodies (not the raw editor body) means a signature that changed
// under an unchanged body - switching identity, toggling the separator -
@@ -2776,19 +2931,7 @@ export function EmailComposer({
setSaveStatus('saving');
// Get the selected identity or primary identity
// Generate sub-addressed email if tag is set
const identityFromEmail = currentIdentity?.email
? subAddressTag
? generateSubAddress(currentIdentity.email, subAddressTag, subAddressDelimiter)
: currentIdentity.email
: undefined;
const fromEmail = (fromOverrideEnabled && fromOverrideEmail.trim())
? fromOverrideEmail.trim()
: identityFromEmail;
const fromName = (fromOverrideEnabled && fromOverrideEmail.trim())
? (fromOverrideName.trim() || undefined)
: (currentIdentity?.name || undefined);
const { fromEmail, fromName } = draftSender();
try {
const previousDraftId = draftIdRef.current;
@@ -2943,6 +3086,7 @@ export function EmailComposer({
// Only the save the user asked for is read out: autosave would say it
// every minute, and the save before sending is followed by "Sent".
if (opts.announce && id && !saveFailedRef.current) announceStatus(t('draft_saved'));
if (id && !saveFailedRef.current) ownWindowRef.current?.onDraftSaved?.();
return id;
})();
inflightSaveRef.current = promise;
@@ -4040,8 +4184,10 @@ export function EmailComposer({
// Clear ref so unmount effect doesn't re-save
stateRef.current = { to: '', cc: '', bcc: '', subject: '', body: '', showCc: false, showBcc: false, selectedIdentityId: null, subAddressTag: '', draftId: null, draftAccountId: undefined, draftLocalAccountId: undefined, fromOverrideEnabled: false, fromOverrideEmail: '', fromOverrideName: '', attachments: [], plainTextMode };
// The host closes the composer from onSend or onScheduledSendCreated;
// a send the plugin made itself reaches neither (#1207).
if (sendHandledByPlugin && !effectiveDelayedUntil) cleanClose();
// a send the plugin made itself reaches neither (#1207). A window of
// its own closes only now: closing it stops whatever is still running,
// such as removing the draft's last version above.
if (ownWindowRef.current || (sendHandledByPlugin && !effectiveDelayedUntil)) cleanClose();
} catch (err) {
// Not sent, so the composer stays open and is an unsent draft again.
explicitCloseRef.current = false;
@@ -4069,6 +4215,8 @@ export function EmailComposer({
} else if (err instanceof SubmissionQuotaError) {
// At a full submission quota only an administrator can help.
toast.error(sendFailureMessage(err, t));
} else if (isServerOutage(err)) {
toast.error(t('send_failed'), { message: tOfflineNotes('server_not_answering') });
} else if (err instanceof Error && OFFLINE_SEND_ERRORS[err.name]) {
// Offline mode (#523) refused to keep it: says why, in the user's language.
toast.error(t('send_failed'), { message: tOffline(OFFLINE_SEND_ERRORS[err.name]) });
@@ -4093,6 +4241,7 @@ export function EmailComposer({
const afterCloseRef = useRef<(() => void) | null>(null);
const emitClose = () => {
closedRef.current = true;
onClose?.();
const afterClose = afterCloseRef.current;
afterCloseRef.current = null;
@@ -4181,6 +4330,71 @@ export function EmailComposer({
}
};
// Moves the draft to its own window. The window opens first, inside the
// click, and waits; this window saves what the server doesn't have yet,
// gives it the draft under the same id, and closes the composer here.
const [isPoppingOut, setIsPoppingOut] = useState(false);
const poppingOutRef = useRef(false);
const handlePopOut = async () => {
if (!popOut || poppingOutRef.current || isSendingRef.current || saveCloseAttemptRef.current) return;
const target = popOut();
if (!target) {
toast.error(tWindows('popup_blocked'));
return;
}
poppingOutRef.current = true;
setIsPoppingOut(true);
if (saveTimeoutRef.current) {
clearTimeout(saveTimeoutRef.current);
saveTimeoutRef.current = null;
}
try {
const uploads = await waitForPendingUploads(() => attachmentsRef.current, () => false);
if (uploads === 'failed') {
target.cancel();
toast.error(t('save_failed'));
return;
}
if (isDirtyRef.current && (changeVersionRef.current !== savedVersionRef.current || saveFailedRef.current)) {
// A failed save doesn't stop the move: the text goes along, marked
// unsaved, and this composer lets go only once it is on screen there.
await saveDraftRef.current().catch(() => null);
}
const data = snapshotStateRef.current();
const shown = await target.handOver({
...data,
draftId: draftIdRef.current ?? lastDraftIdRef.current,
draftLocalAccountId: draftLocalAccountIdRef.current,
});
// Not on screen there, so this is still the only copy of the text.
if (!shown) {
target.cancel();
toast.error(tWindows('window_not_ready'));
return;
}
explicitCloseRef.current = true;
sendCancelledRef.current = true;
emitClose();
} finally {
poppingOutRef.current = false;
setIsPoppingOut(false);
}
};
const popOutButton = (className: string, iconClassName: string) => popOut && (
<button
type="button"
onClick={(event) => { event.stopPropagation(); void handlePopOut(); }}
disabled={isPoppingOut || isSending}
className={className}
aria-label={tWindows('open_in_window')}
title={tWindows('open_in_window')}
data-testid="composer-open-in-window"
>
<ExternalLink className={iconClassName} />
</button>
);
const handleDiscardAndClose = () => {
cancelSaveAndClose();
sendCancelledRef.current = true;
@@ -4322,6 +4536,8 @@ export function EmailComposer({
<div
ref={setComposerRootEl}
data-testid="email-composer"
// Edits made while the draft moves wouldn't move with it.
inert={isPoppingOut || undefined}
className={cn("flex h-full bg-background relative", className)}
onKeyDownCapture={handleComposerKeyDown}
// Bubble phase, in the same batch as the field's own onChange. A state
@@ -4380,6 +4596,7 @@ export function EmailComposer({
<ExternalLink className="h-4 w-4" />
</button>
)}
{popOutButton("grid h-8 w-8 place-items-center rounded-full text-muted-foreground hover:bg-muted hover:text-foreground", "h-4 w-4")}
<button
type="button"
onClick={() => handleClose()}
@@ -4407,6 +4624,7 @@ export function EmailComposer({
{saveStatus === 'saving' && <Save className="w-3.5 h-3.5 animate-pulse text-muted-foreground flex-shrink-0" aria-label={t('saving')} />}
{mvWindow.state !== "minimized" && leftPanelToggle}
{mvWindow.state !== "minimized" && rightPanelToggle}
{mvWindow.state !== "minimized" && popOutButton("grid h-7 w-7 place-items-center rounded-full text-muted-foreground hover:bg-foreground/10 hover:text-foreground", "h-4 w-4")}
<button
type="button"
onClick={(e) => { e.stopPropagation(); mvWindow.setState(mvWindow.state === "minimized" ? "normal" : "minimized"); }}
@@ -4507,6 +4725,7 @@ export function EmailComposer({
</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")}
{/* 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
+4
View File
@@ -123,6 +123,8 @@ interface EmailContextMenuProps {
copyTargets?: CopyTargetAccount[];
onCopyToAccount?: (accountId: string, mailboxId: string) => void;
onBatchForwardAsAttachment?: () => void;
/** Opens the message in its own window (single message). */
onOpenInWindow?: () => void;
/** Save the message as .eml, print it, show its source (single message). */
onExport?: () => void;
onPrint?: () => void;
@@ -183,6 +185,7 @@ export function EmailContextMenu({
onRescheduleScheduled,
copyTargets,
onCopyToAccount,
onOpenInWindow,
onExport,
onPrint,
onViewSource,
@@ -308,6 +311,7 @@ export function EmailContextMenu({
onRescheduleScheduled,
onCancelScheduledForEdit,
onCancelScheduledSend,
onOpenInWindow,
onExport,
onPrint,
onViewSource,
+3
View File
@@ -27,6 +27,7 @@ import { useEmailStore, resolveEmailBlobContext, ArchiveMailboxNotFoundError, re
import { useRemoveFromFolder } from "@/hooks/use-remove-from-folder";
import { useShallow } from "zustand/react/shallow";
import { useAuthStore } from "@/stores/auth-store";
import { useOpenEmailInWindow } from "@/hooks/use-popouts-available";
import { useSettingsStore } from "@/stores/settings-store";
import { useListRowShape } from "@/hooks/use-list-row-shape";
import { MailListRowsSkeleton, type MailRowShape } from "@/components/boot-skeleton/mail-skeleton";
@@ -177,6 +178,7 @@ export function EmailList({
}: EmailListProps) {
const t = useTranslations('email_list');
const tContextMenu = useTranslations('context_menu');
const openInWindow = useOpenEmailInWindow();
const tSpam = useTranslations('email_viewer.spam');
const tNotifications = useTranslations('notifications');
const tViewer = useTranslations('email_viewer');
@@ -1360,6 +1362,7 @@ export function EmailList({
: [contextMenuEmail!];
await copyToAccount(emails, accountId, mailboxId);
}}
onOpenInWindow={openInWindow && contextMenuEmail ? () => openInWindow(contextMenuEmail) : undefined}
// Export, print and View source follow the device policy of the row's own account.
onExport={contextMenuEmail && !canExport(contextMenuEmail) ? undefined : () => {
const target = contextMenuEmail!;
+93 -32
View File
@@ -82,6 +82,7 @@ import {
MailOpen,
Loader2,
Printer,
ExternalLink,
FileText,
File,
Shield,
@@ -158,6 +159,7 @@ import { requestInternalMailto } from "@/lib/protocol-handlers/mailto";
import { imageBlobUrl, inertBlobType, isFilePreviewable, isMimeTypeSafeForInlinePreview, toInertBlob } from "@/lib/file-preview";
import { openPreviewInNewWindow } from "@/lib/standalone-display";
import { downloadAllowed, saveBlobAs } from "@/lib/download-guard";
import { canPickFolder, createUniqueNamer, isPickerCancelled, pickFolder, saveFilesToFolder, type FolderHandle } from "@/lib/attachments/save-to-folder";
import { useDevicePolicy } from "@/hooks/use-device-policy";
import { Watermark, useWatermarkText } from "@/components/device/watermark";
import { watermarkForPrint } from "@/lib/watermark";
@@ -285,6 +287,8 @@ interface EmailViewerProps {
* minimize button; `isFullscreen` reflects the host's current state.
*/
onToggleFullscreen?: () => void;
/** Opens this message in its own window; left out where that isn't on offer. */
onOpenInWindow?: () => void;
isFullscreen?: boolean;
currentUserEmail?: string;
currentUserName?: string;
@@ -1318,6 +1322,7 @@ export function EmailViewer({
onRescheduleScheduled,
onCompose,
onToggleFullscreen,
onOpenInWindow,
isFullscreen = false,
currentUserEmail,
currentUserName,
@@ -1329,6 +1334,7 @@ export function EmailViewer({
}: EmailViewerProps) {
const t = useTranslations('email_viewer');
const archiveActionEnabled = useArchiveActionEnabled();
const tWindows = useTranslations('pwaWindows');
const tComposer = useTranslations('email_composer');
const tNotifications = useTranslations('notifications');
const tImport = useTranslations('mail_import');
@@ -3005,10 +3011,24 @@ export function EmailViewer({
saveBlobAs(blob, downloadName, { kind: 'attachment', subject: email });
}, [onDownloadAttachment, email, resolveAttachmentName]);
// An attachment's content for "download all" and "save all": fetched
// through the JMAP client when it is blob-backed, the already decoded bytes
// for S/MIME-decrypted and TNEF-extracted ones. Null when it has none.
const readAttachmentContent = useCallback(async (attachment: EffectiveAttachment, name: string): Promise<Blob | Uint8Array<ArrayBuffer> | null> => {
if (attachment.blobId && blobClient) {
return blobClient.fetchBlob(attachment.blobId, attachment.name || name, attachment.type, blobAccountId);
}
if (attachment.tnefData) return attachment.tnefData as Uint8Array<ArrayBuffer>;
if (attachment.decryptedAttachment) {
const bytes = getAttachmentContentBytes(attachment.decryptedAttachment);
if (bytes && bytes.byteLength > 0) return bytes as Uint8Array<ArrayBuffer>;
}
return null;
}, [blobClient, blobAccountId]);
// Bundle every attachment of this email into a single .zip and download it.
// Fetches blob-backed attachments through the JMAP client and reuses already
// decoded bytes for S/MIME-decrypted and TNEF-extracted ones. Individual
// failures are skipped so a single bad blob doesn't sink the whole archive.
// Individual failures are skipped so a single bad blob doesn't sink the
// whole archive.
const handleDownloadAllAttachments = useCallback(async () => {
if (isDownloadingAll || effectiveAttachments.length === 0) return;
if (!downloadAllowed('attachment', email)) return;
@@ -3016,39 +3036,17 @@ export function EmailViewer({
try {
const { default: JSZip } = await import('jszip');
const zip = new JSZip();
const used = new Set<string>();
// Zip entries must be unique; suffix collisions with " (n)" before the
// extension so duplicates stay recognisable.
const uniqueName = (raw: string): string => {
const base = raw || 'attachment';
if (!used.has(base)) { used.add(base); return base; }
const dot = base.lastIndexOf('.');
const stem = dot > 0 ? base.slice(0, dot) : base;
const ext = dot > 0 ? base.slice(dot) : '';
let i = 1;
let candidate = `${stem} (${i})${ext}`;
while (used.has(candidate)) { i++; candidate = `${stem} (${i})${ext}`; }
used.add(candidate);
return candidate;
};
// Zip entries must be unique.
const uniqueName = createUniqueNamer();
let added = 0;
for (const attachment of effectiveAttachments) {
const entryName = uniqueName(getAttachmentDisplayName(attachment.name, attachment.type));
try {
if (attachment.blobId && blobClient) {
const blob = await blobClient.fetchBlob(attachment.blobId, attachment.name || entryName, attachment.type, blobAccountId);
zip.file(entryName, blob);
const content = await readAttachmentContent(attachment, entryName);
if (content) {
zip.file(entryName, content);
added++;
} else if (attachment.tnefData) {
zip.file(entryName, attachment.tnefData);
added++;
} else if (attachment.decryptedAttachment) {
const bytes = getAttachmentContentBytes(attachment.decryptedAttachment);
if (bytes && bytes.byteLength > 0) {
zip.file(entryName, bytes);
added++;
}
}
} catch {
// Skip individual failures; remaining attachments still bundle.
@@ -3071,7 +3069,43 @@ export function EmailViewer({
} finally {
setIsDownloadingAll(false);
}
}, [isDownloadingAll, effectiveAttachments, blobClient, blobAccountId, email, t, tFiles]);
}, [isDownloadingAll, effectiveAttachments, readAttachmentContent, email, t, tFiles]);
// Save every attachment into a folder the user picks. These writes don't
// pass saveBlobAs, so the device policy is asked here: before the picker,
// and before each file. A browser that refuses the picker gets the zip.
const handleSaveAllToFolder = useCallback(async () => {
if (isDownloadingAll || effectiveAttachments.length === 0) return;
if (!downloadAllowed('attachment', email)) return;
let folder: FolderHandle;
try {
folder = await pickFolder();
} catch (error) {
if (!isPickerCancelled(error)) void handleDownloadAllAttachments();
return;
}
setIsDownloadingAll(true);
try {
const result = await saveFilesToFolder(
folder,
effectiveAttachments.map((attachment) => {
const name = getAttachmentDisplayName(attachment.name, attachment.type);
return { name, read: () => readAttachmentContent(attachment, name) };
}),
() => downloadAllowed('attachment', email),
);
if (result.saved === result.total) {
toast.success(tWindows('saved_all', { count: result.saved, folder: result.folder }));
} else if (result.saved > 0) {
toast.warning(tWindows('saved_partial', { saved: result.saved, total: result.total, folder: result.folder }));
} else if (result.stopped !== 'policy') {
// The policy said why itself.
toast.error(tWindows('save_failed', { folder: result.folder }));
}
} finally {
setIsDownloadingAll(false);
}
}, [isDownloadingAll, effectiveAttachments, readAttachmentContent, handleDownloadAllAttachments, email, tWindows]);
// What the attachment bar and the attachment cards share.
const attachmentCardsRef = useRef<HTMLDivElement>(null);
@@ -3082,6 +3116,7 @@ export function EmailViewer({
onOpen: handleEffectiveAttachmentOpen,
onDownload: handleEffectiveAttachmentDownload,
onDownloadAll: handleDownloadAllAttachments,
onSaveAllToFolder: canPickFolder() ? () => void handleSaveAllToFolder() : undefined,
downloadingAll: isDownloadingAll,
downloadsOff,
// Save to Files would get around the policy: Files downloads are off too, but the copy would stay.
@@ -4479,6 +4514,20 @@ ${printWatermark ? printWatermark.html : ''}
{isDark ? <Sun className="w-4 h-4" /> : <Moon className="w-4 h-4" />}
</Button>
{onOpenInWindow && !mvViewer && (
<Button
variant="ghost"
size="sm"
onClick={onOpenInWindow}
className="hidden sm:inline-flex h-8 gap-1.5"
title={tWindows('open_in_window')}
aria-label={tWindows('open_in_window')}
data-testid="viewer-open-in-window"
>
<ExternalLink className="w-4 h-4" />
</Button>
)}
{/* Fullscreen toggle - hidden on mobile (already fullscreen there).
Never overflows into the More menu: in fullscreen this button is
the way back out, so it must stay visible. */}
@@ -4630,7 +4679,7 @@ ${printWatermark ? printWatermark.html : ''}
inset (same treatment as the preview modals). (#936) */}
<div className={cn(
"flex items-center justify-between px-4 border-b border-border",
isPaneScoped ? "py-3" : "pb-3 pt-[calc(0.75rem+env(safe-area-inset-top))]"
isPaneScoped ? "py-3" : "pb-3 pt-[calc(0.75rem+var(--app-top-inset))]"
)}>
{moreMenuSub ? (
<button
@@ -4781,6 +4830,18 @@ ${printWatermark ? printWatermark.html : ''}
<Printer className="w-5 h-5" />
</button>
)}
{onOpenInWindow && (
<button
type="button"
onClick={onOpenInWindow}
className="grid place-items-center w-10 h-10 rounded-full text-muted-foreground hover:bg-muted hover:text-foreground transition-colors"
title={tWindows('open_in_window')}
aria-label={tWindows('open_in_window')}
data-testid="viewer-open-in-window"
>
<ExternalLink className="w-5 h-5" />
</button>
)}
{onToggleFullscreen && (
<button
type="button"
+6
View File
@@ -25,6 +25,7 @@ import {
Tag,
ShieldAlert,
ShieldCheck,
ExternalLink,
CalendarClock,
CalendarX,
Paperclip,
@@ -65,6 +66,7 @@ export type MessageActionKey =
| "spam"
| "report_phishing"
| "find_from_sender"
| "open_window"
| "export"
| "print"
| "view_source"
@@ -115,6 +117,8 @@ export interface MessageActionOptions {
onRescheduleScheduled?: () => void;
onCancelScheduledForEdit?: () => void;
onCancelScheduledSend?: () => void;
/** Opens the message in its own window (installed app, desktop app). */
onOpenInWindow?: () => void;
/** Save the message as .eml. */
onExport?: () => void;
onPrint?: () => void;
@@ -149,6 +153,7 @@ export function useMessageActionList(o: MessageActionOptions): MessageActionEntr
const tViewer = useTranslations("email_viewer");
const tDeepLink = useTranslations("deep_link");
const tPhishing = useTranslations("phishing_report");
const tWindows = useTranslations("pwaWindows");
const copyLink = useCopyLink();
const archiveEnabled = useArchiveActionEnabled();
const mountainView = useSettingsStore((state) => state.interfaceLayout === "mountain-view");
@@ -264,6 +269,7 @@ export function useMessageActionList(o: MessageActionOptions): MessageActionEntr
: [];
// Download/Export, Print, View source (R6: after Copy, before the end).
const file = [
...(o.onOpenInWindow ? [item("open_window", ExternalLink, tWindows("open_in_window"), o.onOpenInWindow, { testId: "ctx-open-window" })] : []),
...(o.onExport ? [item("export", Download, tViewer("export_email"), o.onExport, { disabled: !email.blobId, testId: "ctx-export" })] : []),
...(o.onPrint ? [item("print", Printer, tViewer("print"), o.onPrint, { testId: "ctx-print" })] : []),
...(o.onViewSource ? [item("view_source", Code, tViewer("view_source"), o.onViewSource, { disabled: !email.blobId, testId: "ctx-view-source" })] : []),
+24 -3
View File
@@ -52,6 +52,8 @@ interface ReaderAttachmentsProps<T extends ReaderAttachmentItem> {
onOpen: (attachment: T) => void;
onDownload: (attachment: T) => void;
onDownloadAll: () => void;
/** "Save all to a folder": left out where the browser can't ask for one. */
onSaveAllToFolder?: () => void;
downloadingAll: boolean;
/**
* The account's device policy turned downloads off (Organisation >
@@ -91,6 +93,7 @@ export function ReaderAttachments<T extends ReaderAttachmentItem>({
onOpen,
onDownload,
onDownloadAll,
onSaveAllToFolder,
downloadingAll,
downloadsOff = false,
onSaveToFiles,
@@ -101,6 +104,7 @@ export function ReaderAttachments<T extends ReaderAttachmentItem>({
const t = useTranslations("email_viewer");
const tFiles = useTranslations("files");
const tDevice = useTranslations("device_policy");
const tWindows = useTranslations("pwaWindows");
// Opens nothing: no preview, and downloads are off.
const locked = (attachment: T) => downloadsOff && !opensPreview(attachment);
const openLabel = (attachment: T, name: string) =>
@@ -238,7 +242,7 @@ export function ReaderAttachments<T extends ReaderAttachmentItem>({
const draw = layout === "cards" ? card : tile;
return (
<section aria-label={t("attachments")} className={cn("flex flex-col gap-3", className)} data-testid="reader-attachments" data-layout={layout} {...noMediaSavingProps(downloadsOff)}>
<section aria-label={t("attachments")} className={cn("@container flex flex-col gap-3", className)} data-testid="reader-attachments" data-layout={layout} {...noMediaSavingProps(downloadsOff)}>
<div className="flex items-center justify-between gap-3">
<div className="flex min-w-0 items-center gap-2 text-sm text-muted-foreground">
<Paperclip className="h-4 w-4 shrink-0" aria-hidden="true" />
@@ -258,10 +262,27 @@ export function ReaderAttachments<T extends ReaderAttachmentItem>({
onClick={onDownloadAll}
disabled={downloadingAll}
title={t("download_all")}
className="shrink-0 gap-1.5 disabled:cursor-wait"
aria-label={t("download_all")}
className="shrink-0 gap-1.5 whitespace-nowrap disabled:cursor-wait"
>
{downloadingAll ? <Loader2 className="h-4 w-4 animate-spin" /> : <Download className="h-4 w-4" />}
{t("download_all")}
{/* Just the icon in a narrow pane, so the row stays one row. */}
<span className={onSaveAllToFolder ? "hidden @xl:inline" : undefined}>{t("download_all")}</span>
</Button>
)}
{attachments.length > 1 && !downloadsOff && onSaveAllToFolder && (
<Button
variant="ghost"
size="sm"
onClick={onSaveAllToFolder}
disabled={downloadingAll}
title={tWindows("save_all_to_folder")}
aria-label={tWindows("save_all_to_folder")}
className="shrink-0 gap-1.5 whitespace-nowrap disabled:cursor-wait"
data-testid="attachments-save-to-folder"
>
<FolderInput className="h-4 w-4" />
<span className="hidden @xl:inline">{tWindows("save_all_to_folder")}</span>
</Button>
)}
</div>
+1 -1
View File
@@ -11,7 +11,7 @@ function AppErrorLayout({ kind, ...props }: FallbackProps & { kind: "page" | "se
const Fallback = kind === "settings" ? SettingsErrorFallback : PageErrorFallback;
// The navigation stays, so one app crashing doesn't strand the user in it.
return (
<div className="flex h-dvh bg-background pt-[env(safe-area-inset-top)]">
<div className="flex h-dvh bg-background pt-[var(--app-top-inset)]">
{!isMobile && (
<div className="w-14 bg-secondary flex flex-col flex-shrink-0 border-e border-border">
<NavigationRail collapsed />
+1 -1
View File
@@ -813,7 +813,7 @@ export function FilesApp({ linkSegments: routeSegments }: FilesAppProps = {}) {
}
return (
<div className={cn("flex flex-col overflow-hidden pt-[env(safe-area-inset-top)]", mvShell ? "bg-[var(--mv-canvas)]" : "bg-background", isEmbedded ? "h-full" : "h-dvh")}>
<div className={cn("flex flex-col overflow-hidden pt-[var(--app-top-inset)]", mvShell ? "bg-[var(--mv-canvas)]" : "bg-background", isEmbedded ? "h-full" : "h-dvh")}>
{!isEmbedded && <SkipLink>{tShell("skip_to_content")}</SkipLink>}
<AppTopBannerSlot />
{refreshIndicator}
+1 -1
View File
@@ -82,7 +82,7 @@ export function PreviewShell({ name, onClose, onDownload, actions, neighbours, c
{/* Full-screen under `viewport-fit=cover`: the bar pads itself out of
the iOS status bar (#936). The insets are physical, so pl/pr. */}
<div
className="flex items-center justify-between gap-2 pl-[calc(1rem+env(safe-area-inset-left))] pr-[calc(1rem+env(safe-area-inset-right))] pt-[calc(0.75rem+env(safe-area-inset-top))] pb-3 bg-background/90 backdrop-blur border-b border-border"
className="flex items-center justify-between gap-2 pl-[calc(1rem+env(safe-area-inset-left))] pr-[calc(1rem+env(safe-area-inset-right))] pt-[calc(0.75rem+var(--app-top-inset))] pb-3 bg-background/90 backdrop-blur border-b border-border"
onClick={(e) => e.stopPropagation()}
>
<h3 className="text-sm font-medium truncate" title={name}>{name}</h3>
+1 -1
View File
@@ -124,7 +124,7 @@ export function WopiEditor({ target, accountId, slot, onClose, closeOnBack = fal
role="dialog"
aria-modal="true"
aria-labelledby={titleId}
className="fixed inset-0 z-[100] bg-background flex flex-col"
className="fixed inset-0 z-[100] bg-background flex flex-col pt-[var(--titlebar-inset)]"
>
<div className="flex items-center justify-between gap-3 px-4 h-12 border-b border-border shrink-0">
<h2 id={titleId} className="text-sm font-medium text-foreground truncate">{target.name}</h2>
+48
View File
@@ -0,0 +1,48 @@
"use client";
import { useEffect, useState } from "react";
import { applyTitlebarInset, watchTitlebarArea, type TitlebarArea } from "@/lib/window-controls-overlay";
/**
* The strip above the app in a window without a native title bar: the part
* the user drags the window by, with the window's title in small text. The
* native window controls sit next to it, outside the area it is given. The
* page roots leave this row empty through --titlebar-inset.
*
* Renders nothing, and changes nothing on the page, without an overlay. It
* repeats the title for sighted users only, so it stays out of the
* accessibility tree and out of the tab order.
*/
export function WindowTitleBar() {
const [area, setArea] = useState<TitlebarArea | null>(null);
const [title, setTitle] = useState("");
useEffect(() => watchTitlebarArea((next) => {
applyTitlebarInset(next);
setArea(next);
}), []);
const visible = area !== null;
useEffect(() => {
if (!visible) return;
const read = () => setTitle(document.title);
read();
// Each surface sets its own title, and Next puts <title> back on navigation.
const observer = new MutationObserver(read);
observer.observe(document.head, { childList: true, subtree: true, characterData: true });
return () => observer.disconnect();
}, [visible]);
if (!area) return null;
return (
<div
aria-hidden="true"
data-window-title-bar=""
className="window-title-bar fixed z-[100002] flex items-center bg-background ps-3 pe-3 text-xs text-muted-foreground select-none"
style={{ top: area.y, left: area.x, width: area.width, height: area.height }}
>
<span className="truncate">{title}</span>
</div>
);
}
+43 -5
View File
@@ -150,6 +150,9 @@ import { INTERNAL_MAILTO_EVENT, type ParsedMailto } from "@/lib/protocol-handler
import { PLUGIN_REPLY_EVENT, type PluginReplyRequest } from "@/lib/plugin-sandbox/host-api-compose";
import { onOpenEmail, type OpenEmailHandler, type OpenEmailOutcome } from "@/lib/plugin-sandbox/open-email";
import { mailtoComposerDraft } from "./mailto-draft";
import { useOpenEmailInWindow, usePopoutsAvailable } from "@/hooks/use-popouts-available";
import { openComposerWindow } from "@/lib/popout/open";
import { onRescuedDraft, takeRescuedDraft } from "@/lib/popout/rescued-drafts";
import { getQuoteBodies } from "@/lib/email-composer-utils";
import { emailHooks } from "@/lib/plugin-hooks";
import { afterRequestDispatch } from "@/lib/after-request-dispatch";
@@ -2261,6 +2264,39 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) {
// another account's message under the same id.
const composerSource = usePinnedPerSession(composerSessionId, selectedEmail ? emailWriteSource(selectedEmail, client) : undefined);
const popoutsOn = usePopoutsAvailable();
const openEmailInWindow = useOpenEmailInWindow();
// Text from a closing pop-out that couldn't be saved: the "Continue draft"
// slot, once it is free.
useEffect(() => {
const adopt = () => {
if (pendingDraft || showComposer) return;
const draft = takeRescuedDraft();
if (draft) setPendingDraft(draft);
};
adopt();
return onRescuedDraft(adopt);
}, [pendingDraft, showComposer]);
const composerPopOut = () => {
const target = openComposerWindow(activeAccountId);
if (!target) return null;
return {
cancel: target.cancel,
handOver: (state: ComposerDraftData) => target.handOver({
mode: state.mode,
replyTo: state.replyTo,
initialData: state,
sourceEmailId: composerSourceEmail?.id,
sourceEmailSource: composerSource,
composeFromAccountEmail: resolveComposeAccountEmail(
mailboxes,
selectedMailbox,
useAccountStore.getState().getAccountById(viewingAccountId ?? activeAccountId ?? '')?.email,
),
}),
};
};
const handleEmailSend = async (data: {
to: string[];
cc: string[];
@@ -5012,6 +5048,7 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) {
handleDiscardDraft(draftId, draft);
setPendingDraft(null);
}}
popOut={popoutsOn && !isEmbedded ? composerPopOut : undefined}
/>
</ErrorBoundary>
);
@@ -5022,7 +5059,7 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) {
return (
<DragDropProvider>
<div ref={appRootRef} className={cn("flex flex-col overflow-hidden pt-[env(safe-area-inset-top)]", mvShell ? "bg-[var(--mv-canvas)]" : "bg-background", isEmbedded ? "h-full" : "h-dvh")}>
<div ref={appRootRef} className={cn("flex flex-col overflow-hidden pt-[var(--app-top-inset)]", mvShell ? "bg-[var(--mv-canvas)]" : "bg-background", isEmbedded ? "h-full" : "h-dvh")}>
{/* Rail and folders are many Tab stops: jump past them (WCAG 2.4.1). */}
<a
href="#message-list"
@@ -5135,7 +5172,7 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) {
isEmbedded
? (isMobile || isTablet
? cn(
"absolute inset-y-0 start-0 w-72 pt-[env(safe-area-inset-top)]",
"absolute inset-y-0 start-0 w-72 pt-[var(--app-top-inset)]",
"transform transition-transform duration-300 ease-in-out",
// translate-x is physical, so RTL needs the opposite
// sign or the drawer slides off the wrong edge.
@@ -5146,7 +5183,7 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) {
// Mobile/Tablet: fixed overlay
// start-0 rather than left-0: in RTL the drawer belongs on
// the right, matching the hamburger that opens it.
"max-lg:fixed max-lg:inset-y-0 max-lg:start-0 max-lg:w-72 max-lg:pt-[env(safe-area-inset-top)]",
"max-lg:fixed max-lg:inset-y-0 max-lg:start-0 max-lg:w-72 max-lg:pt-[var(--app-top-inset)]",
"max-lg:transform max-lg:transition-transform max-lg:duration-300 max-lg:ease-in-out",
!sidebarOpen && "max-lg:-translate-x-full max-lg:rtl:translate-x-full",
// Desktop: normal flow
@@ -5288,7 +5325,7 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) {
{(!isMobile || mobileSearchOpen) && (
<div className={cn(
"border-b border-border bg-background",
isMobile && mobileSearchOpen && "fixed inset-0 z-50 overflow-y-auto"
isMobile && mobileSearchOpen && "fixed inset-0 z-50 overflow-y-auto pt-[var(--titlebar-inset)]"
)}>
{isMobile && mobileSearchOpen && (
<div className="h-14 px-2 flex items-center border-b border-border">
@@ -5650,7 +5687,7 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) {
isHorizontalMailLayout ? "min-h-0" : "h-full",
// Mobile: full screen overlay when active
"max-md:fixed max-md:inset-0 max-md:z-30",
"max-md:h-full max-md:pt-[env(safe-area-inset-top)]",
"max-md:h-full max-md:pt-[var(--app-top-inset)]",
isMobile && mobileView !== "viewer" && "max-md:hidden",
// Tablet/Desktop: relative. Pane-mobile instead overlays the
// pane (absolute within the relative content row above) - the
@@ -5835,6 +5872,7 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) {
} : undefined}
mvInlineComposer={mvInlineReply ? <MvComposeInline onPopOut={handleMvPopOut}>{composerNode}</MvComposeInline> : undefined}
onToggleFullscreen={!isEmbedded && !isMobile ? () => setFullscreenReading((v) => !v) : undefined}
onOpenInWindow={!isEmbedded && !isMobile && openEmailInWindow && selectedEmail ? () => openEmailInWindow(selectedEmail) : undefined}
isFullscreen={fullscreenReading}
onShowShortcuts={() => setShowShortcutsModal(true)}
onEditDraft={handleEditDraft}
@@ -158,7 +158,7 @@ export function NotificationSheet({ onClose }: { onClose: () => void }) {
role="dialog"
aria-modal="true"
aria-label={t("title")}
className="fixed inset-0 z-50 flex flex-col bg-background pt-[env(safe-area-inset-top)]"
className="fixed inset-0 z-50 flex flex-col bg-background pt-[var(--app-top-inset)]"
>
<NotificationPanel onClose={onClose} sheet className="flex-1 min-h-0" />
</div>,
@@ -101,7 +101,7 @@ describe('what an account keeps', () => {
const select = screen.getByText('attachment_cap_label').closest('[data-search-label]')!.querySelector('select') as HTMLSelectElement;
expect([...select.options].map((o) => o.value)).toEqual(['5', '10']);
fireEvent.change(select, { target: { value: '5' } });
expect(offline.chooseScope).toHaveBeenCalledWith('acc', { maxAttachmentMb: 5 });
expect(offline.chooseScope).toHaveBeenCalledWith('acc', { maxAttachmentBytes: 5 * 1024 * 1024 });
});
it('says when the total is set by the organisation', () => {
@@ -110,6 +110,13 @@ describe('what an account keeps', () => {
expect(screen.getByTestId('offline-total-locked').textContent).toContain('total_locked');
});
it('locks the switch when the desktop policy forces it', () => {
(window as { bulwarkDesktop?: unknown }).bulwarkDesktop = { version: 1, policy: { get: () => ({ OfflineEnabled: { value: true, locked: true, source: 'machine' } }) } };
render(<OfflineSettings />);
expect(screen.getByTestId('offline-switch').closest('[inert]')).not.toBeNull();
delete (window as { bulwarkDesktop?: unknown }).bulwarkDesktop;
});
it('shows nothing of this with offline off', () => {
useOfflineStore.setState({ enabled: [] });
render(<OfflineSettings />);
@@ -128,7 +135,7 @@ describe('what it takes', () => {
});
it('shows the time of the last sync from before a reload', () => {
useOfflineStore.setState({ health: { acc: { opened: true, lastSync: Date.now() - 60_000 } } });
useOfflineStore.setState({ health: { acc: { lastSync: Date.now() - 60_000 } } });
render(<OfflineSettings />);
expect(screen.getByTestId('offline-status').textContent).toContain('usage_updated');
});
@@ -182,11 +189,11 @@ describe('what the browser may do', () => {
});
it('warns about a store it deleted, with the count, until read', () => {
useOfflineStore.setState({ health: { acc: { opened: true, evicted: { at: 1, lost: 2 } } } });
useOfflineStore.setState({ health: { acc: { reset: { at: 1, lost: 2 } } } });
render(<OfflineSettings />);
expect(screen.getByTestId('offline-evicted').textContent).toContain('evicted_lost');
fireEvent.click(within(screen.getByTestId('offline-evicted')).getByRole('button', { name: 'evicted_dismiss' }));
expect(useOfflineStore.getState().health.acc.evicted).toBeUndefined();
expect(useOfflineStore.getState().health.acc.reset).toBeUndefined();
});
it('says the device is full, with what to do', () => {
@@ -0,0 +1,55 @@
import 'fake-indexeddb/auto';
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { OfflineHost } from '../offline-host';
import { queueSend } from '@/lib/offline/queue';
import { useOfflineStore, writeEnabled } from '@/lib/offline/state';
import { passSignOutGates } from '@/lib/sign-out-cleanup';
import { setStoreBackend } from '@/lib/store/client/api';
import { InProcessStore } from '@/lib/store/__tests__/helpers/in-process-store';
import { wipeEverything } from '@/lib/offline/offline-mode';
import { useAccountStore } from '@/stores/account-store';
let store: InProcessStore;
beforeEach(() => {
store = new InProcessStore();
setStoreBackend(store);
localStorage.clear();
useOfflineStore.setState({ outbox: [], pendingChanges: 0, conflicts: [] });
useAccountStore.setState({ accounts: [{ id: 'acc' }] as never });
writeEnabled(['acc']);
});
afterEach(async () => {
cleanup();
await wipeEverything();
setStoreBackend(null);
});
describe('the question before a sign-out', () => {
it('counts what the queue holds, though the screen has seen none of it', async () => {
await queueSend('acc', { subject: 'Hello', to: [] }, { kind: 'email', args: [] });
useOfflineStore.setState({ outbox: [] });
render(<OfflineHost />);
const answer = passSignOutGates('acc');
fireEvent.click(await screen.findByRole('button', { name: /signout\.confirm/ }));
expect(await answer).toBe(true);
});
it('asks about a change that hasn\'t reached the server, on its own', async () => {
await store.ensureOpen('acc');
store.dbs.get('acc')!.run("INSERT INTO calendar_pending (jmap, record_id, kind, patch, queued_at) VALUES ('j1', 'ev', 'update', '{}', 1)");
render(<OfflineHost />);
const answer = passSignOutGates('acc');
expect(await screen.findByText(/signout_changes_title/)).toBeTruthy();
fireEvent.click(await screen.findByRole('button', { name: /signout\.confirm/ }));
expect(await answer).toBe(true);
});
it('asks nothing with nothing waiting', async () => {
render(<OfflineHost />);
expect(await passSignOutGates('acc')).toBe(true);
expect(screen.queryByRole('button', { name: /signout\.confirm/ })).toBeNull();
});
});
@@ -35,6 +35,17 @@ beforeEach(() => {
});
describe('Settings > Offline', () => {
it('says so in a private window, with no switch to turn on', () => {
useOfflineStore.setState({ storageBlocked: true });
try {
render(<OfflineSettings />);
expect(screen.getByTestId('offline-private')).toBeTruthy();
expect(screen.queryByTestId('offline-switch')).toBeNull();
} finally {
useOfflineStore.setState({ storageBlocked: false });
}
});
it('is off until the user turns it on in this browser', () => {
render(<OfflineSettings />);
const toggle = screen.getByTestId('offline-switch');
+7 -7
View File
@@ -8,7 +8,7 @@ import { OrgLockedNote } from '@/components/settings/org-locked-note';
import { Button } from '@/components/ui/button';
import { ConfirmDialog } from '@/components/ui/confirm-dialog';
import { formatFileSize } from '@/lib/utils';
import { chooseScope, clearAccount, disableOffline, dismissEvicted, enableOffline, scopeForAccount } from '@/lib/offline/offline-mode';
import { chooseScope, clearAccount, disableOffline, dismissStoreReset, enableOffline, scopeForAccount } from '@/lib/offline/offline-mode';
import { attachmentCapOptions, maxAttachmentMb, windowOptions } from '@/lib/offline/scope';
import { useOfflineStore } from '@/lib/offline/state';
import { minutesLeft, progressWorthShowing, type SyncProgress } from '@/lib/offline/sync-progress';
@@ -51,7 +51,7 @@ export function AccountStorage({ account, primary, heading }: { account: string;
const usage = useOfflineStore((s) => s.usage[account]);
const syncing = useOfflineStore((s) => s.syncing.includes(account));
const lastSynced = useOfflineStore((s) => s.lastSyncedAt[account] ?? s.health[account]?.lastSync);
const evicted = useOfflineStore((s) => s.health[account]?.evicted);
const storeReset = useOfflineStore((s) => s.health[account]?.reset);
const storageFull = useOfflineStore((s) => !!s.storageFull[account]);
const progress = useOfflineStore((s) => s.progress[account]);
const unsent = useOfflineStore((s) => s.outbox.filter((row) => row.account === account).length);
@@ -89,7 +89,7 @@ export function AccountStorage({ account, primary, heading }: { account: string;
return (
<div className={heading ? 'rounded-md border border-border px-3' : undefined} data-testid={testId('offline-account')}>
{heading && <p className="pt-3 text-sm font-semibold text-foreground [overflow-wrap:anywhere]">{heading}</p>}
<SettingItem label={t('keep_label')} description={tStorage('keep_description')}>
<SettingItem label={t('keep_label')} description={tStorage('keep_description')} locked={locked.forced}>
<ToggleSwitch
checked={enabled}
testId={testId('offline-switch')}
@@ -100,13 +100,13 @@ export function AccountStorage({ account, primary, heading }: { account: string;
}}
/>
</SettingItem>
{evicted && (
{storeReset && (
<div className="my-2 flex flex-col gap-2 rounded-md border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-xs text-amber-900 dark:text-amber-200 sm:flex-row sm:items-center sm:justify-between" role="alert" data-testid="offline-evicted">
<p className="min-w-0">
{tStorage('evicted')}
{evicted.lost > 0 && <> {tStorage('evicted_lost', { count: evicted.lost })}</>}
{storeReset.lost > 0 && <> {tStorage('evicted_lost', { count: storeReset.lost })}</>}
</p>
<Button variant="outline" size="sm" className="shrink-0" onClick={() => dismissEvicted(account)}>{tStorage('evicted_dismiss')}</Button>
<Button variant="outline" size="sm" className="shrink-0" onClick={() => dismissStoreReset(account)}>{tStorage('evicted_dismiss')}</Button>
</div>
)}
{enabled && (
@@ -169,7 +169,7 @@ export function AccountStorage({ account, primary, heading }: { account: string;
<div className="flex flex-col items-start gap-1 sm:items-end">
<Select
value={String(currentCap)}
onChange={(value) => chooseScope(account, { maxAttachmentMb: Number(value) })}
onChange={(value) => chooseScope(account, { maxAttachmentBytes: Number(value) * MB })}
options={(caps.includes(currentCap) ? caps : [...caps, currentCap].sort((a, b) => a - b)).map((mb) => ({ value: String(mb), label: formatFileSize(mb * MB) }))}
/>
{locked.maxAttachment && caps.length > 1 && <OrgLockedNote />}
+20 -11
View File
@@ -8,8 +8,7 @@ import { useConfirmDialog } from '@/hooks/use-confirm-dialog';
import { addSignOutGate } from '@/lib/sign-out-cleanup';
import { reloadToNewBuild } from '@/lib/app-update';
import { buildSettingsPath } from '@/lib/deep-links';
import { confirmLoss, setOfflineNotifier, startOfflineMode, type OfflineNotice } from '@/lib/offline/offline-mode';
import { useOfflineStore } from '@/lib/offline/state';
import { confirmLoss, setOfflineNotifier, startOfflineMode, unsentCount, type OfflineNotice } from '@/lib/offline/offline-mode';
import { toast } from '@/stores/toast-store';
/**
@@ -63,15 +62,21 @@ export function OfflineHost() {
case 'storage-failed':
toast.warning(tStorageRef.current('storage_full_title'), { message: tStorageRef.current('storage_full_text'), duration: 0, action: openStorage });
break;
case 'evicted':
toast.warning(tStorageRef.current('evicted'), {
case 'default-on':
toast.info(tStorageRef.current('default_on'), { duration: 0, action: openStorage });
break;
case 'legacy-stranded':
toast.warning(tConflictsRef.current('legacy_stranded'), { duration: 0 });
break;
case 'store-reset':
toast.warning(tConflictsRef.current('store_reset'), {
message: notice.lost > 0 ? tStorageRef.current('evicted_lost', { count: notice.lost }) : undefined,
duration: notice.lost > 0 ? 0 : undefined,
duration: 0,
action: openStorage,
});
break;
case 'default-on':
toast.info(tStorageRef.current('default_on'), { duration: 0, action: openStorage });
case 'store-unavailable':
toast.warning(tConflictsRef.current('store_unavailable'), { duration: 0 });
break;
case 'refused-delete':
toast.warning(tr('toast.refused_delete'));
@@ -94,12 +99,16 @@ export function OfflineHost() {
const stop = startOfflineMode();
// Messages that would be lost: ask before a sign-out the user started.
const removeGate = addSignOutGate(async (accountId) => {
const unsent = useOfflineStore.getState().outbox.filter((row) => accountId === 'all' || row.account === accountId).length;
if (unsent === 0) return true;
const { messages, changes } = await unsentCount(accountId);
if (messages === 0 && changes === 0) return true;
const tr = tRef.current;
const trConflicts = tConflictsRef.current;
const ok = await confirmRef.current({
title: tr('signout.title'),
message: tr('signout.message', { count: unsent }),
title: messages > 0 ? tr('signout.title') : trConflicts('signout_changes_title'),
message: [
...(messages > 0 ? [tr('signout.message', { count: messages })] : []),
...(changes > 0 ? [trConflicts('signout_changes', { count: changes })] : []),
].join(' '),
confirmText: tr('signout.confirm'),
variant: 'destructive',
});
+5 -1
View File
@@ -31,6 +31,8 @@ export function OfflineSettings() {
const labels = useAccountStore((s) => s.accounts);
const enabledCount = useOfflineStore((s) => s.enabled.length);
const persist = useOfflineStore((s) => s.persist);
const blocked = useOfflineStore((s) => s.storageBlocked);
const tNotes = useTranslations('offlineConflicts');
const [asking, setAsking] = useState(false);
useEffect(() => {
@@ -51,7 +53,9 @@ export function OfflineSettings() {
return (
<SettingsSection id="offline" title={t('title')} description={t('description')}>
{!offlineSupported() ? (
{blocked ? (
<p className="text-sm text-muted-foreground" data-testid="offline-private">{tNotes('store_private')}</p>
) : !offlineSupported() ? (
<p className="text-sm text-muted-foreground" data-testid="offline-unsupported">{t('unsupported')}</p>
) : (
<>
+1 -1
View File
@@ -133,7 +133,7 @@ export function PluginPageApp({ linkSegments = [] }: PluginPageAppProps) {
}
return (
<div className={cn("flex flex-col overflow-hidden pt-[env(safe-area-inset-top)]", mvShell ? "bg-[var(--mv-canvas)]" : "bg-background", isEmbedded ? "h-full" : "h-dvh")}>
<div className={cn("flex flex-col overflow-hidden pt-[var(--app-top-inset)]", mvShell ? "bg-[var(--mv-canvas)]" : "bg-background", isEmbedded ? "h-full" : "h-dvh")}>
<AppTopBannerSlot />
{mvShell && (
<MvTopBar
@@ -0,0 +1,144 @@
import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { FakeBroadcastChannel } from '@/lib/__tests__/fixtures/fake-broadcast-channel';
import { openPopoutChannel, type PopoutMessage, type RescuedDraft } from '@/lib/popout/channel';
import { createComposeHandoff, rememberComposePayload } from '@/lib/popout/compose-handoff';
import { useAuthStore } from '@/stores/auth-store';
import { usePluginStore } from '@/stores/plugin-store';
// The composer's window: when it tells the opening window to let go, and what
// happens on a reload. The composer itself is stubbed; its own tests cover it.
type ComposerProps = {
initialData?: { draftId?: string | null; subject?: string; unsaved?: boolean } | null;
ownWindow: { rescueDraft: (draft: RescuedDraft) => boolean };
};
let composer: ComposerProps | null;
vi.mock('@/components/email/email-composer', () => ({
EmailComposer: (props: ComposerProps) => {
composer = props;
return <div data-testid="composer">{props.initialData?.subject}</div>;
},
}));
vi.mock('@/components/error', () => ({ ErrorBoundary: ({ children }: { children: React.ReactNode }) => <>{children}</>, ComposerErrorFallback: () => null }));
vi.mock('../popout-shell', () => ({
PopoutShell: ({ children }: { children: React.ReactNode }) => <>{children}</>,
PopoutSkeleton: () => <div data-testid="skeleton" />,
}));
vi.mock('@/hooks/use-document-title', () => ({ useDocumentTitle: vi.fn() }));
const { PopoutComposeApp } = await import('../popout-compose-app');
const original = useAuthStore.getState();
const PAYLOAD = { mode: 'compose' as const, initialData: { subject: 'Moving', draftId: 'old', unsaved: true } as never };
let heard: PopoutMessage[];
let listener: NonNullable<ReturnType<typeof openPopoutChannel>>;
const settle = async (ms = 10) => {
for (let round = 0; round < 5; round++) {
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, ms));
});
}
};
beforeEach(() => {
FakeBroadcastChannel.reset();
vi.stubGlobal('BroadcastChannel', FakeBroadcastChannel);
sessionStorage.clear();
composer = null;
heard = [];
listener = openPopoutChannel((message) => heard.push(message))!;
useAuthStore.setState({ client: {} as never, activeAccountId: 'alice' });
});
afterEach(() => {
cleanup();
listener.close();
useAuthStore.setState(original);
vi.unstubAllGlobals();
vi.resetModules();
window.history.replaceState(null, '', '/');
});
function openAt(handoffId: string) {
window.history.replaceState(null, '', `/en/popout/compose?handoff=${handoffId}&account=alice`);
render(<PopoutComposeApp />);
}
describe('PopoutComposeApp', () => {
it('tells the opening window to let go only with the composer on screen', async () => {
const handoff = createComposeHandoff()!;
openAt(handoff.id);
await settle();
expect(heard.some((message) => message.type === 'handoff-rendered')).toBe(false);
expect(screen.queryByTestId('composer')).toBeNull();
await expect(Promise.all([handoff.complete(PAYLOAD), settle()]).then(([shown]) => shown)).resolves.toBe(true);
expect(screen.getByTestId('composer').textContent).toBe('Moving');
});
it('does not while it has no session, so the opening window keeps its copy', async () => {
useAuthStore.setState({ client: null });
const handoff = createComposeHandoff()!;
openAt(handoff.id);
await settle();
const shown = handoff.complete(PAYLOAD, 100);
await settle(30);
await expect(shown).resolves.toBe(false);
handoff.cancel();
await settle();
});
it('closes when the opening window takes the draft back, also after it was delivered', async () => {
const close = vi.spyOn(window, 'close').mockImplementation(() => {});
useAuthStore.setState({ client: null });
const handoff = createComposeHandoff()!;
openAt(handoff.id);
await settle();
void handoff.complete(PAYLOAD, 5000);
await settle();
expect(screen.getByTestId('composer')).toBeTruthy();
handoff.cancel();
await settle();
expect(screen.queryByTestId('composer')).toBeNull();
expect(close).toHaveBeenCalled();
close.mockRestore();
});
it('after a reload, takes up the id its text was saved under, so no second draft appears', async () => {
rememberComposePayload('h1', PAYLOAD);
const main = openPopoutChannel((message) => {
if (message.type === 'rescue-query') main.post({ type: 'rescue-answer', rescueKey: message.rescueKey, draftId: 'saved-by-main' });
})!;
openAt('h1');
await waitFor(() => expect(composer?.initialData?.draftId).toBe('saved-by-main'));
expect(composer?.initialData?.unsaved).toBe(false);
main.close();
});
it('after a reload with nothing handed over, keeps what it holds', async () => {
rememberComposePayload('h2', PAYLOAD);
openAt('h2');
await waitFor(() => expect(composer?.initialData?.draftId).toBe('old'), { timeout: 4000 });
expect(composer?.initialData?.unsaved).toBe(true);
});
it('names the login and the key when it hands over a closing draft', async () => {
const main = openPopoutChannel((message) => {
if (message.type === 'main-ping') main.post({ type: 'main-pong', windowId: 'w', accountIds: ['alice'] });
})!;
rememberComposePayload('h3', { mode: 'compose' });
openAt('h3');
await waitFor(() => expect(composer).not.toBeNull());
await settle();
usePluginStore.setState({ initialized: false });
expect(composer!.ownWindow.rescueDraft({ state: {} } as RescuedDraft), 'before plugins have started').toBe(false);
usePluginStore.setState({ initialized: true });
expect(composer!.ownWindow.rescueDraft({ state: {} } as RescuedDraft)).toBe(true);
await settle();
expect(heard.find((message) => message.type === 'draft-rescue')).toMatchObject({ draft: { localAccountId: 'alice', rescueKey: 'h3' } });
main.close();
});
});
@@ -0,0 +1,319 @@
import { act, cleanup, render } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { FakeBroadcastChannel } from '@/lib/__tests__/fixtures/fake-broadcast-channel';
import { openPopoutChannel, requestWindowSession, watchMainWindow, askRescuedDraftId, type PopoutMessage, type RescuedDraft } from '@/lib/popout/channel';
import { takeRescuedDraft } from '@/lib/popout/rescued-drafts';
import { createSessionOpener } from '@/lib/popout/sealed';
import { useAccountStore } from '@/stores/account-store';
import { useAuthStore } from '@/stores/auth-store';
import { useEmailStore } from '@/stores/email-store';
import { useToastStore } from '@/stores/toast-store';
import { PopoutHost } from '../popout-host';
// The main window's side of pop-outs. The next-intl mock returns the key.
const DRAFT: RescuedDraft = {
localAccountId: 'alice',
to: ['a@example.test'], subject: 'Closing', body: 'text', cc: [], bcc: [], draftId: 'old', attachments: [],
state: { subject: 'Closing' } as never,
};
const original = { auth: useAuthStore.getState(), email: useEmailStore.getState(), accounts: useAccountStore.getState() };
let heard: PopoutMessage[];
let popout: NonNullable<ReturnType<typeof openPopoutChannel>>;
let client: { createDraft: ReturnType<typeof vi.fn>; getAuthHeader: () => string; isOfflineOnly: () => boolean };
let lockRequests: string[];
// Rounds, not one long wait: a message and its answer are two hops, and a busy
// machine can run a single timer before the second hop is even queued.
const settle = async (ms = 10) => {
for (let round = 0; round < 5; round++) {
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, ms));
});
}
};
/** Web Locks with one holder per name, as a browser has. */
function stubLocks() {
const held = new Set<string>();
lockRequests = [];
Object.defineProperty(navigator, 'locks', {
configurable: true,
value: {
request(name: string, options: { ifAvailable?: boolean }, callback: (lock: unknown) => Promise<unknown>) {
lockRequests.push(name);
if (options.ifAvailable && held.has(name)) return Promise.resolve(callback(null));
held.add(name);
return Promise.resolve(callback({}));
},
},
});
}
beforeEach(() => {
FakeBroadcastChannel.reset();
vi.stubGlobal('BroadcastChannel', FakeBroadcastChannel);
// The bridge makes pop-outs available without stubbing the display mode.
window.bulwarkDesktop = { version: 1, platform: 'win32', windows: {} };
stubLocks();
sessionStorage.clear();
heard = [];
popout = openPopoutChannel((message) => heard.push(message))!;
client = { createDraft: vi.fn(async () => 'new'), getAuthHeader: () => 'Bearer main', isOfflineOnly: () => false };
useAccountStore.setState({
accounts: [{ id: 'alice', serverUrl: 'https://mail.example.test', username: 'alice', authMode: 'oauth', cookieSlot: 0 } as never],
activeAccountId: 'alice',
});
useAuthStore.setState({
isAuthenticated: true,
isDemoMode: false,
activeAccountId: 'alice',
client: client as never,
getAllConnectedClients: () => new Map([['alice', client]]) as never,
getClientForAccount: (id: string) => (id === 'alice' ? client : undefined) as never,
});
useEmailStore.setState({ refreshCurrentMailbox: vi.fn(async () => {}) as never, fetchMailboxes: vi.fn(async () => {}) as never, pendingUndoSend: null });
useToastStore.getState().clearToasts();
});
afterEach(() => {
cleanup();
popout.close();
delete window.bulwarkDesktop;
useAuthStore.setState(original.auth);
useEmailStore.setState(original.email);
useAccountStore.setState(original.accounts);
vi.unstubAllGlobals();
Object.defineProperty(navigator, 'locks', { configurable: true, value: undefined });
});
const answers = () => heard.filter((message) => message.type === 'session-answer');
describe('in an ordinary browser tab', () => {
it('runs nothing: no channel and no lock', async () => {
delete window.bulwarkDesktop;
const opened = FakeBroadcastChannel.open.size;
render(<PopoutHost />);
await settle();
expect(FakeBroadcastChannel.open.size).toBe(opened);
expect(lockRequests).toEqual([]);
popout.post({ type: 'main-ping' });
await settle();
expect(heard).toEqual([]);
});
});
describe('PopoutHost', () => {
it('holds no lock while idle, which would keep the page out of the back/forward cache', async () => {
render(<PopoutHost />);
await settle();
expect(lockRequests).toEqual([]);
});
it('lends the session to a pop-out that asks, sealed', async () => {
render(<PopoutHost />);
await settle();
await expect(requestWindowSession({}, 2000)).resolves.toMatchObject({
activeAccountId: 'alice',
sessions: [{ accountId: 'alice', authHeader: 'Bearer main', authMode: 'oauth' }],
});
expect(JSON.stringify(heard)).not.toContain('Bearer main');
});
it('says nothing while it has no session to lend, so a pop-out goes on to the cookies', async () => {
useAuthStore.setState({ isAuthenticated: false });
render(<PopoutHost />);
await settle();
await expect(requestWindowSession({}, 100)).resolves.toBeNull();
});
it('says nothing about a login it does not hold, so the window that holds it answers first', async () => {
render(<PopoutHost />);
await settle();
await expect(requestWindowSession({ accountId: 'bob' }, 100)).resolves.toBeNull();
expect(answers()).toEqual([]);
});
it('renews a token the server refused, once, in this window', async () => {
const refresh = vi.fn(async () => 'next');
useAuthStore.setState({ refreshAccessToken: refresh as never });
render(<PopoutHost />);
await settle();
await requestWindowSession({ accountId: 'alice', rejectedAuthHeader: 'Bearer main' }, 2000);
expect(refresh).toHaveBeenCalledWith({ accountId: 'alice' });
refresh.mockClear();
await requestWindowSession({ accountId: 'alice', rejectedAuthHeader: 'Bearer older' }, 2000);
expect(refresh).not.toHaveBeenCalled();
});
it('saves a closing window\'s draft, replacing its version', async () => {
render(<PopoutHost />);
await settle();
popout.post({ type: 'draft-rescue', draft: DRAFT });
await settle();
expect(client.createDraft).toHaveBeenCalledTimes(1);
expect(client.createDraft.mock.calls[0].slice(0, 2)).toEqual([['a@example.test'], 'Closing']);
expect(client.createDraft.mock.calls[0][7]).toBe('old');
});
it('saves it once with two main windows open', async () => {
render(<><PopoutHost /><PopoutHost /></>);
await settle();
popout.post({ type: 'draft-rescue', draft: { ...DRAFT, rescueKey: 'k' } });
await settle();
expect(client.createDraft).toHaveBeenCalledTimes(1);
});
it('keeps the text for the "Continue draft" slot when the save fails, and says so', async () => {
client.createDraft.mockRejectedValueOnce(new Error('Server down'));
vi.spyOn(console, 'error').mockImplementation(() => {});
render(<PopoutHost />);
await settle();
popout.post({ type: 'draft-rescue', draft: DRAFT });
await settle();
expect(useToastStore.getState().toasts.map((toast) => toast.type)).toEqual(['error']);
expect(takeRescuedDraft()).toMatchObject({ subject: 'Closing', unsaved: true });
});
it('keeps the text too when the login is gone by then', async () => {
vi.spyOn(console, 'error').mockImplementation(() => {});
useAuthStore.setState({ getClientForAccount: () => undefined });
render(<PopoutHost />);
await settle();
popout.post({ type: 'draft-rescue', draft: DRAFT });
await settle();
expect(takeRescuedDraft()).toMatchObject({ subject: 'Closing' });
});
it('tells a reloaded pop-out which id its text was saved under', async () => {
render(<PopoutHost />);
await settle();
popout.post({ type: 'draft-rescue', draft: { ...DRAFT, rescueKey: 'k1' } });
await settle();
await expect(askRescuedDraftId('k1', 1000)).resolves.toBe('new');
await expect(askRescuedDraftId('nobody', 50)).resolves.toBeNull();
});
it('takes over the send\'s outcome once, and offers Undo here', async () => {
render(<><PopoutHost /><PopoutHost /></>);
await settle();
const pending = { submissionId: 's', sendAt: '2030-01-01T00:00:00Z', isSmime: false };
popout.post({ type: 'sent', requestId: 'r1', notice: { accountId: 'alice', pendingUndoSend: pending } });
await settle();
expect(heard.filter((message) => message.type === 'sent-ack')).toHaveLength(1);
expect(useEmailStore.getState().pendingUndoSend).toEqual(pending);
expect(useToastStore.getState().toasts).toEqual([]);
useEmailStore.setState({ pendingUndoSend: null });
popout.post({ type: 'sent', requestId: 'r2', notice: { accountId: 'alice' } });
await settle();
expect(useToastStore.getState().toasts).toHaveLength(1);
});
it('refreshes the list and counts when a pop-out changed mail, once for a burst', async () => {
render(<PopoutHost />);
await settle();
popout.post({ type: 'mail-changed', accountId: 'alice' });
popout.post({ type: 'mail-changed', accountId: 'alice' });
await settle(400);
expect(useEmailStore.getState().refreshCurrentMailbox).toHaveBeenCalledTimes(1);
expect(useEmailStore.getState().fetchMailboxes).toHaveBeenCalledTimes(1);
});
it('tells pop-outs when its own list changed, since no push reports that to them', async () => {
render(<PopoutHost />);
await settle();
act(() => useEmailStore.setState({ emails: [{ id: 'x' } as never] }));
await settle(120);
expect(heard).toContainEqual({ type: 'state-change' });
});
it('tells pop-outs when an account went away', async () => {
render(<PopoutHost />);
await settle();
act(() => useAccountStore.setState({ accounts: [] }));
await settle();
expect(heard).toContainEqual({ type: 'account-removed', accountId: 'alice' });
});
});
describe('watchMainWindow', () => {
it('knows a main window is there, and hands it the draft', async () => {
render(<PopoutHost />);
await settle();
const main = watchMainWindow();
await settle();
expect(main.alive()).toBe(true);
expect(main.rescue(DRAFT)).toBe(true);
await settle();
expect(client.createDraft).toHaveBeenCalledTimes(1);
main.stop();
});
it('won\'t hand a draft to a window that doesn\'t hold its login', async () => {
render(<PopoutHost />);
await settle();
const main = watchMainWindow();
await settle();
expect(main.alive('alice')).toBe(true);
expect(main.alive('bob')).toBe(false);
expect(main.rescue({ ...DRAFT, localAccountId: 'bob' })).toBe(false);
await settle();
expect(client.createDraft).not.toHaveBeenCalled();
main.stop();
});
it('knows at once when the last one closed, and takes nothing then', async () => {
render(<PopoutHost />);
await settle();
const main = watchMainWindow();
await settle();
await act(async () => { window.dispatchEvent(new Event('pagehide')); });
cleanup();
await settle();
expect(main.alive()).toBe(false);
expect(main.rescue(DRAFT)).toBe(false);
expect(client.createDraft).not.toHaveBeenCalled();
main.stop();
});
it('is not fooled by a closing window that still runs long enough to hear the ping', async () => {
render(<PopoutHost />);
await settle();
const main = watchMainWindow();
await settle();
// Still mounted: the page is on its way out, its scripts haven't stopped.
await act(async () => { window.dispatchEvent(new Event('pagehide')); });
const late = openPopoutChannel(() => {})!;
late.post({ type: 'main-ping' });
await settle();
late.close();
expect(main.alive()).toBe(false);
expect(main.rescue(DRAFT)).toBe(false);
main.stop();
});
it('takes nothing with no main window from the start', async () => {
const main = watchMainWindow();
await settle();
expect(main.rescue(DRAFT)).toBe(false);
main.stop();
});
});
describe('sealed answers', () => {
it('open only for the window that asked', async () => {
render(<PopoutHost />);
await settle();
const other = await createSessionOpener();
const mine = await createSessionOpener();
popout.post({ type: 'session-request', requestId: 'r', publicKey: mine.publicKey });
await settle();
const [answer] = answers();
expect(answer).toBeTruthy();
if (answer.type !== 'session-answer') throw new Error('unreachable');
await expect(mine.open(answer.sealed)).resolves.toMatchObject({ activeAccountId: 'alice' });
await expect(other.open(answer.sealed)).rejects.toThrow();
});
});
@@ -0,0 +1,183 @@
import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { Email } from '@/lib/jmap/types';
import { FakeBroadcastChannel } from '@/lib/__tests__/fixtures/fake-broadcast-channel';
import { openPopoutChannel } from '@/lib/popout/channel';
import { useAuthStore } from '@/stores/auth-store';
import { useEmailStore } from '@/stores/email-store';
// The pop-out message around the view it hosts: the view is stubbed, since the
// Pro tab's tests cover it. The next-intl mock returns the key.
type ViewProps = {
emailId: string;
clientAccountId?: string;
accountId?: string;
liveState?: { keywords?: Record<string, boolean>; mailboxIds?: Record<string, boolean> } | null;
onLoaded?: (email: Email) => void;
onClose: () => void;
onOpenCompose?: (data: { mode: string }) => void;
onMailChanged?: () => void;
};
let view: ViewProps;
vi.mock('@/components/pro/pro-email-tab-body', () => ({
ProEmailView: (props: ViewProps) => {
view = props;
return <div data-testid="message-view" />;
},
}));
vi.mock('../popout-shell', () => ({
PopoutShell: ({ children }: { children: React.ReactNode }) => <>{children}</>,
PopoutNotice: ({ title, children }: { title: string; children: React.ReactNode }) => <div><h1>{title}</h1>{children}</div>,
PopoutSkeleton: () => <div data-testid="skeleton" />,
}));
vi.mock('@/hooks/use-document-title', () => ({ useDocumentTitle: vi.fn() }));
const { PopoutMessageApp } = await import('../popout-message-app');
const original = { auth: useAuthStore.getState(), email: useEmailStore.getState() };
const EMAIL = { id: 'm/1', subject: 'Hello', keywords: { $seen: true }, mailboxIds: { inbox: true } } as unknown as Email;
let found: Array<Partial<Email>> | Error;
let client: { getSomeEmails: ReturnType<typeof vi.fn> };
const settle = async () => {
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 5));
});
};
beforeEach(() => {
FakeBroadcastChannel.reset();
vi.stubGlobal('BroadcastChannel', FakeBroadcastChannel);
window.history.replaceState(null, '', '/en/popout/message/m%2F1?account=login-b&owner=group');
found = [EMAIL];
client = {
getSomeEmails: vi.fn(async () => {
if (found instanceof Error) throw found;
return found;
}),
};
useAuthStore.setState({
client: client as never,
activeAccountId: 'login-a',
getClientForAccount: (id: string) => (id === 'login-b' ? client : undefined) as never,
});
useEmailStore.setState({
emails: [],
mailboxes: [{ id: 'inbox', name: 'Inbox', role: 'inbox' }, { id: 'archive', name: 'Old mail', role: null }] as never,
fetchMailboxes: vi.fn(async () => {}) as never,
});
});
afterEach(() => {
cleanup();
useAuthStore.setState(original.auth);
useEmailStore.setState(original.email);
vi.unstubAllGlobals();
window.history.replaceState(null, '', '/');
});
describe('PopoutMessageApp', () => {
it('opens the message of the address, through its login and account', async () => {
render(<PopoutMessageApp id="rendered-for-another-id" />);
await settle();
expect(view.emailId).toBe('m/1');
expect(view.clientAccountId).toBe('login-b');
expect(view.accountId).toBe('group');
expect(client.getSomeEmails).toHaveBeenCalledWith(['m/1'], 'group');
});
it('shows the message once the folders are in: Delete needs Trash, and the toolbar must not move', async () => {
let finish: () => void = () => {};
useEmailStore.setState({ mailboxes: [], fetchMailboxes: vi.fn(() => new Promise<void>((resolve) => { finish = resolve; })) as never });
render(<PopoutMessageApp id="m1" />);
await settle();
expect(screen.queryByTestId('message-view')).toBeNull();
expect(screen.getByTestId('skeleton')).toBeTruthy();
await act(async () => { finish(); });
await settle();
expect(screen.getByTestId('message-view')).toBeTruthy();
});
it('shows the message anyway when the folders cannot be fetched', async () => {
useEmailStore.setState({ mailboxes: [], fetchMailboxes: vi.fn(async () => { throw new Error('offline'); }) as never });
render(<PopoutMessageApp id="m1" />);
await settle();
expect(screen.getByTestId('message-view')).toBeTruthy();
});
it('puts the loaded message where delete, move, star and read look for it', async () => {
render(<PopoutMessageApp id="m1" />);
await settle();
act(() => view.onLoaded?.(EMAIL));
expect(useEmailStore.getState().emails).toEqual([EMAIL]);
expect(useEmailStore.getState().selectedMailbox).toBe('inbox');
});
it('says so when the message is gone', async () => {
found = [];
render(<PopoutMessageApp id="m1" />);
await screen.findByText('message_gone_title');
expect(screen.queryByTestId('message-view')).toBeNull();
});
it('keeps the message on screen when the server does not answer', async () => {
found = new TypeError('Failed to fetch');
render(<PopoutMessageApp id="m1" />);
await settle();
expect(screen.getByTestId('message-view')).toBeTruthy();
expect(screen.queryByText('message_gone_title')).toBeNull();
});
it('checks again when another window reports a change, and shows the new flags', async () => {
const main = openPopoutChannel(() => {})!;
render(<PopoutMessageApp id="m1" />);
await settle();
act(() => view.onLoaded?.(EMAIL));
found = [{ ...EMAIL, keywords: { $seen: false } }];
main.post({ type: 'state-change' });
await waitFor(() => expect(view.liveState?.keywords).toEqual({ $seen: false }));
// And the next toggle starts from them.
expect(useEmailStore.getState().emails[0].keywords).toEqual({ $seen: false });
main.close();
});
it('checks again when the window gets the focus', async () => {
render(<PopoutMessageApp id="m1" />);
await settle();
found = [];
act(() => { window.dispatchEvent(new Event('focus')); });
await screen.findByText('message_gone_title');
});
it('says where a moved message went, and keeps showing it', async () => {
render(<PopoutMessageApp id="m1" />);
await settle();
expect(document.querySelector('[data-popout-moved]')).toBeNull();
found = [{ ...EMAIL, mailboxIds: { archive: true } }];
act(() => { window.dispatchEvent(new Event('focus')); });
await waitFor(() => expect(document.querySelector('[data-popout-moved]')?.textContent).toContain('message_moved_to'));
expect(screen.getByTestId('message-view')).toBeTruthy();
});
it('tells the main window when it changed something', async () => {
const heard: string[] = [];
const main = openPopoutChannel((message) => heard.push(message.type))!;
render(<PopoutMessageApp id="m1" />);
await settle();
act(() => view.onMailChanged?.());
await settle();
expect(heard).toContain('mail-changed');
main.close();
});
it('closes the window when the message leaves it', async () => {
const close = vi.spyOn(window, 'close').mockImplementation(() => {});
render(<PopoutMessageApp id="m1" />);
await settle();
act(() => view.onClose());
expect(close).toHaveBeenCalledTimes(1);
close.mockRestore();
});
});
@@ -0,0 +1,156 @@
import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
import { useEffect } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { FakeBroadcastChannel } from '@/lib/__tests__/fixtures/fake-broadcast-channel';
import { registerComposeFlush } from '@/lib/compose-flush-registry';
import { SIGNED_OUT_KEY } from '@/lib/sign-out-cleanup';
import { openPopoutChannel } from '@/lib/popout/channel';
import { sealFor } from '@/lib/popout/sealed';
import { SHARED_SESSION_ENDED_EVENT, useAuthStore } from '@/stores/auth-store';
import { PopoutShell } from '../popout-shell';
// How a pop-out's session ends. The next-intl mock returns the key.
vi.mock('@/hooks/use-config', () => ({ useConfig: () => ({ appName: 'Mail' }) }));
const original = useAuthStore.getState();
let close: ReturnType<typeof vi.spyOn>;
let mounts: number;
function Child() {
useEffect(() => {
mounts += 1;
}, []);
return <div data-testid="content">Typed text</div>;
}
const settle = async (ms = 10) => {
for (let round = 0; round < 5; round++) {
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, ms));
});
}
};
async function mount(kind: 'message' | 'compose', session: 'ready' | 'no-session' = 'ready') {
useAuthStore.setState({ startSharedSession: vi.fn(async () => session) as never, activeAccountId: 'alice' });
render(<PopoutShell kind={kind}><Child /></PopoutShell>);
await settle();
}
function endSession() {
act(() => { window.dispatchEvent(new Event(SHARED_SESSION_ENDED_EVENT)); });
}
function signOutElsewhere() {
act(() => { window.dispatchEvent(new StorageEvent('storage', { key: SIGNED_OUT_KEY, newValue: String(Date.now()) })); });
}
beforeEach(() => {
FakeBroadcastChannel.reset();
vi.stubGlobal('BroadcastChannel', FakeBroadcastChannel);
close = vi.spyOn(window, 'close').mockImplementation(() => {});
mounts = 0;
});
afterEach(() => {
cleanup();
useAuthStore.setState(original);
close.mockRestore();
vi.unstubAllGlobals();
});
describe('when the session is refused', () => {
it('stops showing a message', async () => {
await mount('message');
expect(screen.getByTestId('content')).toBeTruthy();
endSession();
expect(screen.queryByTestId('content')).toBeNull();
expect(screen.getByText('session_ended_title')).toBeTruthy();
});
it('keeps a composer on screen, the same one, with the text in it', async () => {
await mount('compose');
endSession();
expect(screen.getByTestId('content')).toBeTruthy();
expect(mounts).toBe(1);
expect(document.querySelector('[data-popout-session-ended]')).toBeTruthy();
});
});
describe('with no session at all', () => {
it('shows a composer that holds text, and says why it can\'t send', async () => {
await mount('compose', 'no-session');
expect(screen.getByTestId('content')).toBeTruthy();
expect(document.querySelector('[data-popout-session-ended]')).toBeTruthy();
});
it('shows no message', async () => {
await mount('message', 'no-session');
expect(screen.queryByTestId('content')).toBeNull();
});
});
describe('when another window signs everyone out', () => {
it('saves the typing first, then closes', async () => {
const order: string[] = [];
const stop = registerComposeFlush(async () => { order.push('saved'); });
close.mockImplementation(() => { order.push('closed'); });
await mount('compose');
signOutElsewhere();
await settle();
expect(order).toEqual(['saved', 'closed']);
stop();
});
it('stays open when the typing could not be saved', async () => {
const stop = registerComposeFlush(async () => { throw new Error('The draft was not saved'); });
await mount('compose');
signOutElsewhere();
await settle();
expect(close).not.toHaveBeenCalled();
expect(screen.getByTestId('content')).toBeTruthy();
expect(document.querySelector('[data-popout-session-ended]')).toBeTruthy();
stop();
});
it('closes a message window', async () => {
await mount('message');
signOutElsewhere();
await settle();
expect(close).toHaveBeenCalled();
});
});
describe('when a login leaves the list', () => {
it('closes when no window holds it any more', async () => {
const main = openPopoutChannel(() => {})!;
await mount('message');
main.post({ type: 'account-removed', accountId: 'alice' });
await waitFor(() => expect(close).toHaveBeenCalled(), { timeout: 3000 });
main.close();
});
it('stays when another tab still holds it: a new tab dropped a login it could not restore', async () => {
const main = openPopoutChannel((message) => {
if (message.type !== 'session-request') return;
void sealFor(message.publicKey, { activeAccountId: 'alice', sessions: [{ accountId: 'alice' }] })
.then((sealed) => main.post({ type: 'session-answer', requestId: message.requestId, sealed }));
})!;
await mount('message');
main.post({ type: 'account-removed', accountId: 'alice' });
await settle(250);
expect(close).not.toHaveBeenCalled();
expect(screen.getByTestId('content')).toBeTruthy();
main.close();
});
it('ignores another login', async () => {
const main = openPopoutChannel(() => {})!;
await mount('message');
main.post({ type: 'account-removed', accountId: 'bob' });
await settle(250);
expect(close).not.toHaveBeenCalled();
main.close();
});
});
+15
View File
@@ -0,0 +1,15 @@
"use client";
import { usePathname } from "next/navigation";
import { isPopoutPath } from "@/lib/popout/window-role";
/**
* What belongs to the app as a whole and not to each of its windows: live
* push streams, install and update prompts, the command palette's jumps to
* other surfaces. A pop-out shows one message or one draft, and the main
* window does the rest.
*/
export function MainWindowOnly({ children }: { children: React.ReactNode }) {
const pathname = usePathname();
return isPopoutPath(pathname ?? "") ? null : <>{children}</>;
}
+222
View File
@@ -0,0 +1,222 @@
"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
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 { 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 { formatRejectedRecipients } from "@/lib/jmap/client";
import { debug } from "@/lib/debug";
import { composerSendOptions } from "@/lib/outgoing/composer-send-options";
import { announceSent } from "@/lib/plugin-after-send";
import { announceMailChanged, announceSentToMainWindow, askRescuedDraftId, watchMainWindow, type RescuedDraft } from "@/lib/popout/channel";
import { acknowledgeComposeHandoff, receiveComposeHandoff, rememberComposePayload, rememberedComposePayload, watchHandoffCancel } from "@/lib/popout/compose-handoff";
import type { ComposePopoutPayload } from "@/lib/popout/compose-payload";
import { closePopoutWindow } from "@/lib/popout/window-role";
import { PopoutShell, PopoutSkeleton } from "./popout-shell";
/** A warning with no main window left to show it stays this long before the window goes. */
const WARNING_READ_MS = 8000;
type ComposerProps = React.ComponentProps<typeof EmailComposer>;
type SendData = Parameters<NonNullable<ComposerProps["onSend"]>>[0];
const EMPTY_PAYLOAD: ComposePopoutPayload = { mode: "compose" };
/** How long a reloaded window waits to hear what became of the text it handed over on the way out. */
const RESCUE_ANSWER_MS = 2000;
function readLaunch(): { handoffId: string | null; accountId?: string } {
if (typeof window === "undefined") return { handoffId: null };
const search = new URLSearchParams(window.location.search);
return { handoffId: search.get("handoff"), accountId: search.get("account") ?? undefined };
}
/** The composer alone, in its own window: sending, autosave and discard go through the shared stores, as in a Pro tab. */
function PopoutComposer({ payload, handoffId }: { payload: ComposePopoutPayload; handoffId: string | null }) {
const t = useTranslations();
const client = useAuthStore((s) => s.client);
const [sessionKey] = useState(() => `popout-${handoffId ?? Date.now().toString(36)}`);
const mode = payload.initialData?.mode ?? payload.mode;
useDocumentTitle(
mode === "reply" ? t("email_composer.reply")
: mode === "replyAll" ? t("email_composer.reply_all")
: mode === "forward" ? t("email_composer.forward")
: t("email_composer.new_message"),
);
const handleSend = useCallback(async (data: SendData) => {
if (!client) return false;
const sendClient = data.localAccountId
? (useAuthStore.getState().getClientForAccount(data.localAccountId) ?? client)
: client;
const emailStore = useEmailStore.getState();
// A send that fails goes to the composer, which stays open with the text.
const result = await emailStore.sendEmail(
sendClient,
data.to,
data.subject,
data.body,
data.cc,
data.bcc,
data.identityId,
data.fromEmail,
data.draftId,
data.fromName,
data.htmlBody,
data.attachments,
data.inReplyTo,
data.references,
data.delayedUntil,
data.envelopeMailFrom,
composerSendOptions(data),
);
announceSent(result, data);
if (payload.sourceEmailId && (mode === "reply" || mode === "replyAll" || mode === "forward")) {
const keyword = mode === "forward" ? "$forwarded" : "$answered";
try {
await useEmailStore.getState().markEmailKeyword(client, payload.sourceEmailId, keyword, payload.sourceEmailSource ?? undefined);
} catch (error) {
debug.error(`Failed to set ${keyword} keyword:`, error);
}
}
const accountId = data.localAccountId ?? useAuthStore.getState().activeAccountId;
const pending = useEmailStore.getState().pendingUndoSend;
const rejectedRecipients = result.rejectedRecipients?.length ? formatRejectedRecipients(result.rejectedRecipients) : undefined;
const taken = await announceSentToMainWindow({
accountId,
scheduled: !!result.scheduled,
queued: !!result.queued,
filingError: !!result.filingError,
rejectedRecipients,
pendingUndoSend: pending ? { ...pending, localAccountId: pending.localAccountId ?? accountId ?? undefined } : null,
});
// No main window to say so, and this is the only notice these get (#1123).
if (!taken && (result.filingError || rejectedRecipients)) {
if (result.filingError) toast.warning(t("email_composer.send_filing_warning"));
if (rejectedRecipients) toast.warning(t("email_composer.send_some_recipients_rejected"), { message: rejectedRecipients, duration: WARNING_READ_MS });
await new Promise((resolve) => setTimeout(resolve, WARNING_READ_MS));
}
}, [client, mode, payload.sourceEmailId, payload.sourceEmailSource, t]);
const handleDiscardDraft = useCallback(async (draftId: string, draft?: { accountId?: string; localAccountId?: string }) => {
if (!client) return;
// Through the login the draft was saved with, and never another: the id names another message there.
const draftClient = draft?.localAccountId
? useAuthStore.getState().getClientForAccount(draft.localAccountId)
: client;
if (!draftClient) {
toast.error(t("email_composer.discard_signed_out"));
return;
}
try {
await draftClient.deleteEmail(draftId, draft?.accountId);
} catch (error) {
console.error("Failed to discard draft:", error);
}
}, [client, t]);
const handleClose = useCallback(() => {
announceMailChanged(useAuthStore.getState().activeAccountId);
closePopoutWindow();
}, []);
const [mainWindow] = useState(watchMainWindow);
useEffect(() => () => mainWindow.stop(), [mainWindow]);
// The window that opened this one lets go of its copy now. Not without a
// session: this one couldn't save or send the text.
useEffect(() => {
if (handoffId && client) acknowledgeComposeHandoff(handoffId);
}, [handoffId, client]);
const ownWindow = useMemo(() => ({
rescueDraft: (draft: RescuedDraft) => {
// A plugin that hasn't started may yet have a say in what a draft holds,
// and it can only have it in this window's save.
if (!usePluginStore.getState().initialized) return false;
return mainWindow.rescue({
...draft,
localAccountId: draft.localAccountId ?? useAuthStore.getState().activeAccountId ?? undefined,
rescueKey: handoffId ?? undefined,
});
},
// A reload of this window starts from where the text is now.
onUnloadState: (state: ComposerDraftData) => {
if (handoffId) rememberComposePayload(handoffId, { ...payload, initialData: state, prefill: null });
},
onDraftSaved: () => announceMailChanged(useAuthStore.getState().activeAccountId),
}), [handoffId, mainWindow, payload]);
return (
<ErrorBoundary fallback={ComposerErrorFallback}>
<EmailComposer
mode={mode}
replyTo={payload.replyTo}
initialDraftText={payload.initialDraftText}
initialData={payload.initialData}
prefill={payload.prefill}
sessionKey={sessionKey}
sourceEmailId={payload.sourceEmailId ?? undefined}
composeFromAccountEmail={payload.composeFromAccountEmail
?? useAccountStore.getState().getAccountById(useAuthStore.getState().activeAccountId ?? "")?.email}
onSend={handleSend}
onClose={handleClose}
onDiscardDraft={handleDiscardDraft}
ownWindow={ownWindow}
className="min-h-0 flex-1"
/>
</ErrorBoundary>
);
}
/** `/popout/compose`: a draft handed over by another window, or a new message. */
export function PopoutComposeApp() {
const t = useTranslations("pwaWindows");
const [{ handoffId, accountId }] = useState(readLaunch);
const [payload, setPayload] = useState<ComposePopoutPayload | null>(handoffId ? null : EMPTY_PAYLOAD);
useEffect(() => {
if (!handoffId) return;
let cancelled = false;
const reloaded = rememberedComposePayload(handoffId) !== null;
void receiveComposeHandoff(handoffId).then(async (received) => {
if (!received) {
// Called off or never ready: the composer stayed where it was.
if (!cancelled) closePopoutWindow();
return;
}
// Reloaded: the text may have gone to a main window on the way out, under
// a new id. Saving under the old one would leave two drafts.
const draftId = reloaded && received.initialData ? await askRescuedDraftId(handoffId, RESCUE_ANSWER_MS) : null;
if (cancelled) return;
setPayload(draftId && received.initialData
? { ...received, initialData: { ...received.initialData, draftId, draftAccountId: undefined, unsaved: false } }
: received);
});
// The opening window takes the draft back. Gone first, so that closing
// doesn't save a copy of what that window still has.
const stopWatching = watchHandoffCancel(handoffId, () => {
setPayload(null);
setTimeout(closePopoutWindow, 0);
});
return () => {
cancelled = true;
stopWatching();
};
}, [handoffId]);
return (
<PopoutShell kind="compose" accountId={accountId}>
{payload ? <PopoutComposer payload={payload} handoffId={handoffId} /> : <PopoutSkeleton label={t("opening")} />}
</PopoutShell>
);
}
+222
View File
@@ -0,0 +1,222 @@
"use client";
import { useEffect, useRef } from "react";
import { useTranslations } from "next-intl";
import { usePopoutsAvailable } from "@/hooks/use-popouts-available";
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 { newPopoutId, openPopoutChannel, type PopoutChannel, type PopoutMessage, type PopoutSentNotice, type RescuedDraft, type SharedAccountSession } from "@/lib/popout/channel";
import { keepRescuedDraft } from "@/lib/popout/rescued-drafts";
import { credentialFingerprint, sealFor } from "@/lib/popout/sealed";
import { changesAnyType, subscribePushStateChanges } from "@/lib/push-events";
/** At most this often: a pop-out's autosave reports every few seconds. */
const REFRESH_THROTTLE_MS = 1500;
/** What the list changing in this window waits for, so a burst tells pop-outs once. */
const LIST_CHANGE_DEBOUNCE_MS = 400;
/** How long the claim on a one-off job stays held: longer than a message takes to reach every window. */
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 sessions this window can lend. Empty until it is signed in, and in the demo. */
function shareableSessions(): SharedAccountSession[] {
const auth = useAuthStore.getState();
if (!auth.isAuthenticated || auth.isDemoMode) return [];
const sessions: SharedAccountSession[] = [];
for (const [accountId, client] of auth.getAllConnectedClients()) {
const account = useAccountStore.getState().getAccountById(accountId);
if (!account) continue;
sessions.push({
accountId,
serverUrl: account.serverUrl,
username: account.username,
authMode: account.authMode,
authHeader: client.getAuthHeader(),
...(client.isOfflineOnly() ? { offlineOnly: true } : {}),
});
}
return sessions;
}
/**
* Runs `work` in one of the main windows, the first to claim `name`. Held on
* for a while afterwards, or a slower window would find it free. A browser
* releases it with the window, so no window keeps a lock for long (one held for
* life keeps a page out of the back/forward cache).
*/
function claimOnce(name: string, work: () => void | Promise<void>): void {
void navigator.locks?.request(name, { ifAvailable: true }, async (lock) => {
if (!lock) return;
await work();
await new Promise((resolve) => setTimeout(resolve, CLAIM_HOLD_MS));
}).catch(() => {});
}
/**
* The main window's side of pop-outs: lends them its session and renews it
* for them, passes on that mail changed, and takes over what a pop-out can't
* say any more once it has closed. Only where pop-outs are on offer: an
* ordinary browser tab runs none of this.
*/
export function PopoutHost() {
const available = usePopoutsAvailable();
const t = useTranslations();
const tRef = useRef(t);
tRef.current = t;
useEffect(() => {
if (!available) return;
let channel: PopoutChannel | null = null;
const windowId = newPopoutId();
let closing = false;
const rescues = new Map<string, Promise<string | null>>();
const answerSessionRequest = async (message: Extract<PopoutMessage, { type: "session-request" }>) => {
const { accountId, rejectedFingerprint } = message;
const auth = useAuthStore.getState();
// Only a window holding the login answers: the first answer has to be usable.
if (accountId && !shareableSessions().some((session) => session.accountId === accountId)) return;
// The server refused what the pop-out holds. If that is what this window
// holds too, renew it here, where the timers and the sign-out live.
if (accountId && rejectedFingerprint) {
const current = auth.getClientForAccount(accountId)?.getAuthHeader();
if (current && await credentialFingerprint(current) === rejectedFingerprint) await auth.refreshAccessToken({ accountId });
}
const sessions = shareableSessions();
if (sessions.length === 0) return;
const sealed = await sealFor(message.publicKey, { activeAccountId: useAuthStore.getState().activeAccountId, sessions });
channel?.post({ type: "session-answer", requestId: message.requestId, sealed });
};
// List and counts, so read state and Drafts follow what a pop-out did.
let refreshTimer: ReturnType<typeof setTimeout> | null = null;
const refreshList = () => {
if (refreshTimer) return;
refreshTimer = setTimeout(() => {
refreshTimer = null;
const client = useAuthStore.getState().client;
if (!client) return;
const emails = useEmailStore.getState();
void emails.refreshCurrentMailbox(client);
void emails.fetchMailboxes(client);
}, REFRESH_THROTTLE_MS);
};
const takeOverSent = (notice: PopoutSentNotice) => {
const translate = tRef.current;
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 });
}
// Undo lives here now: the window that sent it is closing.
if (notice.pendingUndoSend) useEmailStore.setState({ pendingUndoSend: notice.pendingUndoSend });
else if (!notice.queued && !notice.scheduled && !notice.filingError && !notice.rejectedRecipients) toast.success(translate("notifications.email_sent"));
refreshList();
};
const saveRescuedDraft = async (draft: RescuedDraft): Promise<string | null> => {
const auth = useAuthStore.getState();
const client = draft.localAccountId ? auth.getClientForAccount(draft.localAccountId) : auth.client;
try {
if (!client) throw new Error("No login to save through");
const draftId = await client.createDraft(
draft.to, draft.subject, draft.body, draft.cc, draft.bcc, draft.identityId, draft.fromEmail, draft.draftId,
draft.attachments, draft.fromName, draft.htmlBody, draft.inReplyTo, draft.references, draft.options,
);
refreshList();
return draftId;
} catch (error) {
// The text exists nowhere else now.
console.error("Failed to save a closing window's draft:", error);
keepRescuedDraft(draft.state);
toast.error(tRef.current("email_composer.save_failed"));
return null;
}
};
const startRescue = (draft: RescuedDraft) => {
const claim = draft.rescueKey ?? newPopoutId();
claimOnce(`bulwark-popout-rescue:${claim}`, async () => {
const saved = saveRescuedDraft(draft);
if (draft.rescueKey) {
rescues.set(draft.rescueKey, saved);
setTimeout(() => rescues.delete(claim), RESCUE_MEMORY_MS);
}
await saved;
});
};
channel = openPopoutChannel((message) => {
switch (message.type) {
case "session-request":
void answerSessionRequest(message);
break;
case "sent":
claimOnce(`bulwark-popout-sent:${message.requestId}`, () => {
channel?.post({ type: "sent-ack", requestId: message.requestId });
takeOverSent(message.notice);
});
break;
case "draft-rescue":
startRescue(message.draft);
break;
case "rescue-query": {
const rescue = rescues.get(message.rescueKey);
if (rescue) void rescue.then((draftId) => channel?.post({ type: "rescue-answer", rescueKey: message.rescueKey, draftId }));
break;
}
case "main-ping":
if (!closing) channel?.post({ type: "main-pong", windowId, accountIds: shareableSessions().map((session) => session.accountId) });
break;
case "mail-changed":
refreshList();
break;
}
});
if (!channel) return;
const stopPush = subscribePushStateChanges((change) => {
if (changesAnyType(change, ["Email", "Mailbox"])) channel?.post({ type: "state-change" });
});
// This window's own changes reach no push stream on the way to a pop-out.
let listTimer: ReturnType<typeof setTimeout> | null = null;
const stopList = useEmailStore.subscribe((state, prev) => {
if (state.emails === prev.emails && state.selectedEmail === prev.selectedEmail) return;
if (listTimer) clearTimeout(listTimer);
listTimer = setTimeout(() => channel?.post({ type: "state-change" }), LIST_CHANGE_DEBOUNCE_MS);
});
const stopAccounts = useAccountStore.subscribe((state, prev) => {
if (state.accounts === prev.accounts) return;
const ids = new Set(state.accounts.map((account) => account.id));
for (const account of prev.accounts) {
if (!ids.has(account.id)) channel?.post({ type: "account-removed", accountId: account.id });
}
});
// Hearing a ping late in closing, this window must not answer: a draft
// handed to it now would be lost.
const onPageHide = () => {
closing = true;
channel?.post({ type: "main-gone", windowId });
};
const onPageShow = () => {
closing = false;
};
window.addEventListener("pagehide", onPageHide);
window.addEventListener("pageshow", onPageShow);
return () => {
window.removeEventListener("pagehide", onPageHide);
window.removeEventListener("pageshow", onPageShow);
stopPush();
stopList();
stopAccounts();
if (refreshTimer) clearTimeout(refreshTimer);
if (listTimer) clearTimeout(listTimer);
channel?.close();
};
}, [available]);
return null;
}
+211
View File
@@ -0,0 +1,211 @@
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
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 { useAuthStore } from "@/stores/auth-store";
import { useEmailStore } from "@/stores/email-store";
import { usePolicyStore } from "@/stores/policy-store";
import { toast } from "@/stores/toast-store";
import type { Email } from "@/lib/jmap/types";
import type { ProComposeTabData } from "@/stores/pro-tab-store";
import { localizeMailboxName } from "@/lib/mailbox-label";
import { announceMailChanged, openPopoutChannel } from "@/lib/popout/channel";
import { openComposerWindow } from "@/lib/popout/open";
import { closePopoutWindow } from "@/lib/popout/window-role";
import { PopoutNotice, PopoutShell, PopoutSkeleton } from "./popout-shell";
/** How often an open message checks that it is still there, without a main window to say so. */
const CHECK_INTERVAL_MS = 60_000;
/**
* The id from the address bar: a page the service worker kept for a start
* without the network was rendered for another id.
*/
function readLaunch(paramId: string): { emailId: string; accountId?: string; ownerAccountId?: string } {
if (typeof window === "undefined") return { emailId: paramId };
const segments = window.location.pathname.split("/").filter(Boolean);
const at = segments.lastIndexOf("message");
let emailId = paramId;
try {
if (at >= 0 && segments[at + 1]) emailId = decodeURIComponent(segments[at + 1]);
} catch {
// A malformed address: the route's own value.
}
const search = new URLSearchParams(window.location.search);
return { emailId, accountId: search.get("account") ?? undefined, ownerAccountId: search.get("owner") ?? undefined };
}
type Presence = "present" | "gone";
type LiveState = Pick<Email, "keywords" | "mailboxIds">;
/**
* Whether the message still exists, and in which folders. A JMAP move keeps
* the id, so moved mail stays readable here; only its folders change.
*/
function useMessagePresence(emailId: string, ownerAccountId: string | undefined): { presence: Presence; mailboxIds: string[] | null; liveState: LiveState | null } {
const client = useAuthStore((s) => s.client);
const [presence, setPresence] = useState<Presence>("present");
const [mailboxIds, setMailboxIds] = useState<string[] | null>(null);
const [liveState, setLiveState] = useState<LiveState | null>(null);
const checking = useRef(false);
useEffect(() => {
if (!client) return;
let cancelled = false;
const check = async () => {
if (checking.current) return;
checking.current = true;
try {
const [found] = await client.getSomeEmails([emailId], ownerAccountId);
if (cancelled) return;
setPresence(found ? "present" : "gone");
if (found?.mailboxIds) setMailboxIds(Object.keys(found.mailboxIds).sort());
if (found) {
setLiveState({ keywords: found.keywords, mailboxIds: found.mailboxIds });
// What the next star or read toggle starts from.
useEmailStore.setState((state) => ({
emails: state.emails.map((email) => (email.id === emailId ? { ...email, keywords: found.keywords, mailboxIds: found.mailboxIds } : email)),
}));
}
} catch {
// No answer says nothing about the message: it stays on screen.
} finally {
checking.current = false;
}
};
void check();
const channel = openPopoutChannel((message) => {
if (message.type === "state-change") void check();
});
const onFocus = () => void check();
window.addEventListener("focus", onFocus);
const timer = window.setInterval(() => {
if (document.visibilityState === "visible") void check();
}, CHECK_INTERVAL_MS);
return () => {
cancelled = true;
channel?.close();
window.removeEventListener("focus", onFocus);
window.clearInterval(timer);
};
}, [client, emailId, ownerAccountId]);
return { presence, mailboxIds, liveState };
}
function PopoutMessage({ emailId, accountId, ownerAccountId }: { emailId: string; accountId?: string; ownerAccountId?: string }) {
const t = useTranslations("pwaWindows");
const tSidebar = useTranslations("sidebar");
const login = useAuthStore((s) => accountId ?? s.activeAccountId ?? undefined);
const client = useAuthStore((s) => (login ? s.getClientForAccount(login) : undefined) ?? s.client);
const mailboxes = useEmailStore((s) => s.mailboxes);
const [subject, setSubject] = useState<string | null>(null);
const subjectInTitle = usePolicyStore((s) => s.loaded && s.isFeatureEnabled("tabTitleSubjectEnabled"));
useDocumentTitle(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.
const [foldersReady, setFoldersReady] = useState(mailboxes.length > 0);
useEffect(() => {
if (!client) return;
let cancelled = false;
void Promise.resolve(useEmailStore.getState().fetchMailboxes(client)).catch(() => {}).finally(() => {
if (!cancelled) setFoldersReady(true);
});
return () => {
cancelled = true;
};
// Once per client: an account without folders shouldn't ask forever.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [client]);
const { presence, mailboxIds, liveState } = useMessagePresence(emailId, ownerAccountId);
const firstMailboxIds = useRef<string | null>(null);
if (mailboxIds && firstMailboxIds.current === null) firstMailboxIds.current = mailboxIds.join();
const moved = !!mailboxIds && firstMailboxIds.current !== mailboxIds.join();
const movedTo = moved ? mailboxes.find((mailbox) => mailboxIds.includes(mailbox.originalId || mailbox.id)) : undefined;
const handleClose = useCallback(() => {
announceMailChanged(login ?? null);
closePopoutWindow();
}, [login]);
const handleMailChanged = useCallback(() => announceMailChanged(login ?? null), [login]);
const handleLoaded = useCallback((email: Email) => {
setSubject(email.subject || null);
// Delete, move, star and read look the message up in the list and do
// nothing when it isn't there, and this window has no list of its own.
useEmailStore.setState({ emails: [email], selectedMailbox: Object.keys(email.mailboxIds ?? {})[0] ?? "" });
}, []);
// Reply and forward open a composer window of their own.
const openCompose = useCallback(async (data: Omit<ProComposeTabData, "sessionId">) => {
const opened = openComposerWindow(login);
if (!opened) {
toast.error(t("popup_blocked"));
return false;
}
const shown = await opened.handOver({
mode: data.mode,
replyTo: data.replyTo,
initialDraftText: data.initialDraftText,
initialData: data.initialData,
prefill: data.prefill,
sourceEmailId: data.sourceEmailId,
sourceEmailSource: data.sourceEmailSource,
});
if (!shown) {
opened.cancel();
toast.error(t("window_not_ready"));
}
return shown;
}, [login, t]);
if (!foldersReady) return <PopoutSkeleton label={t("opening")} />;
if (presence === "gone") {
return (
<PopoutNotice title={t("message_gone_title")} body={t("message_gone_body")}>
<Button onClick={handleClose}>{t("close_window")}</Button>
</PopoutNotice>
);
}
return (
<>
{moved && (
<div role="status" data-popout-moved="" className="shrink-0 border-b border-border bg-muted px-4 py-2 text-sm text-foreground">
{movedTo
? t("message_moved_to", { folder: localizeMailboxName(movedTo.role, movedTo.name, (key) => tSidebar(`mailboxes.${key}`)) })
: t("message_moved")}
</div>
)}
<ProEmailView
emailId={emailId}
client={client ?? undefined}
clientAccountId={login}
accountId={ownerAccountId}
onLoaded={handleLoaded}
onClose={handleClose}
onOpenCompose={openCompose}
liveState={liveState}
onMailChanged={handleMailChanged}
className="min-h-0 w-full flex-1"
/>
</>
);
}
/** `/popout/message/<id>`: one message in its own window, with no rail, sidebar or list. */
export function PopoutMessageApp({ id }: { id: string }) {
const [launch] = useState(() => readLaunch(id));
return (
<PopoutShell kind="message" accountId={launch.accountId}>
<PopoutMessage emailId={launch.emailId} accountId={launch.accountId} ownerAccountId={launch.ownerAccountId} />
</PopoutShell>
);
}
+119
View File
@@ -0,0 +1,119 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
import { useConfig } from "@/hooks/use-config";
import { useAuthStore, SHARED_SESSION_ENDED_EVENT } from "@/stores/auth-store";
import { withBasePath } from "@/lib/browser-navigation";
import { flushComposers } from "@/lib/compose-flush-registry";
import { openPopoutChannel, requestWindowSession } from "@/lib/popout/channel";
import { closePopoutWindow } from "@/lib/popout/window-role";
import { onSignedOutElsewhere } from "@/lib/sign-out-cleanup";
/** How long a closing pop-out waits for its composer to save, when the account went away elsewhere. */
const CLOSE_FLUSH_MS = 3000;
/** How long it waits to hear that another window still holds the login. */
const STILL_HELD_MS = 800;
/** The session gate and page frame of a pop-out window. Takes the session from the main window (lib/popout). */
export function PopoutShell({ kind, accountId, children }: {
kind: "message" | "compose";
/** The login to open; left out, the main window's active one. */
accountId?: string;
children: React.ReactNode;
}) {
const t = useTranslations("pwaWindows");
// Fetches the organisation's policy, which device policies and send rules read.
useConfig();
const [status, setStatus] = useState<"loading" | "ready" | "no-session">("loading");
useEffect(() => {
let cancelled = false;
void useAuthStore.getState().startSharedSession({ accountId }).then((result) => {
if (!cancelled) setStatus(result);
});
return () => {
cancelled = true;
};
}, [accountId]);
// The session ended elsewhere: save what can be saved, and go. A composer
// whose text didn't make it stays, as the only place that text still is.
const endSession = useCallback(async () => {
const flushed = await flushComposers(CLOSE_FLUSH_MS);
if (kind === "compose" && (flushed.failed > 0 || flushed.timedOut)) setStatus("no-session");
else closePopoutWindow();
}, [kind]);
useEffect(() => {
const channel = openPopoutChannel((message) => {
const active = useAuthStore.getState().activeAccountId;
if (message.type !== "account-removed" || message.accountId !== active) return;
// One tab dropping a login it couldn't restore says nothing about the
// tab that is signed in with it.
void requestWindowSession({ accountId: active }, STILL_HELD_MS).then((held) => {
if (!held?.sessions.some((session) => session.accountId === active)) void endSession();
});
});
const stopSignOut = onSignedOutElsewhere(() => void endSession());
return () => {
channel?.close();
stopSignOut();
};
}, [endSession]);
// The session can't be renewed and no main window is left to do it. A
// message stops showing; a composer stays, its text still worth copying.
useEffect(() => {
const onEnded = () => setStatus("no-session");
window.addEventListener(SHARED_SESSION_ENDED_EVENT, onEnded);
return () => window.removeEventListener(SHARED_SESSION_ENDED_EVENT, onEnded);
}, []);
const actions = (
<>
<Button onClick={() => window.location.replace(withBasePath("/"))}>{t("open_app")}</Button>
<Button variant="ghost" onClick={closePopoutWindow}>{t("close_window")}</Button>
</>
);
return (
<div data-popout-window={kind} data-popout-status={status} className="flex h-dvh flex-col overflow-hidden bg-background pt-[var(--app-top-inset)]">
{status === "loading" && <PopoutSkeleton label={t("opening")} />}
{status === "no-session" && kind === "message" && (
<PopoutNotice title={t("session_ended_title")} body={t("session_ended_body")}>{actions}</PopoutNotice>
)}
{status === "no-session" && kind === "compose" && (
<div role="alert" data-popout-session-ended="" className="flex shrink-0 flex-wrap items-center gap-2 border-b border-border bg-muted px-4 py-2 text-sm text-foreground">
<span className="min-w-0 flex-1">{t("session_ended_title")}. {t("session_ended_body")}</span>
{actions}
</div>
)}
{/* One place in the tree, so a composer stays mounted, text and all, when the session ends. */}
{(status === "ready" || (status === "no-session" && kind === "compose")) && children}
</div>
);
}
export function PopoutSkeleton({ label }: { label: string }) {
return (
<div role="status" aria-label={label} className="flex flex-1 flex-col gap-4 p-6" data-popout-skeleton="">
<div className="h-6 w-2/3 rounded bg-muted" />
<div className="h-4 w-1/3 rounded bg-muted" />
<div className="mt-4 h-4 w-full rounded bg-muted" />
<div className="h-4 w-5/6 rounded bg-muted" />
<div className="h-4 w-4/6 rounded bg-muted" />
</div>
);
}
export function PopoutNotice({ title, body, children }: { title: string; body: string; children?: React.ReactNode }) {
return (
<div className="flex flex-1 flex-col items-center justify-center gap-3 p-6 text-center" data-popout-notice="">
<h1 className="text-lg font-semibold text-foreground">{title}</h1>
<p className="max-w-md text-sm text-muted-foreground">{body}</p>
{children && <div className="mt-2 flex items-center gap-2">{children}</div>}
</div>
);
}
+10
View File
@@ -0,0 +1,10 @@
"use client";
import { useEffect } from "react";
import { startWindowSync } from "@/lib/desktop/window-sync";
/** See lib/desktop/window-sync.ts. */
export function WindowSyncHost() {
useEffect(() => startWindowSync(), []);
return null;
}
@@ -136,6 +136,36 @@ describe('Pro email view - editing a draft', () => {
expect(initialData).toMatchObject({ draftId: 'eaaaaab', draftAccountId: 'c' });
});
describe('in a window of its own', () => {
async function editIn({ onOpenCompose, onClose }: { onOpenCompose: () => Promise<boolean>; onClose: () => void }) {
const client = { getEmail: vi.fn().mockResolvedValue(DRAFT), getUsername: () => 'userb@example.org', getAccountId: () => 'e' };
render(<ProEmailView emailId="d1" client={client as never} onOpenCompose={onOpenCompose} onClose={onClose} />);
await waitFor(() => expect(viewerProps.current?.email).toBeTruthy());
(viewerProps.current!.onEditDraft as () => void)();
}
it('leaves the message window only once the draft is on screen in the other, or it would take the draft with it', async () => {
let show: (shown: boolean) => void = () => {};
const onClose = vi.fn();
const onOpenCompose = vi.fn(() => new Promise<boolean>((resolve) => { show = resolve; }));
await editIn({ onOpenCompose, onClose });
await waitFor(() => expect(onOpenCompose).toHaveBeenCalledTimes(1));
expect(onClose).not.toHaveBeenCalled();
show(true);
await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1));
});
it('stays when the draft did not make it', async () => {
const onClose = vi.fn();
const onOpenCompose = vi.fn(async () => false);
await editIn({ onOpenCompose, onClose });
await waitFor(() => expect(onOpenCompose).toHaveBeenCalledTimes(1));
await new Promise((resolve) => setTimeout(resolve, 5));
expect(onClose).not.toHaveBeenCalled();
expect(openComposeTab).not.toHaveBeenCalled();
});
});
it('opens an own draft without an account, as before', async () => {
const initialData = await openAndEdit(undefined);
+21
View File
@@ -15,6 +15,8 @@ import { threadKeyFor } from "@/lib/thread-utils";
import { formatRejectedRecipients } from "@/lib/jmap/client";
import { announceSent } from "@/lib/plugin-after-send";
import { composerSendOptions } from "@/lib/outgoing/composer-send-options";
import { usePopoutsAvailable } from "@/hooks/use-popouts-available";
import { openComposerWindow } from "@/lib/popout/open";
interface ProComposeTabBodyProps {
tabId: string;
@@ -212,6 +214,8 @@ export function ProComposeTabBody({ tabId, data }: ProComposeTabBodyProps) {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const popoutsOn = usePopoutsAvailable();
// Mirrors the standard shell (see the same prop in `components/mail/mail-app.tsx`).
// Without it `mode === 'compose'` resolves `findComposeIdentityId(identities,
// undefined)` -> null and every new message in the Pro shell defaults to the
@@ -234,6 +238,22 @@ export function ProComposeTabBody({ tabId, data }: ProComposeTabBodyProps) {
);
});
const popOut = useCallback(() => {
const target = openComposerWindow(useAuthStore.getState().activeAccountId);
if (!target) return null;
return {
cancel: target.cancel,
handOver: (state: ComposerDraftData) => target.handOver({
mode: state.mode,
replyTo: state.replyTo,
initialData: state,
sourceEmailId: data.sourceEmailId,
sourceEmailSource: data.sourceEmailSource,
composeFromAccountEmail,
}),
};
}, [composeFromAccountEmail, data.sourceEmailId, data.sourceEmailSource]);
return (
<div className="flex h-full w-full flex-col bg-background">
<ErrorBoundary fallback={ComposerErrorFallback}>
@@ -254,6 +274,7 @@ export function ProComposeTabBody({ tabId, data }: ProComposeTabBodyProps) {
requestCloseRef={requestCloseRef}
onDiscardDraft={handleDiscardDraft}
onSaveState={handleSaveState}
popOut={popoutsOn ? popOut : undefined}
className="flex-1"
/>
</ErrorBoundary>
+33 -4
View File
@@ -32,6 +32,7 @@ import { takeTabReply, useNotificationTabReply } from '@/lib/pwa-notify/tab-repl
import { ConfirmDialog } from '@/components/ui/confirm-dialog';
import { saveQuickReplyDraft } from '@/lib/outgoing/quick-reply-envelope';
import { canDownload } from '@/lib/device-policy';
import { useOpenEmailInWindow } from '@/hooks/use-popouts-available';
import { isFilePreviewable } from '@/lib/file-preview';
import dynamic from 'next/dynamic';
@@ -66,6 +67,16 @@ interface ProEmailViewProps {
accountId?: string;
/** Fires once the full message is loaded (tab retitling, sidebar highlight). */
onLoaded?: (email: Email) => void;
/**
* Opens a reply, forward or draft somewhere else than a Pro tab: a pop-out
* window (components/popout) has no tabs. Resolves true once it is on screen
* there: a draft leaves this view only then.
*/
onOpenCompose?: (data: Omit<ProComposeTabData, 'sessionId'>) => Promise<boolean>;
/** Flags and folders as the server has them now, when the host tracks them (a pop-out). */
liveState?: Pick<Email, 'keywords' | 'mailboxIds'> | null;
/** This view changed the message's flags, for a host other windows should hear from. */
onMailChanged?: () => void;
/**
* The message left this view: deleted, archived, moved, or reopened in the
* composer. The host decides what that means (close the tab / clear the
@@ -121,7 +132,7 @@ function buildReplyContext(email: Email): ProReplyContext {
* Hosted by `ProEmailTabBody` (a dedicated email tab) and by the folder tab's
* reading pane.
*/
export function ProEmailView({ emailId, client: clientOverride, clientAccountId, accountId, onLoaded, onClose, className }: ProEmailViewProps) {
export function ProEmailView({ emailId, client: clientOverride, clientAccountId, accountId, onLoaded, onOpenCompose, liveState, onMailChanged, onClose, className }: ProEmailViewProps) {
const t = useTranslations();
const tNotifications = useTranslations('notifications');
const tRemove = useTranslations('email_list.confirm_remove');
@@ -176,6 +187,12 @@ export function ProEmailView({ emailId, client: clientOverride, clientAccountId,
onOpened?: () => void,
) => {
const open = (prefill: ComposePrefill | null) => {
if (onOpenCompose) {
void onOpenCompose({ ...data, prefill }).then((shown) => {
if (shown) onOpened?.();
});
return;
}
composerSessionIdRef.current += 1;
openComposeTabNow({ ...data, sessionId: composerSessionIdRef.current, prefill });
onOpened?.();
@@ -192,7 +209,7 @@ export function ProEmailView({ emailId, client: clientOverride, clientAccountId,
})).then((prefill) => {
if (prefill) open(Object.keys(prefill).length > 0 ? prefill : null);
});
}, [identities, openComposeTabNow, t]);
}, [identities, onOpenCompose, openComposeTabNow, t]);
// Held in a ref so a host passing an inline callback doesn't refetch the
// message on every render.
@@ -243,6 +260,13 @@ export function ProEmailView({ emailId, client: clientOverride, clientAccountId,
};
}, [client, clientOverride, clientAccountId, emailId, accountId, fetchEmailContent]);
useEffect(() => {
if (!liveState) return;
setEmail((prev) => (prev && prev.id === emailId
? { ...prev, keywords: liveState.keywords ?? prev.keywords, mailboxIds: liveState.mailboxIds ?? prev.mailboxIds }
: prev));
}, [liveState, emailId]);
const currentMailboxRole = useMemo(() => {
if (!email) return undefined;
const mb = email.mailboxIds
@@ -368,6 +392,7 @@ export function ProEmailView({ emailId, client: clientOverride, clientAccountId,
if (!client || !email) return;
try {
if (!(await toggleStar(client, email.id, emailKeyFor(email)))) return;
onMailChanged?.();
// Reflect locally - the viewer re-reads from email-store's selectedEmail
// shape only for the mail tab; here we update our local copy too.
setEmail((prev) => prev ? {
@@ -381,12 +406,13 @@ export function ProEmailView({ emailId, client: clientOverride, clientAccountId,
console.error('Toggle star failed:', err);
toast.error(tNotifications('error_updating'));
}
}, [client, email, toggleStar, tNotifications]);
}, [client, email, toggleStar, tNotifications, onMailChanged]);
const handleMarkAsRead = useCallback(async (emailIdToMark: string, read: boolean, opts?: { automatic?: boolean }) => {
if (!client) return;
try {
if (!(await markAsRead(client, emailIdToMark, read))) return;
onMailChanged?.();
setEmail((prev) => prev && prev.id === emailIdToMark ? {
...prev,
keywords: { ...prev.keywords, $seen: read },
@@ -396,7 +422,7 @@ export function ProEmailView({ emailId, client: clientOverride, clientAccountId,
// A refused mark-as-read on opening needs no notice (see EmailViewer).
if (!opts?.automatic) toast.error(tNotifications('error_updating'));
}
}, [client, markAsRead, tNotifications]);
}, [client, markAsRead, tNotifications, onMailChanged]);
const handleSetTag = useCallback((emailIdToTag: string, tagId: string | null) => {
if (!email || email.id !== emailIdToTag) return;
@@ -457,6 +483,8 @@ export function ProEmailView({ emailId, client: clientOverride, clientAccountId,
return { blob, contentType: preview.type || blob.type };
}, [preview]);
const openInWindow = useOpenEmailInWindow();
const handleQuickReply = useCallback(async (body: string) => {
handleReply(body);
}, [handleReply]);
@@ -534,6 +562,7 @@ export function ProEmailView({ emailId, client: clientOverride, clientAccountId,
onMarkAsRead={handleMarkAsRead}
onSetTag={handleSetTag}
onDownloadAttachment={handleDownloadAttachment}
onOpenInWindow={openInWindow && email ? () => openInWindow(email) : undefined}
onQuickReply={handleQuickReply}
onSaveQuickReplyDraft={handleSaveQuickReplyDraft}
onEditDraft={handleEditDraft}
+1 -1
View File
@@ -76,7 +76,7 @@ export function ProInterfaceRedirect() {
if (!takingOver) return null;
return (
<div className="fixed inset-0 z-50" data-pro-takeover="">
<div className="fixed inset-0 z-50 pt-[var(--titlebar-inset)]" data-pro-takeover="">
<ProSkeleton label={label} />
</div>
);
@@ -1,5 +1,6 @@
"use client";
import { isStandaloneDisplayMode } from "@/lib/standalone-display";
import { useEffect } from "react";
import { MailSkeleton } from "@/components/boot-skeleton/mail-skeleton";
import type { RailLabels } from "@/components/boot-skeleton/shell";
@@ -7,7 +8,6 @@ import { parseMailto } from "@/lib/protocol-handlers/mailto";
import { requestOpenMailtoInExistingClient, savePendingMailto } from "@/lib/protocol-handlers/session";
import { useSettingsStore } from "@/stores/settings-store";
type StandaloneNavigator = Navigator & { standalone?: boolean };
function getProtocolPathPrefix(): string {
const marker = "/protocol/mailto";
@@ -34,9 +34,7 @@ function openFallbackAppTab(raw: string): boolean {
}
function shouldOpenFallbackAppTab(): boolean {
const standalone = window.matchMedia?.("(display-mode: standalone)").matches
|| (navigator as StandaloneNavigator).standalone === true;
return !standalone && window.history.length > 1;
return !isStandaloneDisplayMode() && window.history.length > 1;
}
async function focusExistingClient() {
@@ -8,6 +8,8 @@ import { ConfirmDialog } from "@/components/ui/confirm-dialog";
import { useConfig } from "@/hooks/use-config";
import { useConfirmDialog } from "@/hooks/use-confirm-dialog";
import { flushComposers } from "@/lib/compose-flush-registry";
import { isPopoutPath } from "@/lib/popout/window-role";
import { isStandaloneDisplayMode } from "@/lib/standalone-display";
import { getPathPrefix } from "@/lib/browser-navigation";
import { matchSurface, type AppSurface } from "@/lib/deep-links";
import {
@@ -45,7 +47,6 @@ type LaunchParams = {
targetURL?: string;
files?: ReadonlyArray<{ kind?: string; getFile?: () => Promise<File> }>;
};
type StandaloneNavigator = Navigator & { standalone?: boolean };
declare global {
interface Window {
@@ -91,11 +92,6 @@ const OFFER_FILE_COUNT = 5;
type ShareOffer = { subject: string; body: string; files: string[] };
function isStandaloneDisplayMode() {
return window.matchMedia?.("(display-mode: standalone)").matches
|| (navigator as StandaloneNavigator).standalone === true;
}
function openProtocolInNewTab(protocol: "mailto" | "webcal", raw: string): boolean {
const url = `${getPathPrefix()}/protocol/${protocol}?url=${encodeURIComponent(raw)}&fallback=1`;
const opened = window.open(url, "_blank");
@@ -206,7 +202,7 @@ export function ProtocolLaunchHandlerProvider({ children }: ProtocolLaunchHandle
}, [pathname, leaveFor]);
useEffect(() => {
if (pathname.startsWith("/protocol/")) return;
if (pathname.startsWith("/protocol/") || isPopoutPath(pathname)) return;
return listenForMailtoRequests((pending) => {
savePendingMailto(pending);
@@ -221,7 +217,7 @@ export function ProtocolLaunchHandlerProvider({ children }: ProtocolLaunchHandle
}, [pathname, router, t, appName]);
useEffect(() => {
if (typeof window === "undefined" || !window.launchQueue) return;
if (typeof window === "undefined" || !window.launchQueue || isPopoutPath(pathname)) return;
window.launchQueue.setConsumer((launchParams) => {
if (launchParams.files && launchParams.files.length > 0) {
@@ -1,5 +1,6 @@
"use client";
import { isStandaloneDisplayMode } from "@/lib/standalone-display";
import { useEffect } from "react";
import { parseWebcal } from "@/lib/protocol-handlers/webcal";
import { savePendingWebcal } from "@/lib/protocol-handlers/session";
@@ -7,7 +8,6 @@ import { useSettingsStore } from "@/stores/settings-store";
import { CalendarSkeleton, type CalendarSkeletonText } from "@/components/boot-skeleton/calendar-skeleton";
import type { RailLabels } from "@/components/boot-skeleton/shell";
type StandaloneNavigator = Navigator & { standalone?: boolean };
function getProtocolPathPrefix(): string {
const marker = "/protocol/webcal";
@@ -34,9 +34,7 @@ function openFallbackAppTab(raw: string): boolean {
}
function shouldOpenFallbackAppTab(): boolean {
const standalone = window.matchMedia?.("(display-mode: standalone)").matches
|| (navigator as StandaloneNavigator).standalone === true;
return !standalone && window.history.length > 1;
return !isStandaloneDisplayMode() && window.history.length > 1;
}
interface WebcalProtocolClientProps {
@@ -1,6 +1,7 @@
'use client';
import { useState, useEffect, useMemo, useCallback, useId, useRef } from 'react';
import { IS_DESKTOP_BUILD } from '@/lib/desktop/flag';
import { useParams } from 'next/navigation';
import { useTranslations } from 'next-intl';
import QRCode from 'qrcode';
@@ -1569,8 +1570,12 @@ export function AccountSecuritySettings() {
<SettingsSection id="devices" title={t('title')} description={t('description')}>
{!IS_LITE ? (
<div className="space-y-6">
<LinkDeviceSection />
<div className="border-t border-border" />
{!IS_DESKTOP_BUILD && (
<>
<LinkDeviceSection />
<div className="border-t border-border" />
</>
)}
<div className="text-sm text-muted-foreground" dangerouslySetInnerHTML={{ __html: sanitizeI18nHtml(t.raw('not_available')) }} />
</div>
) : (
@@ -1610,7 +1615,7 @@ export function AccountSecuritySettings() {
description={withoutPassword ? t('description') : t('sections.devices_description')}
>
<div className="space-y-6">
{!IS_LITE && (
{!IS_LITE && !IS_DESKTOP_BUILD && (
<>
<LinkDeviceSection />
<div className="border-t border-border" />
+3 -3
View File
@@ -910,7 +910,7 @@ export function SettingsApp({ linkSegments: routeSegments }: SettingsAppProps =
if (!isDesktop) {
if (mobileShowContent) {
return (
<div className={cn("flex flex-col bg-background pt-[env(safe-area-inset-top)]", isEmbedded ? "h-full" : "h-dvh")}>
<div className={cn("flex flex-col bg-background pt-[var(--app-top-inset)]", isEmbedded ? "h-full" : "h-dvh")}>
<AppTopBannerSlot />
<div className="flex items-center gap-2 px-4 h-14 border-b border-border bg-background shrink-0">
<IconButton label={t('back_to_settings')} size="icon-lg" onClick={() => window.history.back()}>
@@ -939,7 +939,7 @@ export function SettingsApp({ linkSegments: routeSegments }: SettingsAppProps =
}
return (
<div className={cn("flex flex-col bg-background pt-[env(safe-area-inset-top)]", isEmbedded ? "h-full" : "h-dvh")}>
<div className={cn("flex flex-col bg-background pt-[var(--app-top-inset)]", isEmbedded ? "h-full" : "h-dvh")}>
<AppTopBannerSlot />
<div className="flex items-center gap-2 px-4 h-14 border-b border-border bg-background shrink-0">
<IconButton label={t('back_to_mail')} size="icon-lg" onClick={() => router.push('/')}>
@@ -1057,7 +1057,7 @@ export function SettingsApp({ linkSegments: routeSegments }: SettingsAppProps =
</AppMain>
);
return (
<div className={cn("flex flex-col pt-[env(safe-area-inset-top)]", mvShell ? "bg-[var(--mv-canvas)]" : "bg-background", isEmbedded ? "h-full" : "h-dvh")}>
<div className={cn("flex flex-col pt-[var(--app-top-inset)]", mvShell ? "bg-[var(--mv-canvas)]" : "bg-background", isEmbedded ? "h-full" : "h-dvh")}>
{!isEmbedded && <SkipLink>{tShell("skip_to_content")}</SkipLink>}
<AppTopBannerSlot />
{mvShell && (
+2 -2
View File
@@ -155,8 +155,8 @@ export function Dialog({
return createPortal(
<div
className={cn(
"fixed inset-0 bg-black/50 backdrop-blur-[1px] flex items-center justify-center z-[60] p-4 animate-in fade-in duration-150",
size === "full-on-phone" && "max-sm:p-0"
"fixed inset-0 bg-black/50 backdrop-blur-[1px] flex items-center justify-center z-[60] p-4 pt-[calc(1rem+var(--titlebar-inset))] animate-in fade-in duration-150",
size === "full-on-phone" && "max-sm:p-0 max-sm:pt-[var(--titlebar-inset)]"
)}
onMouseDown={(e) => {
pressedOnBackdrop.current = e.target === e.currentTarget;