Merge branch 'feat/desktop-offline' into feat/do-native-dialogs

# Conflicts:
#	components/email/email-composer.tsx
This commit is contained in:
Linus Rath
2026-11-04 18:20:54 +01:00
61 changed files with 2664 additions and 459 deletions
@@ -866,3 +866,56 @@ describe('CalendarApp company calendars on a phone', () => {
}
});
});
// Below the full desktop the sidebar is the same drawer as Mail's folders
// (usability test 2026-11-04): from the window's edge, the page dimmed,
// Escape closes it, and the focus goes in and back to the menu button.
describe('CalendarApp sidebar drawer', () => {
beforeEach(() => {
media.desktop = false;
});
const drawer = () => screen.getByTestId('calendar-sidebar-drawer');
const menu = () => screen.getByRole('button', { name: 'nav_open_menu' });
it("opens from the window's edge, over the app rail and under the top bar", () => {
renderApp();
const classes = drawer().className.split(/\s+/);
expect(classes).toEqual(expect.arrayContaining(['fixed', 'start-0', 'top-[var(--drawer-top)]', 'bottom-0']));
expect(classes).not.toContain('absolute');
});
it("is out of reach while closed, so Tab doesn't walk into the hidden calendars", () => {
renderApp();
expect(drawer()).toHaveAttribute('inert');
fireEvent.click(menu());
expect(drawer()).not.toHaveAttribute('inert');
});
it('takes the focus in, keeps Tab there and gives it back to the menu button on Escape', () => {
renderApp();
menu().focus();
fireEvent.click(menu());
expect(drawer().contains(document.activeElement)).toBe(true);
const stops = Array.from(drawer().querySelectorAll<HTMLElement>('button:not(:disabled)'));
stops.at(-1)!.focus();
fireEvent.keyDown(stops.at(-1)!, { key: 'Tab' });
expect(document.activeElement).toBe(stops[0]);
fireEvent.keyDown(document.activeElement!, { key: 'Escape' });
expect(drawer()).toHaveAttribute('inert');
expect(document.activeElement).toBe(menu());
});
it('closes on a click on the dimmed window and gives the focus back to the menu button', () => {
renderApp();
menu().focus();
fireEvent.click(menu());
const scrim = screen.getByTestId('drawer-scrim');
expect(scrim.className.split(/\s+/)).toEqual(expect.arrayContaining(['fixed', 'inset-0']));
(document.activeElement as HTMLElement).blur();
fireEvent.click(scrim);
expect(drawer()).toHaveAttribute('inert');
expect(document.activeElement).toBe(menu());
});
});
+125 -121
View File
@@ -60,6 +60,7 @@ import { useIsFocusedProTab, useIsPaneScoped } from "@/hooks/use-pane-context";
import { useProMultiAccountCalendars } from "@/hooks/use-pro-multi-account-calendars";
import { useEventUserEmails } from "@/hooks/use-event-user-emails";
import { ResizeHandle } from "@/components/layout/resize-handle";
import { EdgeDrawer } from "@/components/layout/edge-drawer";
import { descriptionWithNote } from "@/lib/calendar-description";
import { filterTasksByCalendars } from "@/lib/calendar-tasks";
import { baseEventStoreId, isServerRecurrenceInstance } from "@/lib/recurrence-instances";
@@ -183,6 +184,7 @@ export function CalendarApp({ linkSegments: routeSegments }: CalendarAppProps =
// collapses into a burger-toggled overlay instead of taking inline space.
const isNarrow = !isFullDesktop;
const [narrowSidebarOpen, setNarrowSidebarOpen] = useState(false);
const closeNarrowSidebar = useCallback(() => setNarrowSidebarOpen(false), []);
useEffect(() => { if (!isNarrow) setNarrowSidebarOpen(false); }, [isNarrow]);
const { showAppsModal, inlineApp, loadedApps, handleManageApps, handleInlineApp, closeInlineApp, closeAppsModal } = useSidebarApps();
const { client, isAuthenticated, logout, checkAuth, switchAccount, activeAccountId, isLoading: authLoading } = useAuthStore();
@@ -2218,6 +2220,97 @@ export function CalendarApp({ linkSegments: routeSegments }: CalendarAppProps =
/>
);
// The sidebar's content: beside the views on the full desktop, a drawer below it.
const calendarSidebar = (
<>
<CalendarSidebarHeader
onCreateEvent={() => { setNarrowSidebarOpen(false); openCreateForView(); }}
createLabel={createLabel}
tourTarget={!isNarrow}
/>
<div className="flex-1 overflow-y-auto overflow-x-hidden py-3">
<div className="px-3">
<MiniCalendar
selectedDate={selectedDate}
displayMonth={miniMonth}
onSelectDate={handleMiniCalendarSelect}
onChangeMonth={handleMiniMonthChange}
events={events}
firstDayOfWeek={firstDayOfWeek}
showWeekNumbers={showWeekNumbers}
/>
</div>
<CalendarSidebarPanel
calendars={allCalendars}
selectedCalendarIds={shownCalendarIds}
onToggleVisibility={toggleShownCalendar}
onColorChange={client ? (calendarId, color) => {
if (calendarId === BIRTHDAY_CALENDAR_ID) {
updateSetting('birthdayCalendarColor', color);
return;
}
// Shared calendars: recolor locally only (the viewer usually
// can't write the owner's calendar, and it'd recolor it for
// everyone). Personal calendars write through to the server.
const cal = allCalendars.find((c) => c.id === calendarId);
if (cal?.isShared) {
setSharedCalendarColor(sharedCalendarColorKey(cal), color);
return;
}
updateCalendar(client, calendarId, { color });
} : undefined}
onResetColor={(cal) => {
// Drop the local override. A calendar with a server color goes
// back to it; one without gets a fresh unused color from the
// auto-assign effect (so it never reverts to a collision).
removeSharedCalendarColor(sharedCalendarColorKey(cal));
}}
onShareCalendar={client ? (cal) => setSharingCalendarId(cal.id) : undefined}
onCreateEvent={(cal: Calendar) => {
setDefaultCalendarIdForCreate(cal.id);
openCreateModal();
}}
onClearCalendar={client ? async (cal: Calendar) => {
const ok = await confirmAction({
title: tMgmt("clear_events"),
message: tMgmt("confirm_clear", { name: shownName.calendar(cal) }),
variant: "destructive",
confirmText: tMgmt("clear_events"),
});
if (!ok) return;
try {
const count = await clearCalendarEvents(client, cal.id);
toast.success(tMgmt("events_cleared", { count }));
} catch (err) {
// The store rethrows the server's reason (#434).
toast.error(err instanceof Error && err.message ? err.message : tMgmt("error_clear"));
}
} : undefined}
onDeleteCalendar={client ? async (cal: Calendar) => {
const ok = await confirmAction({
title: tMgmt("delete"),
message: tMgmt("confirm_delete", { name: shownName.calendar(cal) }),
variant: "destructive",
confirmText: tMgmt("delete"),
});
if (!ok) return;
try {
await removeCalendar(client, cal.id);
toast.success(tMgmt("calendar_deleted"));
} catch {
toast.error(tMgmt("error_delete"));
}
} : undefined}
onCreateCalendar={client ? () => setShowCreateCalendar(true) : undefined}
onSubscribe={canSubscribe ? () => setShowSubscriptionModal(true) : undefined}
onEditSubscription={(subId) => setEditingSubscription(subId)}
client={client}
multiAccountMode={multiAccountEnabled && accountClients.length > 1}
/>
</div>
</>
);
return (
<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>}
@@ -2253,138 +2346,49 @@ export function CalendarApp({ linkSegments: routeSegments }: CalendarAppProps =
<InlineAppView apps={loadedApps} activeAppId={inlineApp!.id} onClose={closeInlineApp} className="flex-1" />
)}
{/* Narrow-pane backdrop: dim and close overlay sidebar */}
{isNarrow && narrowSidebarOpen && !inlineApp && (
<div
className={cn(
"inset-0 bg-black/50 z-40",
isEmbedded ? "absolute" : "fixed"
)}
onClick={() => setNarrowSidebarOpen(false)}
/>
)}
{!inlineApp && (
<div className="flex flex-col flex-1 min-w-0 min-h-0">
<div className="flex flex-1 min-w-0 min-h-0">
{/* Sidebar - in-flow when desktop pane, overlay when narrow */}
{(isNarrow || !sidebarCollapsed) && (
{/* The sidebar: in flow on the full desktop; below it a drawer from
the window's edge, over the app rail, as Mail's folders. */}
{isNarrow && (
<EdgeDrawer
open={narrowSidebarOpen}
onClose={closeNarrowSidebar}
contained={isEmbedded || mvShell}
// A closed drawer is off-screen: not a pane for F6.
data-pane={narrowSidebarOpen ? "sidebar" : undefined}
data-testid="calendar-sidebar-drawer"
className="border-e border-border bg-secondary overflow-hidden"
>
{calendarSidebar}
</EdgeDrawer>
)}
{!isNarrow && !sidebarCollapsed && (
<>
<div
// A closed drawer is off-screen: not a pane for F6.
data-pane={!isNarrow || narrowSidebarOpen ? "sidebar" : undefined}
data-pane="sidebar"
className={cn(
"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-[var(--app-top-inset)]",
"transform transition-transform duration-300 ease-in-out",
!narrowSidebarOpen && "-translate-x-full rtl:translate-x-full"
)
)}
style={isNarrow ? undefined : { width: `${calSidebarWidth}px` }}
style={{ width: `${calSidebarWidth}px` }}
>
<CalendarSidebarHeader
onCreateEvent={() => { setNarrowSidebarOpen(false); openCreateForView(); }}
createLabel={createLabel}
tourTarget={!isNarrow}
/>
<div className="flex-1 overflow-y-auto overflow-x-hidden py-3">
<div className="px-3">
<MiniCalendar
selectedDate={selectedDate}
displayMonth={miniMonth}
onSelectDate={handleMiniCalendarSelect}
onChangeMonth={handleMiniMonthChange}
events={events}
firstDayOfWeek={firstDayOfWeek}
showWeekNumbers={showWeekNumbers}
/>
</div>
<CalendarSidebarPanel
calendars={allCalendars}
selectedCalendarIds={shownCalendarIds}
onToggleVisibility={toggleShownCalendar}
onColorChange={client ? (calendarId, color) => {
if (calendarId === BIRTHDAY_CALENDAR_ID) {
updateSetting('birthdayCalendarColor', color);
return;
}
// Shared calendars: recolor locally only (the viewer usually
// can't write the owner's calendar, and it'd recolor it for
// everyone). Personal calendars write through to the server.
const cal = allCalendars.find((c) => c.id === calendarId);
if (cal?.isShared) {
setSharedCalendarColor(sharedCalendarColorKey(cal), color);
return;
}
updateCalendar(client, calendarId, { color });
} : undefined}
onResetColor={(cal) => {
// Drop the local override. A calendar with a server color goes
// back to it; one without gets a fresh unused color from the
// auto-assign effect (so it never reverts to a collision).
removeSharedCalendarColor(sharedCalendarColorKey(cal));
}}
onShareCalendar={client ? (cal) => setSharingCalendarId(cal.id) : undefined}
onCreateEvent={(cal: Calendar) => {
setDefaultCalendarIdForCreate(cal.id);
openCreateModal();
}}
onClearCalendar={client ? async (cal: Calendar) => {
const ok = await confirmAction({
title: tMgmt("clear_events"),
message: tMgmt("confirm_clear", { name: shownName.calendar(cal) }),
variant: "destructive",
confirmText: tMgmt("clear_events"),
});
if (!ok) return;
try {
const count = await clearCalendarEvents(client, cal.id);
toast.success(tMgmt("events_cleared", { count }));
} catch (err) {
// The store rethrows the server's reason (#434).
toast.error(err instanceof Error && err.message ? err.message : tMgmt("error_clear"));
}
} : undefined}
onDeleteCalendar={client ? async (cal: Calendar) => {
const ok = await confirmAction({
title: tMgmt("delete"),
message: tMgmt("confirm_delete", { name: shownName.calendar(cal) }),
variant: "destructive",
confirmText: tMgmt("delete"),
});
if (!ok) return;
try {
await removeCalendar(client, cal.id);
toast.success(tMgmt("calendar_deleted"));
} catch {
toast.error(tMgmt("error_delete"));
}
} : undefined}
onCreateCalendar={client ? () => setShowCreateCalendar(true) : undefined}
onSubscribe={canSubscribe ? () => setShowSubscriptionModal(true) : undefined}
onEditSubscription={(subId) => setEditingSubscription(subId)}
client={client}
multiAccountMode={multiAccountEnabled && accountClients.length > 1}
/>
</div>
{calendarSidebar}
</div>
{!isNarrow && (
<ResizeHandle
pane="sidebar"
value={calSidebarWidth}
min={180}
max={400}
onResizeStart={() => { dragStartWidth.current = calSidebarWidth; setIsResizing(true); }}
onResize={(delta) => setCalSidebarWidth(Math.max(180, Math.min(400, dragStartWidth.current + delta)))}
onResizeEnd={() => {
setIsResizing(false);
localStorage.setItem("calendar-sidebar-width", String(calSidebarWidth));
}}
onDoubleClick={() => { setCalSidebarWidth(256); localStorage.setItem("calendar-sidebar-width", "256"); }}
/>
)}
<ResizeHandle
pane="sidebar"
value={calSidebarWidth}
min={180}
max={400}
onResizeStart={() => { dragStartWidth.current = calSidebarWidth; setIsResizing(true); }}
onResize={(delta) => setCalSidebarWidth(Math.max(180, Math.min(400, dragStartWidth.current + delta)))}
onResizeEnd={() => {
setIsResizing(false);
localStorage.setItem("calendar-sidebar-width", String(calSidebarWidth));
}}
onDoubleClick={() => { setCalSidebarWidth(256); localStorage.setItem("calendar-sidebar-width", "256"); }}
/>
</>
)}
@@ -102,6 +102,48 @@ describe('ContactsApp', () => {
expect(within(drawer()).getByText('tabs.all')).toBeInTheDocument();
});
// The same drawer as Mail's folders (usability test 2026-11-04): it opened
// beside the app rail, ignored Escape and left the focus on the page.
it("opens the drawer from the window's edge, over the app rail and under the top bar", () => {
renderContacts();
const classes = drawer().className.split(/\s+/);
expect(classes).toEqual(expect.arrayContaining(['fixed', 'start-0', 'top-[var(--drawer-top)]', 'bottom-0']));
expect(classes).not.toContain('absolute');
});
it('takes the focus into the drawer, keeps Tab there and gives it back to the menu button on Escape', () => {
renderContacts();
const menu = screen.getAllByRole('button', { name: 'open_categories' })[0];
menu.focus();
fireEvent.click(menu);
// The category on screen.
const current = within(drawer()).getByRole('button', { name: /tabs\.all/ });
expect(document.activeElement).toBe(current);
const stops = Array.from(drawer().querySelectorAll<HTMLElement>('button:not(:disabled)'));
stops.at(-1)!.focus();
fireEvent.keyDown(stops.at(-1)!, { key: 'Tab' });
expect(document.activeElement).toBe(stops[0]);
fireEvent.keyDown(document.activeElement!, { key: 'Escape' });
expect(drawer()).toHaveAttribute('inert');
expect(document.activeElement).toBe(menu);
});
it('dims the whole window behind the drawer and closes it on a click there, back to the menu button', () => {
renderContacts();
const menu = screen.getAllByRole('button', { name: 'open_categories' })[0];
menu.focus();
fireEvent.click(menu);
const scrim = screen.getByTestId('drawer-scrim');
expect(scrim.className.split(/\s+/)).toEqual(expect.arrayContaining(['fixed', 'inset-0']));
// A press on the scrim drops the focus to the page.
(document.activeElement as HTMLElement).blur();
fireEvent.click(scrim);
expect(drawer()).toHaveAttribute('inert');
expect(screen.queryByTestId('drawer-scrim')).toBeNull();
expect(document.activeElement).toBe(menu);
});
it("closes the drawer when something in it is picked, so it doesn't stay over the form", () => {
renderContacts();
fireEvent.click(screen.getAllByRole('button', { name: 'open_categories' })[0]);
+97 -97
View File
@@ -49,6 +49,7 @@ import { useIsEmbedded } from "@/hooks/use-is-embedded";
import { useIsFocusedProTab } from "@/hooks/use-pane-context";
import { useProMultiAccountContacts } from "@/hooks/use-pro-multi-account-contacts";
import { ResizeHandle } from "@/components/layout/resize-handle";
import { EdgeDrawer } from "@/components/layout/edge-drawer";
import { useIsFullDesktop, useIsMobile } from "@/hooks/use-media-query";
import { useRefreshGesture } from "@/hooks/use-refresh-gesture";
import type { ContactCard, AddressBook, AddressBookRights } from "@/lib/jmap/types";
@@ -210,6 +211,7 @@ function ContactsAppContent({ linkSegments: routeSegments }: ContactsAppProps =
// into a burger-toggled overlay.
const isNarrow = !isFullDesktop;
const [narrowSidebarOpen, setNarrowSidebarOpen] = useState(false);
const closeNarrowSidebar = useCallback(() => setNarrowSidebarOpen(false), []);
useEffect(() => { if (!isNarrow) setNarrowSidebarOpen(false); }, [isNarrow]);
// A new view (a form, a group, a contact) replaces whatever the drawer was for.
useEffect(() => { setNarrowSidebarOpen(false); }, [view]);
@@ -1285,6 +1287,60 @@ function ContactsAppContent({ linkSegments: routeSegments }: ContactsAppProps =
}
})();
// The categories: beside the list on the full desktop, a drawer below it.
const contactsSidebar = (
<ContactsSidebar
groups={groups}
individuals={individuals}
addressBooks={addressBooks}
activeCategory={activeCategory}
onSelectCategory={guard(handleSelectCategory)}
onCreateGroup={fromDrawer(guard(handleCreateGroup))}
onCreateContact={fromDrawer(guard(handleCreateNew))}
onCreateAddressBook={client ? fromDrawer(() => setCreatingAddressBook(true)) : undefined}
onImport={fromDrawer(() => setShowImportDialog(true))}
onEditGroup={fromDrawer(guard(handleEditGroupFromSidebar))}
onDeleteGroup={fromDrawer(handleDeleteGroupFromSidebar)}
onComposeGroup={fromDrawer(handleComposeGroupFromSidebar)}
onDropContacts={handleDropContacts}
onDropContactsToCategory={handleDropContactsToCategory}
onRenameAddressBook={client ? fromDrawer((book: AddressBook) => setRenamingAddressBook(book)) : undefined}
onShareAddressBook={client ? fromDrawer((book: AddressBook) => setSharingAddressBookId(book.id)) : undefined}
onSetDefaultAddressBook={client ? fromDrawer(async (book: AddressBook) => {
try {
await setDefaultAddressBook(client, book);
toast.success(t("address_books.default_updated"));
} catch {
toast.error(t("address_books.set_default_failed"));
}
}) : undefined}
onCreateContactInBook={fromDrawer(guard((book: AddressBook) => {
setDefaultBookIdForCreate(book.id);
setSelectedContact(null);
setView("create");
}))}
onDeleteAddressBook={client ? fromDrawer(async (book: AddressBook) => {
const ok = await confirmDialog({
title: t("address_books.delete_title"),
message: t("address_books.confirm_delete", { name: shownName.addressBook(book) }),
variant: "destructive",
confirmText: t("address_books.delete"),
});
if (!ok) return;
try {
await removeAddressBook(client, book);
toast.success(t("address_books.deleted"));
} catch {
toast.error(t("address_books.delete_failed"));
}
}) : undefined}
onRenameKeyword={fromDrawer((kw: string) => setRenamingKeyword(kw))}
onDeleteKeyword={fromDrawer((kw: string) => void handleDeleteKeyword(kw))}
directoryCount={showDirectory ? directoryPrincipals.length : undefined}
multiAccountMode={multiAccountEnabled && accountClients.length > 1}
/>
);
const mobileBackToList = () => {
if (returnToEmail) {
setReturnToEmail(false);
@@ -1331,105 +1387,49 @@ function ContactsAppContent({ linkSegments: routeSegments }: ContactsAppProps =
{inlineApp && (
<InlineAppView apps={loadedApps} activeAppId={inlineApp!.id} onClose={closeInlineApp} />
)}
{/* Clips the closed drawer, so it never sits over the nav rail. */}
{/* Holds the drawer in a Pro pane and clips it there when closed. */}
<div className={cn("relative flex flex-1 min-h-0 overflow-hidden", inlineApp && "hidden")}>
{/* Narrow-pane backdrop for the overlay categories sidebar */}
{isNarrow && narrowSidebarOpen && (
<div
className={cn(
"inset-0 bg-black/50 z-40",
isEmbedded ? "absolute" : "fixed"
)}
onClick={() => setNarrowSidebarOpen(false)}
/>
{/* Panel 1: the categories. Below the full desktop a drawer from the
window's edge, over the app rail, as Mail's folders. */}
{showListPanel && isNarrow && (
<EdgeDrawer
open={narrowSidebarOpen}
onClose={closeNarrowSidebar}
contained={isEmbedded || mvShell}
data-testid="contacts-sidebar-drawer"
data-pane="sidebar"
className="border-e border-border bg-background"
>
{contactsSidebar}
</EdgeDrawer>
)}
{showListPanel && !isNarrow && !isMobile && (
<>
<div
data-pane="sidebar"
className={cn(
"border-e border-border flex flex-col flex-shrink-0 bg-background",
!isSidebarResizing && "transition-[width] duration-300",
)}
style={{ width: `${sidebarWidth}px` }}
>
{contactsSidebar}
</div>
<ResizeHandle
pane="sidebar"
value={sidebarWidth}
min={180}
max={400}
onResizeStart={() => { sidebarDragStartWidth.current = sidebarWidth; setIsSidebarResizing(true); }}
onResize={(delta) => setSidebarWidth(Math.max(180, Math.min(400, sidebarDragStartWidth.current + delta)))}
onResizeEnd={() => {
setIsSidebarResizing(false);
localStorage.setItem("contacts-sidebar-width", String(sidebarWidth));
}}
onDoubleClick={() => { setSidebarWidth(256); localStorage.setItem("contacts-sidebar-width", "256"); }}
/>
</>
)}
{/* Panel 1: Categories sidebar (in-flow on desktop, overlay on narrow) */}
{showListPanel && (!isMobile || isNarrow) && (
<>
<div
data-testid={isNarrow ? "contacts-sidebar-drawer" : undefined}
data-pane="sidebar"
className={cn(
"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-[var(--app-top-inset)]",
"transform transition-[transform,visibility] duration-300 ease-in-out",
!narrowSidebarOpen && "invisible -translate-x-full rtl:translate-x-full"
)
)}
// Closed, the drawer is out of reach: no clicks, no Tab stops.
inert={isNarrow && !narrowSidebarOpen}
style={isNarrow ? undefined : { width: `${sidebarWidth}px` }}
>
<ContactsSidebar
groups={groups}
individuals={individuals}
addressBooks={addressBooks}
activeCategory={activeCategory}
onSelectCategory={guard(handleSelectCategory)}
onCreateGroup={fromDrawer(guard(handleCreateGroup))}
onCreateContact={fromDrawer(guard(handleCreateNew))}
onCreateAddressBook={client ? fromDrawer(() => setCreatingAddressBook(true)) : undefined}
onImport={fromDrawer(() => setShowImportDialog(true))}
onEditGroup={fromDrawer(guard(handleEditGroupFromSidebar))}
onDeleteGroup={fromDrawer(handleDeleteGroupFromSidebar)}
onComposeGroup={fromDrawer(handleComposeGroupFromSidebar)}
onDropContacts={handleDropContacts}
onDropContactsToCategory={handleDropContactsToCategory}
onRenameAddressBook={client ? fromDrawer((book: AddressBook) => setRenamingAddressBook(book)) : undefined}
onShareAddressBook={client ? fromDrawer((book: AddressBook) => setSharingAddressBookId(book.id)) : undefined}
onSetDefaultAddressBook={client ? fromDrawer(async (book: AddressBook) => {
try {
await setDefaultAddressBook(client, book);
toast.success(t("address_books.default_updated"));
} catch {
toast.error(t("address_books.set_default_failed"));
}
}) : undefined}
onCreateContactInBook={fromDrawer(guard((book: AddressBook) => {
setDefaultBookIdForCreate(book.id);
setSelectedContact(null);
setView("create");
}))}
onDeleteAddressBook={client ? fromDrawer(async (book: AddressBook) => {
const ok = await confirmDialog({
title: t("address_books.delete_title"),
message: t("address_books.confirm_delete", { name: shownName.addressBook(book) }),
variant: "destructive",
confirmText: t("address_books.delete"),
});
if (!ok) return;
try {
await removeAddressBook(client, book);
toast.success(t("address_books.deleted"));
} catch {
toast.error(t("address_books.delete_failed"));
}
}) : undefined}
onRenameKeyword={fromDrawer((kw: string) => setRenamingKeyword(kw))}
onDeleteKeyword={fromDrawer((kw: string) => void handleDeleteKeyword(kw))}
directoryCount={showDirectory ? directoryPrincipals.length : undefined}
multiAccountMode={multiAccountEnabled && accountClients.length > 1}
/>
</div>
{!isNarrow && (
<ResizeHandle
pane="sidebar"
value={sidebarWidth}
min={180}
max={400}
onResizeStart={() => { sidebarDragStartWidth.current = sidebarWidth; setIsSidebarResizing(true); }}
onResize={(delta) => setSidebarWidth(Math.max(180, Math.min(400, sidebarDragStartWidth.current + delta)))}
onResizeEnd={() => {
setIsSidebarResizing(false);
localStorage.setItem("contacts-sidebar-width", String(sidebarWidth));
}}
onDoubleClick={() => { setSidebarWidth(256); localStorage.setItem("contacts-sidebar-width", "256"); }}
/>
)}
</>
)}
{/* The list and the contact: the main content, after the sidebar. */}
<AppMain
+3
View File
@@ -323,6 +323,8 @@ export function ContactsSidebar({
{/* All contacts */}
<button
onClick={() => onSelectCategory("all")}
// Marked as the other categories are: the drawer opens on it.
aria-current={isAllActive ? "true" : undefined}
className={cn(
"w-full flex items-center gap-2 px-3 text-sm transition-colors min-h-8 pointer-coarse:min-h-11",
isAllActive
@@ -342,6 +344,7 @@ export function ContactsSidebar({
{directoryCount !== undefined && (
<button
onClick={() => onSelectCategory("directory")}
aria-current={activeCategory === "directory" ? "true" : undefined}
className={cn(
"w-full flex items-center gap-2 px-3 text-sm transition-colors min-h-8 pointer-coarse:min-h-11",
activeCategory === "directory"
@@ -0,0 +1,401 @@
import { render, screen, fireEvent, act, waitFor, within } from '@testing-library/react';
import { describe, it, expect, vi, afterEach } from 'vitest';
import React from 'react';
import { EmailComposer } from '../email-composer';
import { useAuthStore } from '@/stores/auth-store';
import { DEFAULT_POLICY_SNAPSHOT, type PolicySnapshot } from '@/lib/desktop/policy-schema';
import type { BulwarkDesktopBridge, DesktopRecentFile } from '@/lib/desktop/types';
// Recent files in the Attach menu, in the desktop app: the shell's side is
// repos/desktop's test/recent-files.spec.ts; here the bridge is a stub.
const hoisted = vi.hoisted(() => ({
picked: [] as unknown[],
beforeAttachmentUpload: vi.fn(async (_info: { name: string }) => true),
toastError: vi.fn(),
}));
vi.mock('@/components/files/file-picker-dialog', () => ({
FilePickerDialog: ({ onPick }: { onPick: (nodes: unknown[]) => void }) =>
React.createElement(
'button',
{ type: 'button', 'data-testid': 'fake-file-picker', onClick: () => onPick(hoisted.picked) },
'pick',
),
}));
// ─── Heavy component mocks (mirrors composer-plugin-attachment-source.test.tsx) ─
vi.mock('@/components/email/rich-text-editor', () => ({
RichTextEditor: () => React.createElement('div', { 'data-testid': 'rich-text-editor' }),
}));
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-focus-trap', () => ({
useFocusTrap: () => ({ current: null }),
}));
vi.mock('@/hooks/use-pro-multi-account-identities', () => ({
useProMultiAccountIdentities: () => ({ enabled: false, groups: [], allIdentities: [] }),
stripCrossAccountIdentityPrefix: (id: string) => ({ localAccountId: null, rawId: id }),
}));
// ─── Store mocks ──────────────────────────────────────────────────────────────
vi.mock('@/stores/auth-store', () => {
const state = {
client: null,
identities: [],
primaryIdentity: null,
isAuthenticated: false,
isDemoMode: false,
activeAccountId: null,
connectionLost: false,
getClientForAccount: () => undefined,
getAllConnectedClients: () => new Map(),
syncIdentities: () => {},
refreshIdentities: async () => {},
};
const hook = (sel?: (s: typeof state) => unknown) =>
typeof sel === 'function' ? sel(state) : state;
hook.getState = () => state;
hook.setState = (p: Partial<typeof state>) => Object.assign(state, p);
return { useAuthStore: hook };
});
vi.mock('@/stores/identity-store', () => {
const state = {
identities: [{ id: 'id-me', email: 'me@example.com', name: 'Me' }],
defaultIdentityId: 'id-me',
};
const hook = (sel?: (s: typeof state) => unknown) =>
typeof sel === 'function' ? sel(state) : state;
hook.getState = () => state;
hook.setState = (p: Partial<typeof state>) => Object.assign(state, p);
return { useIdentityStore: hook };
});
vi.mock('@/stores/account-store', () => {
const state = { accounts: [], getAccountById: () => undefined };
const hook = (sel?: (s: typeof state) => unknown) =>
typeof sel === 'function' ? sel(state) : state;
hook.getState = () => state;
hook.setState = (p: Partial<typeof state>) => Object.assign(state, p);
return { useAccountStore: hook };
});
vi.mock('@/stores/email-store', () => {
const state = {
draftSaveEnabled: false,
sendRawEmail: async () => ({ sent: true }),
};
const hook = (sel?: (s: typeof state) => unknown) =>
typeof sel === 'function' ? sel(state) : state;
hook.getState = () => state;
hook.setState = (p: Partial<typeof state>) => Object.assign(state, p);
return { useEmailStore: hook };
});
vi.mock('@/stores/settings-store', () => {
const state = {
timeFormat: '24h',
plainTextMode: false,
subAddressDelimiter: '+',
autoSelectReplyIdentity: true,
attachmentReminderEnabled: false,
attachmentReminderKeywords: [],
emptySubjectWarningEnabled: true,
sendDelaySeconds: 0,
signaturePosition: 'above_quote',
signatureSeparatorEnabled: false,
requestReadReceiptDefault: false,
addTrustedSender: () => {},
trustedSendersAddressBook: null,
updateSetting: () => {},
};
const hook = (sel?: (s: typeof state) => unknown) =>
typeof sel === 'function' ? sel(state) : state;
hook.getState = () => state;
hook.setState = (p: Partial<typeof state>) => Object.assign(state, p);
return { useSettingsStore: hook };
});
vi.mock('@/stores/contact-store', () => {
const state = {
contacts: [],
getAutocomplete: async () => [],
addToTrustedSendersBook: async () => {},
};
const hook = (sel?: (s: typeof state) => unknown) =>
typeof sel === 'function' ? sel(state) : state;
hook.getState = () => state;
hook.setState = (p: Partial<typeof state>) => Object.assign(state, p);
return { useContactStore: hook };
});
vi.mock('@/stores/template-store', () => {
const state = { templates: [], addTemplate: async () => {} };
const hook = (sel?: (s: typeof state) => unknown) =>
typeof sel === 'function' ? sel(state) : state;
hook.getState = () => state;
hook.setState = (p: Partial<typeof state>) => Object.assign(state, p);
return { useTemplateStore: hook };
});
// ─── Misc dependency mocks ────────────────────────────────────────────────────
vi.mock('@/stores/toast-store', () => ({
toast: { info: () => {}, error: hoisted.toastError, success: () => {} },
}));
vi.mock('@/lib/plugin-hooks', () => ({
identityHooks: {
onSignatureRender: { size: 0, transform: async (value: unknown) => value },
onIdentitySelect: { size: 0, emit: async () => {} },
},
templateHooks: {
onTemplateRender: { size: 0, transform: async (value: unknown) => value },
onTemplateApply: { size: 0, emit: async () => {} },
},
emailHooks: {
onComposerOpen: { call: async () => [] },
onRecipientChange: { call: async () => [] },
getRecipientSuggestions: { call: async () => [] },
onRecipientChipsChange: { transform: async (chips: unknown) => chips },
onDraftChange: { emit: () => {} },
onBeforeDraftAutoSave: { transform: async (draft: unknown) => draft },
onBeforeEmailSend: { intercept: async () => true, interceptOutcome: async () => 'allowed' },
onBeforeAttachmentUpload: { intercept: hoisted.beforeAttachmentUpload },
onComposeSend: { takeOver: async () => 'default' },
onTransformOutgoingEmail: { transform: async (email: unknown) => email },
},
contactHooks: {
search: { call: async () => [] },
onProvideRecipientSuggestions: { transform: async (initial: unknown) => initial },
},
}));
vi.mock('@/lib/email-sanitization', () => ({
sanitizeSignatureHtml: (v: string) => v,
sanitizeEmailHtml: (v: string) => v,
parseHtmlSafely: (html: string) => new DOMParser().parseFromString(html, 'text/html'),
}));
vi.mock('@/lib/email-threading', () => ({
computeReplyThreadingHeaders: () => ({ inReplyTo: [], references: [] }),
}));
vi.mock('@/lib/signature-utils', () => ({
appendPlainTextSignature: (body: string) => body,
getPlainTextSignature: () => '',
plainTextBodyHasSignature: () => false,
plainTextBodyWithoutSignature: (body: string) => body,
}));
vi.mock('@/lib/sub-addressing', () => ({ generateSubAddress: () => '' }));
vi.mock('@/lib/debug', () => ({ debug: { log: () => {}, warn: () => {}, error: () => {} } }));
vi.mock('@/components/email/quoted-html', () => ({
buildQuotedHtmlBlock: () => '',
serializeEditorContent: () => '',
}));
vi.mock('@/lib/template-utils', () => ({ substitutePlaceholders: (s: string) => s }));
// ─── Tests ────────────────────────────────────────────────────────────────────
const NOW = Date.now();
const RECENT: DesktopRecentFile[] = [
{ id: 'id-report', name: 'Quarterly report.docx', folder: '\\\\files\\team\\Reports', path: '\\\\files\\team\\Reports\\Quarterly report.docx', usedAt: NOW - 5 * 60_000, icon: 'data:image/png;base64,iVBORw0KGgo=' },
{ id: 'id-budget', name: 'Budget 2027.xlsx', folder: 'C:\\Users\\me\\Documents', path: 'C:\\Users\\me\\Documents\\Budget 2027.xlsx', usedAt: NOW - 3 * 60 * 60_000 },
];
interface DesktopOptions {
files?: DesktopRecentFile[];
policyOff?: boolean;
/** The shell's native menus: the Attach menu must stay HTML all the same. */
popup?: ReturnType<typeof vi.fn>;
}
function desktop({ files = RECENT, policyOff = false, popup }: DesktopOptions = {}) {
const snapshot: PolicySnapshot = {
...DEFAULT_POLICY_SNAPSHOT,
...(policyOff ? { RecentFilesInAttach: { value: false, source: 'forced-machine', locked: true } } : {}),
} as PolicySnapshot;
const list = vi.fn(async () => ({ ok: true as const, files }));
const attach = vi.fn(async (id: string) => {
const file = files.find((f) => f.id === id);
return file
? { ok: true as const, file: { name: file.name, data: new TextEncoder().encode(`bytes of ${file.name}`) } }
: { ok: false as const, reason: 'unknown' as const };
});
window.bulwarkDesktop = {
version: 1,
platform: 'win32',
policy: { get: () => snapshot, onChange: () => () => {} },
recentFiles: { list, attach },
...(popup ? { menu: { popup, setState: () => {}, onCommand: () => () => {} } } : {}),
} as unknown as BulwarkDesktopBridge;
return { list, attach };
}
function client(overrides: Record<string, unknown> = {}) {
return {
createDraft: vi.fn().mockResolvedValue('draft-1'),
getEmail: vi.fn(),
hasDelayedSend: () => false,
getMaxDelayedSend: () => 0,
// No Files, no plugins: in a browser, Attach is a plain button.
supportsFiles: () => false,
getMaxSizeAttachmentsPerEmail: () => 0,
getMaxSizeUpload: () => 0,
uploadBlob: vi.fn(() => new Promise(() => {})),
...overrides,
};
}
const rows = () => screen.queryAllByTestId('composer-recent-file');
async function openMenu() {
fireEvent.click(screen.getByTestId('composer-attach-menu'));
await act(async () => {});
}
describe('recent files in the Attach menu', () => {
afterEach(() => {
window.bulwarkDesktop = undefined;
useAuthStore.setState({ client: null });
vi.clearAllMocks();
hoisted.beforeAttachmentUpload.mockImplementation(async () => true);
});
it('in a browser the paperclip is the plain button it was', () => {
useAuthStore.setState({ client: client() as never });
render(<EmailComposer onClose={vi.fn()} />);
expect(screen.queryByTestId('composer-attach-menu')).toBeNull();
expect(screen.getByRole('button', { name: 'attach' })).toBeInTheDocument();
});
it('in the desktop app the paperclip opens a menu: recent files first, then the file dialog', async () => {
const { list } = desktop();
useAuthStore.setState({ client: client() as never });
render(<EmailComposer onClose={vi.fn()} />);
expect(list).not.toHaveBeenCalled();
await openMenu();
expect(list).toHaveBeenCalledTimes(1);
const menu = screen.getByRole('menu');
const items = within(menu).getAllByRole('menuitem');
expect(items.map((item) => item.getAttribute('data-testid'))).toEqual(['composer-recent-file', 'composer-recent-file', 'composer-attach-from-device']);
expect(within(menu).getByText('heading')).toBeInTheDocument();
expect(items[2]).toHaveTextContent('browse');
const [report, budget] = rows();
expect(report).toHaveTextContent('Quarterly report.docx');
expect(report).toHaveTextContent('\\\\files\\team\\Reports');
expect(report).toHaveTextContent('5 minutes ago');
expect(report).toHaveAttribute('title', '\\\\files\\team\\Reports\\Quarterly report.docx');
expect(report.querySelector('img')).toHaveAttribute('src', RECENT[0].icon);
// No icon from the shell: the app's own for the type.
expect(budget.querySelector('img')).toBeNull();
expect(budget.querySelector('svg')).not.toBeNull();
expect(budget).toHaveTextContent('3 hours ago');
});
it('one click attaches that file through the composer\'s own checks and closes the menu', async () => {
const { attach } = desktop();
useAuthStore.setState({ client: client() as never });
render(<EmailComposer onClose={vi.fn()} />);
await openMenu();
fireEvent.click(rows()[1]);
expect(screen.queryByRole('menu')).toBeNull();
expect(attach).toHaveBeenCalledWith('id-budget');
expect(await screen.findByText('Budget 2027.xlsx')).toBeInTheDocument();
expect(hoisted.beforeAttachmentUpload).toHaveBeenCalledWith(expect.objectContaining({ name: 'Budget 2027.xlsx', size: 'bytes of Budget 2027.xlsx'.length }));
});
it('a plugin can refuse it, as it can a file from the dialog', async () => {
hoisted.beforeAttachmentUpload.mockImplementation(async (info) => info.name !== 'Budget 2027.xlsx');
desktop();
useAuthStore.setState({ client: client() as never });
render(<EmailComposer onClose={vi.fn()} />);
await openMenu();
fireEvent.click(rows()[1]);
await act(async () => {});
expect(hoisted.beforeAttachmentUpload).toHaveBeenCalled();
expect(screen.queryByText('Budget 2027.xlsx')).toBeNull();
});
it('the server\'s size limit applies too', async () => {
desktop();
useAuthStore.setState({ client: client({ getMaxSizeUpload: () => 5 }) as never });
render(<EmailComposer onClose={vi.fn()} />);
await openMenu();
fireEvent.click(rows()[0]);
await act(async () => {});
expect(hoisted.toastError).toHaveBeenCalledWith('attachment_too_large');
expect(screen.queryByText('Quarterly report.docx')).toBeNull();
});
it('says so when the file is gone or too large for the app', async () => {
const { attach } = desktop();
useAuthStore.setState({ client: client() as never });
render(<EmailComposer onClose={vi.fn()} />);
attach.mockResolvedValueOnce({ ok: false, reason: 'missing' } as never);
await openMenu();
fireEvent.click(rows()[0]);
await act(async () => {});
expect(hoisted.toastError).toHaveBeenLastCalledWith('missing');
attach.mockResolvedValueOnce({ ok: false, reason: 'too-large' } as never);
await openMenu();
fireEvent.click(rows()[0]);
await act(async () => {});
expect(hoisted.toastError).toHaveBeenLastCalledWith('too_large');
});
it('with nothing recent the menu has only its other entries', async () => {
desktop({ files: [] });
useAuthStore.setState({ client: client() as never });
render(<EmailComposer onClose={vi.fn()} />);
await openMenu();
const menu = screen.getByRole('menu');
expect(within(menu).queryByText('heading')).toBeNull();
expect(within(menu).queryByRole('separator')).toBeNull();
expect(within(menu).getAllByRole('menuitem').map((item) => item.getAttribute('data-testid'))).toEqual(['composer-attach-from-device']);
});
it('with the policy off there\'s no list, and Attach is what it was', async () => {
const { list } = desktop({ policyOff: true });
useAuthStore.setState({ client: client() as never });
render(<EmailComposer onClose={vi.fn()} />);
expect(screen.queryByTestId('composer-attach-menu')).toBeNull();
fireEvent.click(screen.getByRole('button', { name: 'attach' }));
await act(async () => {});
expect(list).not.toHaveBeenCalled();
});
it('keys: the first file has the focus, arrows move, Escape closes', async () => {
desktop();
useAuthStore.setState({ client: client() as never });
render(<EmailComposer onClose={vi.fn()} />);
await openMenu();
await waitFor(() => expect(document.activeElement).toBe(rows()[0]), { timeout: 5000 });
fireEvent.keyDown(document.activeElement!, { key: 'ArrowDown' });
expect(document.activeElement).toBe(rows()[1]);
fireEvent.keyDown(document.activeElement!, { key: 'ArrowDown' });
expect(document.activeElement).toHaveAttribute('data-testid', 'composer-attach-from-device');
fireEvent.keyDown(document.activeElement!, { key: 'Escape' });
expect(screen.queryByRole('menu')).toBeNull();
});
it('stays an HTML menu where the shell would draw it natively', async () => {
const popup = vi.fn(async () => null);
desktop({ popup });
useAuthStore.setState({ client: client() as never });
render(<EmailComposer onClose={vi.fn()} />);
await openMenu();
await act(async () => { await new Promise((resolve) => setTimeout(resolve, 300)); });
expect(popup).not.toHaveBeenCalled();
expect(rows()).toHaveLength(2);
});
});
@@ -585,6 +585,7 @@ describe('composer-sidebar and composer-sidebar-right', () => {
Element.prototype.getBoundingClientRect = function (this: Element) {
if (this.matches('[data-testid="email-composer"]')) return rect(100, 800);
if (this.matches('[data-composer-header]')) return rect(100, 156);
if (this.matches('[data-composer-panels]')) return rect(156, 800);
if (this.matches('[data-composer-footer]')) return rect(740, 800);
return original.call(this);
};
@@ -593,7 +594,9 @@ describe('composer-sidebar and composer-sidebar-right', () => {
render(<EmailComposer initialData={DRAFT} onClose={vi.fn()} />);
fireEvent.click(document.querySelector('[data-composer-panel-toggle="right"]')!);
expect(panel('right').dataset.composerSidebarMode).toBe('overlay');
expect(panel('right').style.top).toBe('56px');
// The header is above the row the panel is laid over: the panel starts at that row's top.
expect(document.querySelector('[data-composer-panels]')!.contains(document.querySelector('[data-composer-header]'))).toBe(false);
expect(panel('right').style.top).toBe('0px');
expect(panel('right').style.bottom).toBe('60px');
} finally {
Element.prototype.getBoundingClientRect = original;
@@ -718,7 +721,7 @@ describe('composer-sidebar and composer-sidebar-right', () => {
// Opened once: it stays open for the next composer.
render(<EmailComposer initialData={DRAFT} onClose={vi.fn()} />);
expect(panel('right').dataset.composerSidebarMode).toBe('docked');
fireEvent.click(screen.getByRole('button', { name: 'plugin_panel_hide' }));
fireEvent.click(screen.getByRole('button', { name: 'hide_panel' }));
expect(panel('right').dataset.composerSidebarMode).toBe('folded');
});
@@ -742,11 +745,134 @@ describe('composer-sidebar and composer-sidebar-right', () => {
offerSlots('p1', ['composer-sidebar-right']);
render(<EmailComposer initialData={DRAFT} onClose={vi.fn()} />);
fireEvent.click(screen.getByRole('button', { name: 'plugin_panel_show' }));
fireEvent.click(screen.getByRole('button', { name: 'show_panel' }));
expect(panel('right').dataset.composerSidebarMode).toBe('overlay');
expect(panel('right').className).toContain('absolute');
fireEvent.click(screen.getByRole('button', { name: 'plugin_panel_hide' }));
fireEvent.click(screen.getByRole('button', { name: 'hide_panel' }));
expect(panel('right').dataset.composerSidebarMode).toBe('folded');
});
});
// With a panel open, the composer's header runs over it: Full screen, Pop out
// and Close end the whole composer, not the message column in the middle of
// it. The panel's head (the header above it) has its own Hide button.
describe('the composer header with a plugin panel open', () => {
function stubWidth(width: number) {
class FixedWidthObserver {
constructor(private cb: ResizeObserverCallback) {}
observe(el: Element) {
if ((el as HTMLElement).dataset.testid !== 'email-composer') return;
this.cb([{ target: el, contentRect: { width, height: 700 } } as unknown as ResizeObserverEntry], this as unknown as ResizeObserver);
}
unobserve() {}
disconnect() {}
}
vi.stubGlobal('ResizeObserver', FixedWidthObserver);
}
const panel = (side: 'left' | 'right') => document.querySelector<HTMLElement>(`[data-composer-sidebar="${side}"]`)!;
const header = () => document.querySelector<HTMLElement>('[data-composer-header]')!;
const head = (side: 'left' | 'right') => document.querySelector<HTMLElement>(`[data-composer-panel-head="${side}"]`);
const buttons = (el: HTMLElement) => Array.from(el.querySelectorAll<HTMLElement>('button'));
afterEach(() => {
vi.unstubAllGlobals();
for (const side of ['left', 'right']) {
localStorage.removeItem(`composerPluginSidebarCollapsed:${side}`);
localStorage.removeItem(`composerPluginSidebarWidth:${side}`);
}
});
it('keeps Close the last control, at the end of the row over the open panel', () => {
stubWidth(1400);
offerSlots('p1', ['composer-sidebar-right']);
render(<EmailComposer initialData={DRAFT} onClose={vi.fn()} />);
expect(panel('right').dataset.composerSidebarMode).toBe('docked');
// One row over the message and the panel: the panel is not beside the header.
expect(header().parentElement).toBe(screen.getByTestId('email-composer'));
expect(header().compareDocumentPosition(panel('right')) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
// The part of it above the panel is as wide as the panel...
const right = head('right')!;
expect(header()).toContainElement(right);
expect(right.style.minWidth).toBe('260px');
// ...and ends with Full screen, Pop out and Close, Close last.
const all = buttons(header());
expect(all[all.length - 1]).toBe(screen.getByTestId('composer-close'));
expect(right).toContainElement(screen.getByTestId('composer-close'));
expect(right).toContainElement(screen.getByTestId('composer-maximize'));
});
it('gives the open panel a Hide button in its head, and the header a Show button while it is folded', () => {
stubWidth(1400);
offerSlots('p1', ['composer-sidebar', 'composer-sidebar-right']);
render(<EmailComposer initialData={DRAFT} onClose={vi.fn()} />);
for (const side of ['left', 'right'] as const) {
const hide = head(side)!.querySelector<HTMLElement>(`[data-composer-panel-hide="${side}"]`)!;
expect(hide).toBeTruthy();
expect(hide).toHaveAccessibleName('hide_panel');
expect(hide.getAttribute('title')).toBe('hide_panel');
expect(hide.getAttribute('aria-expanded')).toBe('true');
}
// At the panel's inner edge, where it meets the message: last in the left head, first in the right one.
expect(buttons(head('left')!).at(-1)!.dataset.composerPanelHide).toBe('left');
expect(buttons(head('right')!)[0].dataset.composerPanelHide).toBe('right');
fireEvent.click(head('right')!.querySelector('[data-composer-panel-hide]')!);
expect(panel('right').dataset.composerSidebarMode).toBe('folded');
expect(head('right')).toBeNull();
// Folded: one Show button in the header, before the window buttons; Close still last.
const show = screen.getByRole('button', { name: 'show_panel' });
expect(header()).toContainElement(show);
expect(show.getAttribute('aria-expanded')).toBe('false');
const all = buttons(header());
expect(all[all.length - 1]).toBe(screen.getByTestId('composer-close'));
expect(all.indexOf(show)).toBeLessThan(all.indexOf(screen.getByTestId('composer-maximize')));
fireEvent.click(show);
expect(panel('right').dataset.composerSidebarMode).toBe('docked');
expect(head('right')).toContainElement(screen.getByTestId('composer-close'));
});
it('hides the panel with Hide and closes the composer only with Close', () => {
stubWidth(1400);
offerSlots('p1', ['composer-sidebar-right']);
const onClose = vi.fn();
render(<EmailComposer initialData={DRAFT} onClose={onClose} />);
const hide = head('right')!.querySelector<HTMLElement>('[data-composer-panel-hide]')!;
const close = screen.getByTestId('composer-close');
expect(hide).not.toBe(close);
expect(hide).not.toHaveAccessibleName(close.getAttribute('aria-label')!);
fireEvent.click(hide);
expect(panel('right').dataset.composerSidebarMode).toBe('folded');
expect(onClose).not.toHaveBeenCalled();
expect(screen.queryByRole('alertdialog')).toBeNull();
expect(screen.getByTestId('email-composer')).toBeInTheDocument();
fireEvent.click(screen.getByTestId('composer-close'));
expect(onClose.mock.calls.length > 0 || screen.queryByRole('alertdialog') !== null).toBe(true);
});
it('gives a panel laid over a narrow composer the same head', () => {
stubWidth(700);
offerSlots('p1', ['composer-sidebar-right']);
render(<EmailComposer initialData={DRAFT} onClose={vi.fn()} />);
fireEvent.click(screen.getByRole('button', { name: 'show_panel' }));
expect(panel('right').dataset.composerSidebarMode).toBe('overlay');
expect(head('right')).toContainElement(screen.getByTestId('composer-close'));
fireEvent.click(screen.getByRole('button', { name: 'hide_panel' }));
expect(panel('right').dataset.composerSidebarMode).toBe('folded');
});
it('keeps Close last in a composer that is its own window', () => {
stubWidth(1400);
offerSlots('p1', ['composer-sidebar-right']);
render(<EmailComposer initialData={DRAFT} onClose={vi.fn()} ownWindow={{}} />);
const all = buttons(header());
expect(all[all.length - 1]).toBe(screen.getByTestId('composer-close'));
expect(head('right')).toContainElement(screen.getByTestId('composer-close'));
});
});
+113 -25
View File
@@ -1,20 +1,25 @@
"use client";
// The composer-sidebar and composer-sidebar-right plugin panels. Each has a
// width the user can drag (kept across composers) and a button in the
// composer's header that shows and hides it (the left panel's at the start,
// the right one's at the end, like the reader's). Folded, a panel takes no
// room at all. When the composer is too narrow for an open panel next to
// it, the panel folds by itself (right first); opening it anyway lays it
// over the composer instead of squeezing the message into a column nobody
// can write in. Laid over, it stays between the composer's header and its
// bottom bar: the panel's own button, Close and Send stay in reach.
// width the user can drag (kept across composers). The composer's header
// runs across the whole composer, panels included, so its window buttons
// (Full screen, Pop out, Close) stay at the far end of it, as Outlook and
// Gmail have them. The part of that row above an open panel is the
// panel's head: it holds "Hide <panel>", at the panel's inner edge. A
// folded panel takes no room at all, and a "Show <panel>" button in the
// header brings it back (the left panel's at the start, the right one's
// before the window buttons). When the composer is too narrow for an open
// panel next to it, the panel folds by itself (right first); opening it
// anyway lays it over the composer instead of squeezing the message into a
// column nobody can write in. Laid over, it stays between the header and
// the bottom bar: Hide, Close and Send stay in reach.
import { useEffect, useLayoutEffect, useRef, useState, type RefObject } from "react";
import { useEffect, useLayoutEffect, useRef, useState, type ReactNode, type RefObject } from "react";
import { useTranslations } from "next-intl";
import { PanelLeftClose, PanelLeftOpen, PanelRightClose, PanelRightOpen } from "@/components/icons";
import { PluginSlot } from "@/components/plugins/plugin-slot";
import { usePluginSlotOffers } from "@/hooks/use-plugin-slot-offers";
import { get as getActivePlugin } from "@/lib/plugin-sandbox/registry";
import { onPanelRequest, type PanelRequest } from "@/lib/plugin-sandbox/panel-requests";
import { ResizeHandle } from "@/components/layout/resize-handle";
import { cn } from "@/lib/utils";
@@ -196,40 +201,123 @@ export function useComposerSidebars(root: HTMLElement | null, composerId: string
}
};
return { modes, open, close, toggle, focusRequests, widths, setSideWidth };
// What the panels are called in their Show and Hide buttons: their plugins' names.
const nameOf = (offers: readonly { pluginId: string }[]) =>
offers.map((o) => getActivePlugin(o.pluginId)?.plugin.name).filter((n): n is string => !!n).join(", ") || null;
const names: Record<ComposerSidebarSide, string | null> = { left: nameOf(leftOffers), right: nameOf(rightOffers) };
return { modes, open, close, toggle, focusRequests, widths, setSideWidth, names };
}
/** The button in the composer's header that shows and hides one panel (none on phones). */
export function ComposerPanelToggle({
side,
mode,
onToggle,
className,
}: {
/** Open beside the composer or over it: on screen, with a head in the header row. */
export function isPanelOpen(mode: ComposerSidebarMode | null): boolean {
return mode === "docked" || mode === "overlay";
}
/** The Show or Hide button of one panel. */
function PanelButton({ side, open, name, onToggle, className }: {
side: ComposerSidebarSide;
mode: ComposerSidebarMode | null;
open: boolean;
name: string | null;
onToggle: () => void;
className?: string;
}) {
const t = useTranslations("email_viewer");
if (!mode) return null;
const isOpen = mode !== "folded";
const Icon = side === "left" ? (isOpen ? PanelLeftClose : PanelLeftOpen) : (isOpen ? PanelRightClose : PanelRightOpen);
const t = useTranslations("composer_panel");
const tViewer = useTranslations("email_viewer");
const label = name
? t(open ? "hide_panel" : "show_panel", { name })
: tViewer(open ? "plugin_panel_hide" : "plugin_panel_show");
const Icon = side === "left" ? (open ? PanelLeftClose : PanelLeftOpen) : (open ? PanelRightClose : PanelRightOpen);
return (
<button
type="button"
onClick={(e) => { e.stopPropagation(); onToggle(); }}
className={cn("hidden md:grid h-8 w-8 shrink-0 place-items-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground", className)}
title={t(isOpen ? "plugin_panel_hide" : "plugin_panel_show")}
aria-label={t(isOpen ? "plugin_panel_hide" : "plugin_panel_show")}
aria-pressed={isOpen}
title={label}
aria-label={label}
aria-expanded={open}
data-composer-panel-toggle={side}
data-composer-panel-hide={open ? side : undefined}
>
<Icon className="h-4 w-4 rtl:-scale-x-100" />
</button>
);
}
/**
* The button in the composer's header that brings a folded panel back (none
* on phones). An open panel's Hide button is in its head instead
* (ComposerPanelHead).
*/
export function ComposerPanelToggle({
side,
mode,
name = null,
onToggle,
className,
}: {
side: ComposerSidebarSide;
mode: ComposerSidebarMode | null;
name?: string | null;
onToggle: () => void;
className?: string;
}) {
if (mode !== "folded") return null;
return <PanelButton side={side} open={false} name={name} onToggle={onToggle} className={className} />;
}
/**
* The part of the composer's header row above an open panel, as wide as the
* panel: its Hide button at the panel's inner edge, and for the right panel
* whatever else ends the row (the window buttons, Close last), so they stay
* at the far end of the composer. On phones there are no panels, and no head.
*/
export function ComposerPanelHead({
side,
mode,
width = COMPOSER_SIDEBAR_WIDTH,
name = null,
onToggle,
className,
childrenClassName,
children,
}: {
side: ComposerSidebarSide;
mode: ComposerSidebarMode | null;
width?: number;
name?: string | null;
onToggle: () => void;
/** Padding of the row it is part of. */
className?: string;
/** The gap between what it holds besides Hide, as in the row it is part of. */
childrenClassName?: string;
children?: ReactNode;
}) {
if (!isPanelOpen(mode)) return null;
const hide = <PanelButton side={side} open name={name} onToggle={onToggle} />;
return (
<div
className={cn(
// Below md, where panels aren't shown, only what it holds besides Hide
// shows, at the end of the row (one laid over a composer that got narrower).
"contents md:flex shrink-0 items-center self-stretch border-border",
side === "left" ? "border-e" : "border-s",
className,
)}
// At least the panel's width, so Hide sits at the panel's edge; more when
// the buttons need it (a narrow panel in the desktop app, beside its controls).
style={{ minWidth: width }}
data-composer-panel-head={side}
>
{side === "right" && hide}
<div className="hidden md:block flex-1" />
{/* No gap of the head's own around Hide and the space: a 260 px panel in the desktop app has just enough room for the buttons. */}
{children && <div className={cn("contents md:flex items-center", childrenClassName)}>{children}</div>}
{side === "left" && hide}
</div>
);
}
const COMPOSER_HEADER = "[data-composer-header], [data-mv-compose-titlebar], [data-mv-compose-inline-bar]";
const COMPOSER_FOOTER = "[data-composer-footer]";
+191 -116
View File
@@ -92,7 +92,7 @@ import { useIdentityStore } from "@/stores/identity-store";
import { useProMultiAccountIdentities, stripCrossAccountIdentityPrefix } from "@/hooks/use-pro-multi-account-identities";
import { useAccountStore } from "@/stores/account-store";
import { useSettingsStore } from "@/stores/settings-store";
import { ComposerPanelToggle, ComposerPluginSidebar, useComposerSidebars } from "./composer-plugin-sidebars";
import { ComposerPanelHead, ComposerPanelToggle, ComposerPluginSidebar, isPanelOpen, useComposerSidebars } from "./composer-plugin-sidebars";
import { dragKindFromTypes } from "@/components/pro/pro-shell-drop";
import { useIsPaneScoped } from "@/hooks/use-pane-context";
import { ComposerSelectionMenu, useComposerSelectionMenu } from "./composer-selection-menu";
@@ -188,8 +188,11 @@ import { fileStorage } from "@/lib/plugin-storage";
import { usePolicyStore } from "@/stores/policy-store";
import { isAppLockedNow } from "@/lib/app-lock/state";
import { registerComposeFlush, registerComposeSnapshot } from "@/lib/compose-flush-registry";
import { getDesktopBridge } from "@/lib/desktop/bridge";
import { getDesktopBridge, isDesktopApp } from "@/lib/desktop/bridge";
import { askInWindow } from "@/lib/desktop/dialog-window";
import { readRecentFile, RECENT_FILE_MAX_BYTES, useRecentFilesOffered } from "@/lib/desktop/recent-files";
import type { DesktopRecentFile } from "@/lib/desktop/types";
import { RecentFilesMenuSection } from "@/components/email/recent-files-menu-section";
import { useDesktopCommands } from "@/lib/desktop/commands";
import { noteComposerLanguage } from "@/lib/desktop/languages";
import { noteOpenDraft } from "@/lib/desktop/window-restore";
@@ -651,6 +654,7 @@ export function EmailComposer({
const tEdit = useTranslations('desktopEdit');
const tOfflineDrafts = useTranslations('offlineDrafts');
const tOffline = useTranslations('offline');
const tRecent = useTranslations('desktopAttachRecent');
const tOfflineNotes = useTranslations('offlineConflicts');
const tSendGuards = useTranslations('send_guards');
const tWords = useTranslations('compose_words');
@@ -2779,6 +2783,20 @@ export function EmailComposer({
void addFiles(initialFiles, { handedIn: true });
}, [client, initialFiles, addFiles]);
// The Attach menu's recent files, in the desktop app (lib/desktop/recent-files.ts). The
// shell reads the file; from there it's a file like one from the file dialog.
const recentOffered = useRecentFilesOffered();
const attachRecentFile = useCallback(async (file: DesktopRecentFile) => {
const result = await readRecentFile(file.id);
if (result.ok) {
await addFiles([result.file]);
return;
}
if (result.reason === 'missing') toast.error(tRecent('missing', { name: file.name }));
else if (result.reason === 'too-large') toast.error(tRecent('too_large', { name: file.name, max: formatFileSize(RECENT_FILE_MAX_BYTES) }));
else if (result.reason === 'failed') toast.error(tRecent('failed', { name: file.name }));
}, [addFiles, tRecent]);
const handleFileSelect = async (event: React.ChangeEvent<HTMLInputElement>) => {
if (!event.target.files) return;
await addFiles(Array.from(event.target.files));
@@ -3622,13 +3640,28 @@ export function EmailComposer({
[pluginDraft, pluginSelection, pluginComposerId, pluginSidebars.focusRequests.right],
);
// The buttons that show and hide the plugin panels, in the header.
const leftPanelToggle = pluginSidebars.modes.left
? <ComposerPanelToggle side="left" mode={pluginSidebars.modes.left} onToggle={() => pluginSidebars.toggle('left')} />
// The plugin panels in the header row: a folded one's Show button, and an
// open one's head with its Hide button (see composer-plugin-sidebars.tsx).
const leftPanelToggle = pluginSidebars.modes.left === 'folded'
? <ComposerPanelToggle side="left" mode="folded" name={pluginSidebars.names.left} onToggle={() => pluginSidebars.toggle('left')} />
: null;
const rightPanelToggle = pluginSidebars.modes.right
? <ComposerPanelToggle side="right" mode={pluginSidebars.modes.right} onToggle={() => pluginSidebars.toggle('right')} />
const rightPanelToggle = pluginSidebars.modes.right === 'folded'
? <ComposerPanelToggle side="right" mode="folded" name={pluginSidebars.names.right} onToggle={() => pluginSidebars.toggle('right')} />
: null;
const rightPanelOpen = isPanelOpen(pluginSidebars.modes.right);
const panelHead = (side: 'left' | 'right', className: string, children?: React.ReactNode, childrenClassName?: string) => (
<ComposerPanelHead
side={side}
mode={pluginSidebars.modes[side]}
width={pluginSidebars.widths[side]}
name={pluginSidebars.names[side]}
onToggle={() => pluginSidebars.toggle(side)}
className={className}
childrenClassName={childrenClassName}
>
{children}
</ComposerPanelHead>
);
// The right-click menu on selected text, when a plugin put entries in it.
const selectionMenu = useComposerSelectionMenu();
@@ -4738,6 +4771,86 @@ export function EmailComposer({
</button>
);
// What ends the header row: the window buttons, Close last. With the right
// panel open they end its head instead, at the far end of the composer.
const windowButtons = (
<>
{canMaximize && (
<button
type="button"
onClick={() => setMaximized((v) => !v)}
className="hidden md:grid h-8 w-8 shrink-0 place-items-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground"
aria-label={maximized ? t('restore') : t('maximize')}
title={maximized ? t('restore') : t('maximize')}
data-testid="composer-maximize"
>
{maximized ? <Minimize2 className="w-4 h-4" /> : <Maximize2 className="w-4 h-4" />}
</button>
)}
{popOutButton(cn(phoneLayout ? "hidden md:grid" : "grid", "h-8 w-8 shrink-0 place-items-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground"), "w-4 h-4")}
{!closeBesideControls && composerCloseButton}
</>
);
const mvInlineButtons = mvWindow && (
<>
{mvWindow.popOut && (
<button
type="button"
onClick={mvWindow.popOut}
className="grid h-8 w-8 shrink-0 place-items-center rounded-full text-muted-foreground hover:bg-muted hover:text-foreground"
aria-label={t('pop_out')}
title={t('pop_out')}
>
<ExternalLink className="h-4 w-4" />
</button>
)}
{popOutButton("grid h-8 w-8 shrink-0 place-items-center rounded-full text-muted-foreground hover:bg-muted hover:text-foreground", "h-4 w-4")}
<button
type="button"
onClick={() => handleClose()}
className="grid h-8 w-8 shrink-0 place-items-center rounded-full text-muted-foreground hover:bg-muted hover:text-foreground"
aria-label={tCommon('close')}
title={tCommon('close')}
>
<X className="h-4 w-4" />
</button>
</>
);
const mvWindowButtons = mvWindow && (
<>
{mvWindow.state !== "minimized" && popOutButton("grid h-7 w-7 shrink-0 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"); }}
className="grid h-7 w-7 shrink-0 place-items-center rounded-full text-muted-foreground hover:bg-foreground/10 hover:text-foreground"
aria-label={mvWindow.state === "minimized" ? t("restore") : t("minimize")}
title={mvWindow.state === "minimized" ? t("restore") : t("minimize")}
>
<Minus className="h-4 w-4" />
</button>
<button
type="button"
onClick={(e) => { e.stopPropagation(); mvWindow.setState(mvWindow.state === "maximized" ? "normal" : "maximized"); }}
className="grid h-7 w-7 shrink-0 place-items-center rounded-full text-muted-foreground hover:bg-foreground/10 hover:text-foreground"
aria-label={mvWindow.state === "maximized" ? t("restore") : t("maximize")}
title={mvWindow.state === "maximized" ? t("restore") : t("maximize")}
>
{mvWindow.state === "maximized" ? <Minimize2 className="h-4 w-4" /> : <Maximize2 className="h-4 w-4" />}
</button>
<button
type="button"
onClick={(e) => { e.stopPropagation(); handleClose(); }}
className="grid h-7 w-7 shrink-0 place-items-center rounded-full text-muted-foreground hover:bg-foreground/10 hover:text-foreground"
aria-label={tCommon('close')}
title={tCommon('close')}
>
<X className="h-4 w-4" />
</button>
</>
);
// Files dropped on the header attach, as on the rest of the message.
const headerDropProps = { onDragEnter: handleDragEnter, onDragLeave: handleDragLeave, onDragOver: handleDragOver, onDrop: handleDrop };
// `keepDraft`: the bin's discard, which deletes the draft once its Undo is
// over, not here.
const handleDiscardAndClose = ({ keepDraft = false }: { keepDraft?: boolean } = {}) => {
@@ -5044,8 +5157,11 @@ export function EmailComposer({
data-testid="email-composer"
// Edits made while the draft moves wouldn't move with it.
inert={isPoppingOut || undefined}
// The header row on top, across the plugin panels too, so the window
// buttons and Close end the whole composer; panels and message below.
data-tour="composer"
className={cn(
"flex h-full bg-background relative",
"flex flex-col h-full bg-background relative",
className,
// Over everything but dialogs (z-60) and toasts; below the desktop app's window controls.
// At the folder sidebar's z-50 and after it in the page, so over it (compose-p2-5).
@@ -5064,112 +5180,57 @@ export function EmailComposer({
<div role="status" aria-live="polite" aria-atomic="true" className="sr-only" data-testid="composer-live-region">
{liveMessage && <span key={liveMessage.n}>{liveMessage.text}</span>}
</div>
<ComposerPluginSidebar side="left" mode={pluginSidebars.modes.left} extraProps={pluginSidebarLeftProps} width={pluginSidebars.widths.left} onWidthChange={(w) => pluginSidebars.setSideWidth('left', w)} />
{/* Right-side composer sidebar slot is rendered after the main content div below. */}
<div
className="flex flex-col h-full bg-background relative flex-1 min-w-0"
data-tour="composer"
onDragEnter={handleDragEnter}
onDragLeave={handleDragLeave}
onDragOver={handleDragOver}
onDrop={handleDrop}
>
{/* Drag overlay */}
{isDraggingOver && (
<div className="absolute inset-0 z-50 flex items-center justify-center bg-background/80 border-2 border-dashed border-primary rounded-lg pointer-events-none">
<div className="flex flex-col items-center gap-2 text-primary">
<Paperclip className="w-8 h-8" />
<span className="text-sm font-medium">{t('drop_files')}</span>
</div>
</div>
)}
{/* Header - mobile: clean bar with close/send, desktop: title bar.
In Mountain View's window it is the window's title bar instead. */}
{mvWindow?.variant === "inline" ? (
<div className="flex items-center gap-2 h-10 ps-4 pe-1.5 shrink-0 border-b border-border/50" data-mv-compose-inline-bar="">
{mode === 'replyAll'
? <ReplyAll className="w-4 h-4 text-muted-foreground flex-shrink-0" />
: mode === 'forward'
? <Forward className="w-4 h-4 text-muted-foreground flex-shrink-0" />
: <Reply className="w-4 h-4 text-muted-foreground flex-shrink-0" />}
<h3 className="flex-1 min-w-0 truncate text-sm" data-testid="composer-save-status" data-status={saveStatus}>
{mode === 'reply' ? t('reply') : mode === 'replyAll' ? t('reply_all') : mode === 'forward' ? t('forward') : t('new_message')}
</h3>
{saveStatus === 'saving' && <Save className="w-3.5 h-3.5 animate-pulse text-muted-foreground flex-shrink-0" aria-label={t('saving')} />}
{leftPanelToggle}
{rightPanelToggle}
{mvWindow.popOut && (
<button
type="button"
onClick={mvWindow.popOut}
className="grid h-8 w-8 place-items-center rounded-full text-muted-foreground hover:bg-muted hover:text-foreground"
aria-label={t('pop_out')}
title={t('pop_out')}
>
<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()}
className="grid h-8 w-8 place-items-center rounded-full text-muted-foreground hover:bg-muted hover:text-foreground"
aria-label={tCommon('close')}
title={tCommon('close')}
>
<X className="h-4 w-4" />
</button>
<div className="flex items-stretch h-10 shrink-0 border-b border-border/50" data-mv-compose-inline-bar="" {...headerDropProps}>
{panelHead('left', 'px-1.5')}
<div className="flex-1 min-w-0 flex items-center gap-2 ps-4 pe-1.5">
{mode === 'replyAll'
? <ReplyAll className="w-4 h-4 text-muted-foreground flex-shrink-0" />
: mode === 'forward'
? <Forward className="w-4 h-4 text-muted-foreground flex-shrink-0" />
: <Reply className="w-4 h-4 text-muted-foreground flex-shrink-0" />}
<h3 className="flex-1 min-w-0 truncate text-sm" data-testid="composer-save-status" data-status={saveStatus}>
{mode === 'reply' ? t('reply') : mode === 'replyAll' ? t('reply_all') : mode === 'forward' ? t('forward') : t('new_message')}
</h3>
{saveStatus === 'saving' && <Save className="w-3.5 h-3.5 animate-pulse text-muted-foreground flex-shrink-0" aria-label={t('saving')} />}
{leftPanelToggle}
{rightPanelToggle}
{!rightPanelOpen && mvInlineButtons}
</div>
{panelHead('right', 'ps-1.5 pe-1.5', mvInlineButtons, 'gap-2')}
</div>
) : mvWindow ? (
<div
className={cn(
"flex items-center gap-1 h-10 ps-4 pe-1.5 shrink-0 bg-[var(--mv-search-bg)]",
"flex items-stretch h-10 shrink-0 bg-[var(--mv-search-bg)]",
mvWindow.state === "minimized" && "cursor-pointer",
)}
data-mv-compose-titlebar=""
onClick={mvWindow.state === "minimized" ? () => mvWindow.setState("normal") : undefined}
{...headerDropProps}
>
<h3 className="flex-1 min-w-0 truncate text-sm font-medium" data-testid="composer-save-status" data-status={saveStatus}>
{mode === 'reply' || mode === 'replyAll' || mode === 'forward'
? (subject || t('new_message'))
: t('new_message')}
</h3>
{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"); }}
className="grid h-7 w-7 place-items-center rounded-full text-muted-foreground hover:bg-foreground/10 hover:text-foreground"
aria-label={mvWindow.state === "minimized" ? t("restore") : t("minimize")}
title={mvWindow.state === "minimized" ? t("restore") : t("minimize")}
>
<Minus className="h-4 w-4" />
</button>
<button
type="button"
onClick={(e) => { e.stopPropagation(); mvWindow.setState(mvWindow.state === "maximized" ? "normal" : "maximized"); }}
className="grid h-7 w-7 place-items-center rounded-full text-muted-foreground hover:bg-foreground/10 hover:text-foreground"
aria-label={mvWindow.state === "maximized" ? t("restore") : t("maximize")}
title={mvWindow.state === "maximized" ? t("restore") : t("maximize")}
>
{mvWindow.state === "maximized" ? <Minimize2 className="h-4 w-4" /> : <Maximize2 className="h-4 w-4" />}
</button>
<button
type="button"
onClick={(e) => { e.stopPropagation(); handleClose(); }}
className="grid h-7 w-7 place-items-center rounded-full text-muted-foreground hover:bg-foreground/10 hover:text-foreground"
aria-label={tCommon('close')}
title={tCommon('close')}
>
<X className="h-4 w-4" />
</button>
{mvWindow.state !== "minimized" && panelHead('left', 'px-1.5')}
<div className="flex-1 min-w-0 flex items-center gap-1 ps-4 pe-1.5">
<h3 className="flex-1 min-w-0 truncate text-sm font-medium" data-testid="composer-save-status" data-status={saveStatus}>
{mode === 'reply' || mode === 'replyAll' || mode === 'forward'
? (subject || t('new_message'))
: t('new_message')}
</h3>
{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" || !rightPanelOpen) && mvWindowButtons}
</div>
{mvWindow.state !== "minimized" && panelHead('right', 'ps-1.5 pe-1.5', mvWindowButtons, 'gap-1')}
</div>
) : (
<div ref={setComposerHeader} className="flex items-center gap-3 px-4 py-2 md:py-0 md:h-14 border-b bg-background shrink-0" data-composer-header="">
<div ref={setComposerHeader} className="flex items-stretch md:h-14 border-b bg-background shrink-0" data-composer-header="" {...headerDropProps}>
{panelHead('left', 'px-2')}
<div className="flex-1 min-w-0 flex items-center gap-3 px-4 py-2 md:py-0">
{closeBesideControls && composerCloseButton}
{/* The left panel's button at the start, the right one's at the end: where each panel is. */}
{/* A folded panel's Show button where the panel goes: the left one's at the start, the right one's before the window buttons. */}
{leftPanelToggle && <div className="hidden md:flex -ms-2">{leftPanelToggle}</div>}
<div className="flex-1 min-w-0 flex items-center gap-3">
<div className="flex items-center gap-2" data-testid="composer-save-status" data-status={saveStatus}>
@@ -5239,23 +5300,31 @@ export function EmailComposer({
</Button>
))}
{rightPanelToggle}
{canMaximize && (
<button
type="button"
onClick={() => setMaximized((v) => !v)}
className="hidden md:grid h-8 w-8 place-items-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground"
aria-label={maximized ? t('restore') : t('maximize')}
title={maximized ? t('restore') : t('maximize')}
data-testid="composer-maximize"
>
{maximized ? <Minimize2 className="w-4 h-4" /> : <Maximize2 className="w-4 h-4" />}
</button>
)}
{popOutButton(cn(phoneLayout ? "hidden md:grid" : "grid", "h-8 w-8 place-items-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground"), "w-4 h-4")}
{!closeBesideControls && composerCloseButton}
{!rightPanelOpen && windowButtons}
</div>
{panelHead('right', 'ps-1.5 pe-4', windowButtons, 'gap-3')}
</div>
)}
{/* The left panel, the message and the right panel, under the header. */}
<div className="flex flex-1 min-h-0 relative" data-composer-panels="">
<ComposerPluginSidebar side="left" mode={pluginSidebars.modes.left} extraProps={pluginSidebarLeftProps} width={pluginSidebars.widths.left} onWidthChange={(w) => pluginSidebars.setSideWidth('left', w)} />
<div
className="flex flex-col h-full bg-background relative flex-1 min-w-0"
onDragEnter={handleDragEnter}
onDragLeave={handleDragLeave}
onDragOver={handleDragOver}
onDrop={handleDrop}
>
{/* Drag overlay */}
{isDraggingOver && (
<div className="absolute inset-0 z-50 flex items-center justify-center bg-background/80 border-2 border-dashed border-primary rounded-lg pointer-events-none">
<div className="flex flex-col items-center gap-2 text-primary">
<Paperclip className="w-8 h-8" />
<span className="text-sm font-medium">{t('drop_files')}</span>
</div>
</div>
)}
{/* Fields + body. While pinFields holds, the fields sit outside the
body's scroll container so From/To/Cc/Bcc/Subject stay reachable
while scrolling long bodies, matching the pinned formatting toolbar
@@ -5915,14 +5984,19 @@ export function EmailComposer({
className="hidden"
accept="*/*"
/>
{(filesEnabled && composerClient?.supportsFiles?.()) || hasAttachMenuActions ? (
{recentOffered || (filesEnabled && composerClient?.supportsFiles?.()) || hasAttachMenuActions ? (
<ComposerToolbarMenu icon={Paperclip} label={t('attach')} testId="composer-attach-menu">
{(close) => <>
{/* As Outlook's: the recent files first, one click attaches one and closes. */}
{recentOffered && (
<RecentFilesMenuSection onPick={(file) => { close(); void attachRecentFile(file); }} />
)}
<ComposerToolbarMenuItem
icon={Upload}
onSelect={() => { close(); fileInputRef.current?.click(); }}
testId="composer-attach-from-device"
>
{t('attach_from_device')}
{isDesktopApp() ? tRecent('browse') : t('attach_from_device')}
</ComposerToolbarMenuItem>
{filesEnabled && composerClient?.supportsFiles?.() && (
<ComposerToolbarMenuItem
@@ -5930,7 +6004,7 @@ export function EmailComposer({
onSelect={() => { close(); setFilesPicker({ client: composerClient, accountId: composerAccountId }); }}
testId="composer-attach-from-files"
>
{t('attach_from_files')}
{isDesktopApp() ? tRecent('from_files') : t('attach_from_files')}
</ComposerToolbarMenuItem>
)}
<ComposerPluginMenuItems surface="composer-attach-menu" context={composerActionContext} onSelect={close} separator />
@@ -6330,6 +6404,7 @@ export function EmailComposer({
)}
</div>
<ComposerPluginSidebar side="right" mode={pluginSidebars.modes.right} extraProps={pluginSidebarRightProps} width={pluginSidebars.widths.right} onWidthChange={(w) => pluginSidebars.setSideWidth('right', w)} />
</div>
<ComposerSelectionMenu menu={selectionMenu} composerId={pluginComposerId} onClipboard={clipboardFromMenu} />
</div>
);
@@ -0,0 +1,88 @@
"use client";
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { useLocale, useTranslations } from "next-intl";
import { CONTEXT_MENU_ITEM_CLASS, menuLevelItems } from "@/components/ui/context-menu";
import { attachmentIcon } from "@/components/email/attachment-chips";
import { listRecentFiles, recentWhen, shortFolder } from "@/lib/desktop/recent-files";
import type { DesktopRecentFile } from "@/lib/desktop/types";
import { cn } from "@/lib/utils";
/** Only an icon the shell made: a PNG as a data: URL. */
const ICON_URL = /^data:image\/png;base64,[A-Za-z0-9+/=]+$/;
/**
* The top of the composer's Attach menu in the desktop app: the files the OS says were
* used last, as Outlook lists them. Mounted when the menu opens, from that click, which is
* what the shell asks for. Until the list is there, and when it's empty, it takes no room.
* It stays an HTML menu (data-native-menu): a native one can't show the icons and folders.
*/
export function RecentFilesMenuSection({ onPick }: { onPick: (file: DesktopRecentFile) => void }) {
const t = useTranslations("desktopAttachRecent");
const locale = useLocale();
const [files, setFiles] = useState<DesktopRecentFile[] | null>(null);
// One request per opening, also when a strict-mode remount runs the effect twice.
const request = useRef<Promise<DesktopRecentFile[]> | null>(null);
const rootRef = useRef<HTMLDivElement>(null);
useEffect(() => {
let cancelled = false;
request.current ??= listRecentFiles();
void request.current.then((list) => {
if (!cancelled) setFiles(list);
});
return () => {
cancelled = true;
};
}, []);
// The menu put the focus on its first entry before the list came. If it's still
// there, the first file takes it: the list is what comes first.
useLayoutEffect(() => {
const root = rootRef.current;
const menu = root?.closest<HTMLElement>('[role="menu"]');
if (!root || !menu || !files?.length) return;
const active = document.activeElement;
const others = menuLevelItems(menu).filter((item) => !root.contains(item));
if (active && active === others[0]) root.querySelector<HTMLElement>('[role="menuitem"]')?.focus({ preventScroll: true });
}, [files]);
const now = Date.now();
return (
<div ref={rootRef} data-native-menu="html" data-testid="composer-recent-files" hidden={!files?.length}>
{files && files.length > 0 && (
<>
<div role="presentation" className="px-3 pb-1 pt-1.5 text-xs font-medium text-muted-foreground">
{t("heading")}
</div>
{files.map((file) => {
const Fallback = attachmentIcon(null, file.name).icon;
return (
<button
key={file.id}
type="button"
role="menuitem"
title={file.path}
onClick={() => onPick(file)}
data-testid="composer-recent-file"
className={cn(CONTEXT_MENU_ITEM_CLASS, "w-[min(24rem,calc(100vw-3rem))] gap-2.5")}
>
{file.icon && ICON_URL.test(file.icon) ? (
<img src={file.icon} alt="" aria-hidden="true" draggable={false} className="h-4 w-4 shrink-0" />
) : (
<Fallback className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden="true" />
)}
<span className="min-w-0 flex-1">
<span className="block truncate">{file.name}</span>
<span className="block truncate text-xs text-muted-foreground">{shortFolder(file.folder)}</span>
</span>
<span className="shrink-0 self-start pt-0.5 text-xs text-muted-foreground">{recentWhen(file.usedAt, now, locale)}</span>
</button>
);
})}
<div role="separator" className="my-1 h-px bg-border" />
</>
)}
</div>
);
}
@@ -366,6 +366,53 @@ describe('FileBrowser', () => {
expect(drawer).not.toHaveAttribute('inert');
});
// The same drawer as Mail's folders (usability test 2026-11-04): it opened
// beside the app rail with only the file list dimmed, ignored Escape and
// left the focus on the page.
it("opens the folder drawer from the window's edge, with the whole window dimmed", () => {
renderBrowser();
const drawer = screen.getByTestId('files-sidebar-drawer');
const classes = drawer.className.split(/\s+/);
expect(classes).toEqual(expect.arrayContaining(['fixed', 'start-0', 'top-[var(--drawer-top)]', 'bottom-0']));
expect(classes).not.toContain('absolute');
tree();
expect(screen.getByTestId('drawer-scrim').className.split(/\s+/)).toEqual(expect.arrayContaining(['fixed', 'inset-0']));
});
it('takes the focus into the folder drawer, keeps Tab there and gives it back on Escape without clearing the search', () => {
renderBrowser();
const drawer = screen.getByTestId('files-sidebar-drawer');
const menu = screen.getByRole('button', { name: 'open_folder_tree' });
fireEvent.change(screen.getAllByRole('searchbox')[0], { target: { value: 'notes' } });
menu.focus();
fireEvent.click(menu);
// The folder on screen.
expect(drawer.contains(document.activeElement)).toBe(true);
expect(document.activeElement).toHaveAttribute('aria-current', 'page');
const stops = Array.from(drawer.querySelectorAll<HTMLElement>('button:not(:disabled)'));
stops.at(-1)!.focus();
fireEvent.keyDown(stops.at(-1)!, { key: 'Tab' });
expect(document.activeElement).toBe(stops[0]);
fireEvent.keyDown(document.activeElement!, { key: 'Escape' });
expect(drawer).toHaveAttribute('inert');
expect(document.activeElement).toBe(menu);
expect(screen.getAllByRole('searchbox')[0]).toHaveValue('notes');
});
it('closes the folder drawer on a click on the dimmed window and gives the focus back to the menu button', () => {
renderBrowser();
const drawer = screen.getByTestId('files-sidebar-drawer');
const menu = screen.getByRole('button', { name: 'open_folder_tree' });
menu.focus();
fireEvent.click(menu);
// A press on the scrim drops the focus to the page.
(document.activeElement as HTMLElement).blur();
fireEvent.click(screen.getByTestId('drawer-scrim'));
expect(drawer).toHaveAttribute('inert');
expect(document.activeElement).toBe(menu);
});
it("renames in a dialog that selects the name without its extension and closes on Escape", async () => {
renderBrowser({ props: { selectedResources: new Set(['notes.txt']) } });
fireEvent.keyDown(window, { key: 'F2' });
+17 -15
View File
@@ -32,6 +32,8 @@ import { INTERNAL_DRAG_TYPE, isInternalDrag, readDraggedNames } from "@/componen
import { ResizeHandle } from "@/components/layout/resize-handle";
import { AppMain } from "@/components/layout/app-landmarks";
import { useIsEmbedded } from "@/hooks/use-is-embedded";
import { useMountainViewShell } from "@/hooks/use-mountain-view-shell";
import { EdgeDrawer } from "@/components/layout/edge-drawer";
import { getDroppedFilesAndFolders } from "@/lib/webdav/drop-utils";
import { getFilePreviewKind } from "@/lib/file-preview";
import type { FileAppAction } from "@/lib/files-app-actions";
@@ -298,6 +300,7 @@ export function FileBrowser({
const isMobile = useIsMobile();
const touch = useMediaQuery("(pointer: coarse)") && isMobile;
const [narrowSidebarOpen, setNarrowSidebarOpen] = useState(false);
const closeNarrowSidebar = useCallback(() => setNarrowSidebarOpen(false), []);
useEffect(() => { if (!isNarrow) setNarrowSidebarOpen(false); }, [isNarrow]);
useEffect(() => { setNarrowSidebarOpen(false); }, [currentPath]);
// Anything picked in the drawer closes it (R7).
@@ -844,6 +847,8 @@ export function FileBrowser({
return;
}
if (e.key === "Escape") {
// The folder drawer is the innermost layer; it closes itself (R8).
if (narrowSidebarOpen) return;
// The details panel over the list closes first (innermost layer, R8).
if (showDetails && isNarrow) toggleDetails(false);
else if (searchQuery) setSearchQuery("");
@@ -906,7 +911,7 @@ export function FileBrowser({
return () => window.removeEventListener("keydown", handler);
}, [
showNewFolder, showNewTextFile, renameTarget, renameFolder, shareTargetId, moveTarget, accountPickerMode, selectedList, singleSelected, inTrash,
showDetails, isNarrow, toggleDetails,
showDetails, isNarrow, toggleDetails, narrowSidebarOpen,
selectAllVisible, onCopy, onCut, onPaste, clipboard, searchQuery, onClearSelection, deleteNames, openResource,
focusedName, onToggleSelect, currentPath, navigateUp, viewMode, gridColumns, moveFocus, displayResources,
]);
@@ -1107,6 +1112,8 @@ export function FileBrowser({
const tSidebar = useTranslations("sidebar");
const tShell = useTranslations("shell");
const isEmbedded = useIsEmbedded();
// Mountain View's card holds the drawer, under its top bar.
const mvShell = useMountainViewShell(isEmbedded);
useRegisterCommands(tSidebar("files"), [
{ id: "upload-files", label: tMenu("files_upload_files"), icon: Upload, run: () => fileInputRef.current?.click(), when: () => canCreate },
{ id: "upload-folder", label: tMenu("files_upload_folder"), icon: FolderUp, run: () => folderInputRef.current?.click(), when: () => canCreate },
@@ -1312,26 +1319,21 @@ export function FileBrowser({
} : null;
return (
// Clips the closed drawer, so it never sits over the nav rail.
// Holds the drawer in a Pro pane and clips it there when closed.
<div className="relative flex flex-1 min-h-0 overflow-hidden">
{/* Folder sidebar: in flow on desktop, a drawer on narrow panes */}
{sidebar && isNarrow && narrowSidebarOpen && (
<div className="absolute inset-0 bg-black/50 z-40" onClick={() => setNarrowSidebarOpen(false)} />
)}
{/* Folder sidebar: in flow on the full desktop; below it a drawer from
the window's edge, over the app rail, as Mail's folders. */}
{sidebar && (isNarrow ? (
<div
<EdgeDrawer
open={narrowSidebarOpen}
onClose={closeNarrowSidebar}
contained={isEmbedded || mvShell}
data-testid="files-sidebar-drawer"
data-pane="sidebar"
className={cn(
"absolute inset-y-0 start-0 z-50 w-72 border-e border-border",
"transform transition-[transform,visibility] duration-300 ease-in-out",
!narrowSidebarOpen && "invisible -translate-x-full rtl:translate-x-full",
)}
// Closed, the drawer is out of reach: no clicks, no Tab stops.
inert={!narrowSidebarOpen}
className="border-e border-border"
>
{sidebar}
</div>
</EdgeDrawer>
) : (
<>
<div
@@ -0,0 +1,65 @@
import { useState } from 'react';
import { act, fireEvent, render, screen } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
import { EdgeDrawer } from '../edge-drawer';
// The drawer Calendar, Contacts and Files open below the full desktop, with
// the keyboard side Mail's phone drawer uses too (useEdgeDrawer).
function Harness({ contained = false, onPickFocus }: { contained?: boolean; onPickFocus?: () => void }) {
const [open, setOpen] = useState(false);
return (
<>
<button type="button" onClick={() => setOpen(true)}>menu</button>
<input aria-label="elsewhere" />
<EdgeDrawer open={open} onClose={() => setOpen(false)} contained={contained} data-testid="drawer">
<button type="button">first</button>
<button type="button" aria-current="true">current</button>
<button type="button" onClick={() => { setOpen(false); onPickFocus?.(); }}>pick</button>
</EdgeDrawer>
</>
);
}
describe('EdgeDrawer', () => {
it('opens on the current item and gives the focus back to the opener after a pick', () => {
render(<Harness />);
const menu = screen.getByText('menu');
menu.focus();
fireEvent.click(menu);
expect(document.activeElement).toBe(screen.getByText('current'));
fireEvent.click(screen.getByText('pick'));
expect(screen.getByTestId('drawer')).toHaveAttribute('inert');
expect(document.activeElement).toBe(menu);
});
// Seen in the desktop app: with visibility in the opening transition the
// panel is still hidden in its first frame and refuses the focus.
it('is visible from its first frame when it opens, and hidden only after sliding out', () => {
render(<Harness />);
const classes = () => screen.getByTestId('drawer').className.split(/\s+/);
expect(classes()).toContain('transition-[transform,visibility]');
fireEvent.click(screen.getByText('menu'));
expect(classes()).toContain('transition-transform');
expect(classes()).not.toContain('transition-[transform,visibility]');
expect(classes()).not.toContain('invisible');
});
it('leaves the focus where a pick moved it, outside the drawer', () => {
render(<Harness onPickFocus={() => screen.getByLabelText('elsewhere').focus()} />);
const menu = screen.getByText('menu');
menu.focus();
fireEvent.click(menu);
act(() => fireEvent.click(screen.getByText('pick')));
expect(document.activeElement).toBe(screen.getByLabelText('elsewhere'));
});
it('stays inside a Pro pane: at the pane\'s edge, with only the pane dimmed', () => {
render(<Harness contained />);
fireEvent.click(screen.getByText('menu'));
const classes = screen.getByTestId('drawer').className.split(/\s+/);
expect(classes).toEqual(expect.arrayContaining(['absolute', 'inset-y-0', 'start-0']));
expect(classes).not.toContain('fixed');
expect(screen.getByTestId('drawer-scrim').className.split(/\s+/)).toContain('absolute');
});
});
@@ -0,0 +1,224 @@
import { act, render, screen, fireEvent, cleanup } from '@testing-library/react';
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import type { Mailbox } from '@/lib/jmap/types';
// The folded folder column (600 to 1024 px) of a mailbox with many folders,
// scrolled: shared accounts left only their headings' rules behind, stacked
// into a ladder of lines; the unread counter sat on the icon; one folder of
// one's own was a letter in a box; and the drawer a hover opened kept the
// column's scroll offset, so the hovered folder was somewhere else.
vi.mock('@/components/plugins/plugin-slot', () => ({ PluginSlot: () => null }));
vi.mock('@/components/tour/tour-provider', () => ({
useTour: () => ({ startTour: vi.fn(), resetTourCompletion: vi.fn(), activeTour: null, endTour: vi.fn(), registerStep: vi.fn() }),
}));
vi.mock('@/contexts/drag-drop-context', () => ({
useDragDropContext: () => ({ isDragging: false }),
}));
vi.mock('@/hooks/use-mailbox-drop', () => ({
useMailboxDrop: () => ({ dropHandlers: {}, isValidDropTarget: false, isInvalidDropTarget: false }),
}));
vi.mock('@/hooks/use-tag-drop', () => ({
useTagDrop: () => ({ dropHandlers: {}, isValidDropTarget: false }),
}));
vi.mock('../account-switcher', () => ({ AccountSwitcher: () => null }));
const { Sidebar } = await import('../sidebar');
const { useAuthStore } = await import('@/stores/auth-store');
const { useSettingsStore } = await import('@/stores/settings-store');
const { useUIStore } = await import('@/stores/ui-store');
const box = (id: string, name: string, role: string | null, extra: Partial<Mailbox> = {}) => ({
id, name, role, parentId: null, totalEmails: 0, unreadEmails: 0, myRights: { mayAddItems: true }, ...extra,
}) as unknown as Mailbox;
const shared = (id: string, name: string, role: string | null, extra: Partial<Mailbox> = {}) =>
box(`g1:${id}`, name, role, { originalId: id, accountId: 'g1', accountName: 'Sam Ortega', isShared: true, ...extra });
const own = [
box('inbox', 'Inbox', 'inbox', { totalEmails: 120, unreadEmails: 9 }),
box('clients', 'Clients', null, { parentId: 'inbox', unreadEmails: 132 }),
box('trash', 'Trash', 'trash', { unreadEmails: 3 }),
box('news', 'Newsletters', null, { unreadEmails: 150 }),
];
// A shared account without an inbox: two folders someone shared.
const sharedNoInbox = [shared('team', 'Team', null, { unreadEmails: 2 }), shared('board', 'Board', null, { unreadEmails: 1 })];
const nav = () => document.querySelector<HTMLElement>('[data-folder-nav]')!;
const drawer = () => document.querySelector<HTMLElement>('[data-folder-drawer]');
const row = (key: string) => document.querySelector<HTMLElement>(`[data-rail-key="${key}"]`)!;
const railButtons = () => Array.from(nav().querySelectorAll<HTMLElement>('[data-testid="folder-row"] > button'));
describe('the folded folder column with many folders', () => {
beforeEach(() => {
localStorage.clear();
useAuthStore.setState({ activeAccountId: 'login-a', client: { getAccountId: () => 'me', getCapabilities: () => ({}) } } as never);
useSettingsStore.setState({
hideAccountSwitcher: true, interfaceLayout: 'default', openOnHover: true, unreadCountStyle: 'count',
showSharedMailAccounts: true, hiddenSharedMailAccounts: {}, compactSharedMailboxes: false,
} as never);
useUIStore.setState({ sidebarCollapsed: true, compactSidebarExpanded: false } as never);
});
afterEach(() => {
cleanup();
vi.useRealTimers();
vi.restoreAllMocks();
useUIStore.setState({ sidebarCollapsed: false } as never);
});
it('draws one rule between sections, never two in a row', () => {
render(<Sidebar mailboxes={[...own, ...sharedNoInbox]} selectedMailbox="inbox" />);
// Folders, Your folders, Shared (with its account inside), Tags.
const rules = nav().querySelectorAll('[data-rail-separator]');
expect(rules).toHaveLength(2 + 1);
// Walk the column in order: something to click between any two rules.
const order = Array.from(nav().querySelectorAll('[data-rail-separator], [data-testid="folder-row"]'));
order.forEach((el, i) => {
if (i === 0) return;
const both = el.hasAttribute('data-rail-separator') && order[i - 1].hasAttribute('data-rail-separator');
expect(both, `two rules in a row at ${i}`).toBe(false);
});
});
it('lists a shared account as one item, which opens the drawer with it unfolded when it has no inbox', () => {
render(<Sidebar mailboxes={[...own, ...sharedNoInbox]} selectedMailbox="inbox" />);
const item = row('shared-account-g1');
expect(item.getAttribute('data-testid')).toBe('folder-row');
const button = item.querySelector('button')!;
expect(button.getAttribute('title')).toBe('name_unread');
expect(item.querySelector('[data-testid="folded-unread"]')?.textContent).toBe('3');
fireEvent.click(button);
expect(drawer()).not.toBeNull();
expect(screen.getByText('Team')).toBeTruthy();
});
it('opens a shared account\'s inbox from its item, and marks it while one of its folders is open', () => {
const onMailboxSelect = vi.fn();
const mailboxes = [...own, shared('in', 'Inbox', 'inbox', { unreadEmails: 4 }), ...sharedNoInbox];
const { rerender } = render(<Sidebar mailboxes={mailboxes} selectedMailbox="inbox" onMailboxSelect={onMailboxSelect} />);
fireEvent.click(row('shared-account-g1').querySelector('button')!);
expect(onMailboxSelect).toHaveBeenCalledWith('g1:in');
rerender(<Sidebar mailboxes={mailboxes} selectedMailbox="g1:team" onMailboxSelect={onMailboxSelect} />);
expect(row('shared-account-g1').querySelector('[data-testid="folded-selected"]')).not.toBeNull();
});
it('puts the counter at the icon\'s corner, beside the glyph, and says 99+ for more', () => {
render(<Sidebar mailboxes={own} selectedMailbox="inbox" />);
const badge = row('trash').querySelector<HTMLElement>('[data-testid="folded-unread"]')!;
expect(badge.textContent).toBe('3');
// On the 36px item, above the 16px icon's box, not inside it over the glyph.
expect(badge.parentElement!.tagName).toBe('BUTTON');
expect(badge.parentElement!.className).toContain('h-9');
expect(badge.className.split(/\s+/)).toEqual(expect.arrayContaining(['absolute', 'top-0', 'end-0', 'h-3']));
expect(badge.className).not.toContain('ring-2');
expect(row('news').querySelector('[data-testid="folded-unread"]')!.textContent).toBe('99+');
});
it('gives every item a tooltip with its name and count', () => {
render(<Sidebar mailboxes={[...own, ...sharedNoInbox]} selectedMailbox="inbox" />);
for (const button of railButtons()) {
const title = button.getAttribute('title');
expect(title, button.outerHTML.slice(0, 120)).toBeTruthy();
expect(title).toBe(button.getAttribute('aria-label'));
}
// With unread mail the name carries the count.
expect(row('inbox').querySelector('button')!.getAttribute('title')).toBe('name_unread');
});
it('draws one folder of one\'s own as a plain folder, several with their first letter inside the folder', () => {
render(<Sidebar mailboxes={own} selectedMailbox="inbox" />);
expect(row('news').querySelector('[data-testid="folder-initial"]')).toBeNull();
expect(row('news').querySelector('svg')).not.toBeNull();
cleanup();
render(<Sidebar mailboxes={[...own, box('receipts', 'receipts', null)]} selectedMailbox="inbox" />);
const letter = row('receipts').querySelector('[data-testid="folder-initial"]')!;
expect(letter.textContent).toBe('R');
// Inside the folder glyph, an icon like the others, not a box of its own.
expect(letter.closest('svg')?.querySelector('path')).not.toBeNull();
expect(letter.closest('svg')!.getAttribute('class')).toContain('w-4');
});
it('marks the open folder with a bar at the edge and a filled item', () => {
render(<Sidebar mailboxes={own} selectedMailbox="trash" />);
// Over the filled item, not under it.
expect(row('trash').querySelector('[data-testid="folded-selected"]')!.className).toContain('z-10');
expect(row('trash').querySelector('button')!.className).toContain('bg-accent');
expect(row('inbox').querySelector('[data-testid="folded-selected"]')).toBeNull();
expect(row('inbox').querySelector('button')!.className).not.toContain('bg-accent');
});
it('scrolls on its own, never sideways, with a thin scrollbar', () => {
render(<Sidebar mailboxes={own} selectedMailbox="inbox" />);
expect(nav().hasAttribute('data-folder-rail')).toBe(true);
expect(nav().className.split(/\s+/)).toEqual(expect.arrayContaining(['overflow-y-auto', 'overflow-x-hidden', 'min-h-0']));
});
it('moves through the items with the arrows, Home and End', () => {
render(<Sidebar mailboxes={[...own, ...sharedNoInbox]} selectedMailbox="inbox" />);
const buttons = railButtons().filter((b) => !(b as HTMLButtonElement).disabled);
buttons[0].focus();
fireEvent.keyDown(buttons[0], { key: 'ArrowDown' });
expect(document.activeElement).toBe(buttons[1]);
fireEvent.keyDown(buttons[1], { key: 'ArrowUp' });
expect(document.activeElement).toBe(buttons[0]);
fireEvent.keyDown(buttons[0], { key: 'End' });
expect(document.activeElement).toBe(buttons[buttons.length - 1]);
fireEvent.keyDown(buttons[buttons.length - 1], { key: 'Home' });
expect(document.activeElement).toBe(buttons[0]);
});
describe('the drawer opened from the scrolled column', () => {
// jsdom has no layout: the list's items sit at fixed places in the
// content, further down in the longer tree of the drawer.
let scrollTop = 0;
const NAV_TOP = 100;
const place = (el: Element) => {
const key = (el as HTMLElement).dataset?.railKey;
if (key !== 'news') return null;
return drawer() ? 900 : 500;
};
beforeEach(() => {
scrollTop = 0;
vi.spyOn(Element.prototype, 'getBoundingClientRect').mockImplementation(function (this: Element) {
// The list shows 600px; anything else is somewhere inside it.
const isNav = this.hasAttribute('data-folder-nav');
const at = place(this);
const top = isNav ? NAV_TOP : at === null ? NAV_TOP + 10 : NAV_TOP + at - scrollTop;
const height = isNav ? 600 : 36;
return { top, bottom: top + height, left: 0, right: 48, width: 48, height, x: 0, y: top, toJSON: () => ({}) } as DOMRect;
});
});
const trackScroll = () => Object.defineProperty(nav(), 'scrollTop', {
configurable: true,
get: () => scrollTop,
set: (v: number) => { scrollTop = v; },
});
it('puts the hovered item back under the pointer, and the column back where it was', () => {
vi.useFakeTimers();
const { container } = render(<Sidebar mailboxes={own} selectedMailbox="inbox" />);
trackScroll();
scrollTop = 200;
const news = row('news');
document.elementFromPoint = vi.fn(() => news.querySelector('button'));
// At 400 on screen in the column: 100 + 500 - 200.
fireEvent.mouseEnter(container.firstElementChild!, { clientX: 20, clientY: 410 });
act(() => { vi.advanceTimersByTime(400); });
expect(drawer()).not.toBeNull();
// In the drawer it is 900 down the list: scrolled so it is at 400 again.
expect(scrollTop).toBe(600);
fireEvent.mouseLeave(container.firstElementChild!);
expect(drawer()).toBeNull();
expect(scrollTop).toBe(200);
});
it('starts at the top when All folders opens it', () => {
render(<Sidebar mailboxes={own} selectedMailbox="inbox" />);
trackScroll();
scrollTop = 200;
fireEvent.click(screen.getByTestId('folded-all-folders'));
expect(drawer()).not.toBeNull();
expect(scrollTop).toBe(0);
});
});
});
+76
View File
@@ -0,0 +1,76 @@
"use client";
import type { HTMLAttributes, ReactNode } from "react";
import { cn } from "@/lib/utils";
import { useEdgeDrawer } from "@/hooks/use-edge-drawer";
interface DrawerScrimProps {
onClose: () => void;
/** In a Pro pane: dims the pane only, not the other one beside it. */
contained?: boolean;
className?: string;
"data-testid"?: string;
}
/**
* The dimmed page behind a drawer. A click on it closes the drawer; the
* click, not the press, so it can't go through to what is under it.
*/
export function DrawerScrim({ onClose, contained, className, "data-testid": testId = "drawer-scrim" }: DrawerScrimProps) {
return (
<div
aria-hidden="true"
data-testid={testId}
data-drawer-scrim=""
className={cn("inset-0 bg-black/50 z-40", contained ? "absolute" : "fixed", className)}
onClick={() => onClose()}
/>
);
}
interface EdgeDrawerProps extends Omit<HTMLAttributes<HTMLDivElement>, "children"> {
open: boolean;
onClose: () => void;
/**
* In a Pro pane or Mountain View's card: at the start edge of the nearest
* positioned box instead of the window's.
*/
contained?: boolean;
/** Where the focus goes back to when the opener is gone by then. */
returnFocus?: () => HTMLElement | null | undefined;
children: ReactNode;
}
/**
* A sidebar opened over the page below the full desktop, as Mail's folders
* do: from the window's start edge (the right in RTL), over the app rail,
* from under the top bar and the window's controls (--drawer-top) to the
* bottom, with the page dimmed behind it. Keyboard and focus: useEdgeDrawer.
* Closed, it is off-screen and out of reach: no clicks, no Tab stops.
*/
export function EdgeDrawer({ open, onClose, contained, returnFocus, className, children, ...rest }: EdgeDrawerProps) {
const ref = useEdgeDrawer({ open, onClose, returnFocus });
return (
<>
{open && <DrawerScrim onClose={onClose} contained={contained} />}
<div
{...rest}
ref={ref}
data-edge-drawer=""
inert={!open}
className={cn(
"z-50 w-72 max-w-[85%] flex flex-col",
contained ? "absolute inset-y-0 start-0" : "fixed start-0 top-[var(--drawer-top)] bottom-0",
"transform duration-300 ease-in-out",
// Visible at once on opening, so the focus can go in straight away
// (a visibility transition keeps it hidden for that first frame);
// hidden only once it has slid out on closing.
open ? "shadow-xl transition-transform" : "invisible -translate-x-full rtl:translate-x-full transition-[transform,visibility]",
className
)}
>
{children}
</div>
</>
);
}
+215 -40
View File
@@ -1,7 +1,7 @@
"use client";
import { hoverOpens } from "@/lib/open-on-hover";
import { memo, useState, useEffect, useMemo, useCallback, useRef, useId, Fragment, ReactNode } from "react";
import { memo, useState, useEffect, useLayoutEffect, useMemo, useCallback, useRef, useId, Fragment, ReactNode } from "react";
import { useTranslations } from "next-intl";
import { useRouter } from "@/i18n/navigation";
import { PluginSlot } from "@/components/plugins/plugin-slot";
@@ -396,6 +396,9 @@ interface SidebarRowProps {
testName?: string;
testMailboxId?: string;
testShared?: boolean;
/** Names the row the same folded and unfolded, so the drawer opened by a
* hover can put the hovered item back under the pointer. */
railKey?: string;
}
function SidebarRow({
@@ -420,6 +423,7 @@ function SidebarRow({
testName,
testMailboxId,
testShared,
railKey,
}: SidebarRowProps) {
const t = useTranslations('sidebar');
const tShell = useTranslations('shell');
@@ -436,6 +440,8 @@ function SidebarRow({
unread, total, role: testRole, mode: countMode, showTotalGlobally: showFolderTotalCount, mountainView,
}).unread;
const accessibleName = unreadForName > 0 ? tShell('name_unread', { name: label, count: unreadForName }) : undefined;
// The default layout's folded column: one grid of square items.
const railItem = isCollapsed && !mountainView;
const [labelRef, shortenedLabel] = useShortenedText(labelCandidates ?? [label]);
// Touch has no right-click: a long-press opens the same menu (R7), and a
// ⋮ shows it too.
@@ -473,21 +479,31 @@ function SidebarRow({
data-shared={testShared ? 'true' : undefined}
data-selected={isSelected ? 'true' : undefined}
data-has-unread={(unread ?? 0) > 0 && testRole !== 'drafts' ? '' : undefined}
style={{ paddingBlock: 'var(--density-sidebar-py)' }}
data-rail-key={railKey ?? testMailboxId ?? undefined}
style={railItem ? undefined : { paddingBlock: 'var(--density-sidebar-py)' }}
className={cn(
"group w-full flex items-center tap:min-h-[44px] text-sm transition-colors duration-150",
isCollapsed ? "justify-center px-1" : "pe-2",
// Folded, every item is the same square on one grid, as in Outlook's
// folded pane: the button carries the hover and the selection, and a
// bar at the column's edge marks the open one.
// Mountain View's 72px rail keeps its own pill rows (globals.css).
railItem ? "relative justify-center py-px" : isCollapsed ? "justify-center px-1" : "pe-2",
openFromRow && "cursor-pointer select-none",
isVirtual
? "text-muted-foreground"
: isSelected
? "bg-accent text-accent-foreground font-semibold border-s-2 border-primary"
: "hover:bg-muted/50 text-foreground border-s-2 border-transparent",
railItem
? (isVirtual ? "text-muted-foreground" : isSelected ? "text-accent-foreground font-semibold" : "text-foreground")
: isVirtual
? "text-muted-foreground"
: isSelected
? "bg-accent text-accent-foreground font-semibold border-s-2 border-primary"
: "hover:bg-muted/50 text-foreground border-s-2 border-transparent",
// Only a folder that takes the drop lights up. Elsewhere the pointer
// says no (dropEffect none), as in a native mail client.
isValidDropTarget && "bg-primary/20 ring-2 ring-primary ring-inset"
)}
>
{railItem && isSelected && (
<span aria-hidden="true" data-testid="folded-selected" className="absolute z-10 start-0 top-1/2 -translate-y-1/2 h-5 w-[0.1875rem] rounded-e-full bg-primary" />
)}
{!isCollapsed && (
<div
className="flex items-center flex-shrink-0"
@@ -528,28 +544,36 @@ function SidebarRow({
aria-describedby={muted && !isCollapsed ? mutedId : undefined}
className={cn(
"flex items-center gap-2 min-w-0 transition-colors",
isCollapsed ? "justify-center" : "flex-1 text-start",
railItem
? cn(
// 36px high: the icon sits 10px down, under the counter's
// 12px, so the counter never covers the glyph.
"relative justify-center w-full max-w-10 h-9 rounded-md focus-visible:outline-2 focus-visible:outline-ring focus-visible:-outline-offset-2",
!isVirtual && (isSelected ? "bg-accent" : "hover:bg-muted/60"),
)
: isCollapsed ? "relative justify-center w-10 h-8" : "flex-1 text-start",
isVirtual && "cursor-default select-none"
)}
title={isCollapsed ? label : undefined}
// Folded, the name and count are only in the tooltip.
title={isCollapsed ? (accessibleName ?? label) : undefined}
>
<span className="relative flex items-center justify-center flex-shrink-0 w-4 h-4">
{icon}
{/* Folded to icons, the count rides on the icon (p2-9); the name says it already. */}
{isCollapsed && unreadForName > 0 && (
unreadCountStyle === 'dot' ? (
<span aria-hidden="true" data-testid="folded-unread" className="absolute -top-0.5 -end-1 w-2 h-2 rounded-full bg-primary ring-2 ring-secondary" />
) : (
<span
aria-hidden="true"
data-testid="folded-unread"
className="absolute -top-2 -end-3 min-w-4 h-4 px-1 rounded-full bg-primary text-primary-foreground text-[0.625rem] leading-4 font-semibold tabular-nums text-center ring-2 ring-secondary"
>
{unreadForName > 99 ? '99+' : unreadForName}
</span>
)
)}
</span>
{/* Folded to icons, a small counter at the icon's top corner (p2-9); the name says it already. */}
{isCollapsed && unreadForName > 0 && (
unreadCountStyle === 'dot' ? (
<span aria-hidden="true" data-testid="folded-unread" className="absolute top-1.5 end-1.5 w-1.5 h-1.5 rounded-full bg-primary" />
) : (
<span
aria-hidden="true"
data-testid="folded-unread"
className="absolute top-0 end-0 min-w-3 h-3 px-[0.1875rem] rounded-full bg-primary text-primary-foreground text-[0.5625rem] leading-3 font-semibold tabular-nums text-center"
>
{unreadForName > 99 ? '99+' : unreadForName}
</span>
)
)}
{!isCollapsed && (
<>
<span
@@ -598,20 +622,52 @@ function SidebarRow({
);
}
/** A folder of one's own on the folded strip: its first letter in a small box. */
/**
* A folder of one's own on the folded strip, when there are several: the
* folder glyph the other rows use, same size and stroke, with the folder's
* first letter inside it. A letter in a box of its own looked like no other
* icon in the column.
*/
function FolderInitial({ name, className }: { name: string; className?: string }) {
const initial = Array.from(name.trim())[0]?.toLocaleUpperCase() ?? '?';
return (
<span
<svg
aria-hidden="true"
data-testid="folder-initial"
className={cn(className, "grid place-items-center rounded-[0.25rem] border border-current text-[0.625rem] font-semibold leading-none")}
data-testid="folder-initial-icon"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth={2}
strokeLinecap="round"
strokeLinejoin="round"
className={className}
>
{initial}
</span>
{/* Lucide's folder outline. */}
<path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z" />
<text
data-testid="folder-initial"
x="12"
y="13"
textAnchor="middle"
dominantBaseline="central"
fill="currentColor"
stroke="none"
fontSize="10"
fontWeight="700"
>
{initial}
</text>
</svg>
);
}
/** Whether the folder `id` is this node or below it. */
const subtreeHas = (node: MailboxNode, id: string): boolean =>
node.id === id || node.children.some((child) => subtreeHas(child, id));
/** Unread mail in the folders below a node (a shared account counts nothing itself). */
const subtreeUnread = (node: MailboxNode): number =>
node.children.reduce((sum, child) => sum + (child.unreadEmails ?? 0) + subtreeUnread(child), 0);
/** A folder the server gave a role (inbox, sent, trash...), as opposed to one the user made. */
const isSystemFolder = (node: MailboxNode) => !!node.role;
/** Key of the single-account "Your folders" section in the collapsed set. */
@@ -634,6 +690,7 @@ function SidebarSectionHeader({
status,
onAdd,
addTitle,
railKey,
}: {
label: string;
expanded: boolean;
@@ -650,9 +707,14 @@ function SidebarSectionHeader({
onContextMenu?: (event: React.MouseEvent) => void;
/** A short note after the label, e.g. how many accounts have loaded. */
status?: ReactNode;
/** The folded column's item for the same thing (see SidebarRow). */
railKey?: string;
}) {
if (isCollapsed) {
return first ? null : <div className="h-px bg-border/50 mx-2 my-2" aria-hidden />;
// One thin rule between sections. A sub-section (a shared account, the
// folders inside a Pro account group) draws none: under a section's own
// rule they stacked into a ladder of lines.
return first || sub ? null : <div className="h-px bg-border mx-2.5 my-1.5" data-rail-separator="" aria-hidden />;
}
const paddingY = sub ? "pt-2" : first ? "pt-3" : "pt-5";
@@ -670,6 +732,7 @@ function SidebarSectionHeader({
return (
<div
onContextMenu={onContextMenu}
data-rail-key={railKey}
className={cn(
"group w-full flex items-center pb-1 select-none rounded-sm hover:bg-muted/40 transition-colors",
paddingX,
@@ -740,6 +803,7 @@ function MailboxTreeItem({
pickOnly = false,
sharedAccountName,
renderAfterChild,
initials = false,
}: {
node: MailboxNode;
selectedMailbox: string;
@@ -763,19 +827,23 @@ function MailboxTreeItem({
/** Rendered after each direct child's subtree, e.g. the Scheduled row after
* Drafts. Not passed further down. */
renderAfterChild?: (child: MailboxNode) => React.ReactNode;
/** Folded: several folders of one's own are listed, so each carries its
* first letter. One alone is a plain folder. */
initials?: boolean;
}) {
const tNotifications = useTranslations('notifications');
const tListExtra = useTranslations('mail_list_extra');
const tSidebar = useTranslations('sidebar');
const hasChildren = node.children.length > 0;
const isExpanded = expandedFolders.has(node.id);
const Icon = sharedAccountName ? User : getIconForMailbox(node.role, hasChildren, isExpanded, node.id);
// Folded, no subfolders show, so no folder is drawn open.
const Icon = sharedAccountName ? User : getIconForMailbox(node.role, hasChildren, isExpanded && !isCollapsed, node.id);
const isVirtualNode = node.id.startsWith('shared-');
const isSelected = selectedMailbox === node.id;
const label = sharedAccountName ?? localizeMailboxName(node.role, node.name, (k) => tSidebar(`mailboxes.${k}`));
// Folded to icons, eight folders of one's own were eight identical folder
// icons (p2-9): each shows its first letter instead.
const letterIcon = isCollapsed && !node.role && !sharedAccountName && !isVirtualNode;
// icons (p2-9): each carries its first letter inside the folder glyph.
const letterIcon = isCollapsed && initials && !node.role && !sharedAccountName && !isVirtualNode;
// Only for the active login's folders: its client tells a missing
// accountId (own mailbox) apart.
const muted = useMutedMailbox(isVirtualNode || dragAccountId || pickOnly ? null : node);
@@ -969,6 +1037,7 @@ function TagItem({
isCollapsed={isCollapsed}
dropHandlers={globalDragging ? (dropHandlers as Record<string, unknown>) : undefined}
isValidDropTarget={isValidDropTarget}
railKey={`tag:${node.id}`}
/>
{hasChildren && isExpanded && !isCollapsed && node.children.map((child) => (
@@ -1299,9 +1368,26 @@ function SidebarImpl({
}, [railOpen]);
// The pointer resting on the folders floats the tree out; on the header
// (expand, compose) it doesn't, so the expand button can still be clicked.
const armRailHover = useCallback((target: EventTarget | null) => {
const navRef = useRef<HTMLElement>(null);
// The item the pointer rests on in the folded column, and where on screen.
const hoveredRailItem = useRef<{ key: string; top: number } | null>(null);
const lastPointer = useRef<{ x: number; y: number; target: EventTarget | null }>({ x: 0, y: 0, target: null });
// Read when the tree floats out, not when the pointer arrived: the column
// may have been scrolled under a resting pointer in between.
const noteHoveredRailItem = useCallback(() => {
const { x, y, target } = lastPointer.current;
const under = typeof document.elementFromPoint === 'function' ? document.elementFromPoint(x, y) : null;
const from = under ?? (target instanceof Element ? target : null);
const item = from?.closest<HTMLElement>('[data-rail-key]');
hoveredRailItem.current = item?.dataset.railKey && navRef.current?.contains(item)
? { key: item.dataset.railKey, top: item.getBoundingClientRect().top }
: null;
}, []);
const armRailHover = useCallback((e: React.MouseEvent) => {
if (!hoverOpens()) return;
if (mvShell) { setRailHovered(true); return; }
const target = e.target;
lastPointer.current = { x: e.clientX, y: e.clientY, target };
if (mvShell) { noteHoveredRailItem(); setRailHovered(true); return; }
if (target instanceof Element && target.closest('[data-sidebar-head]')) {
if (railHoverTimer.current) clearTimeout(railHoverTimer.current);
railHoverTimer.current = null;
@@ -1310,9 +1396,59 @@ function SidebarImpl({
if (railHoverTimer.current) return;
railHoverTimer.current = setTimeout(() => {
railHoverTimer.current = null;
noteHoveredRailItem();
setRailHovered(true);
}, RAIL_HOVER_DELAY_MS);
}, [mvShell]);
}, [mvShell, noteHoveredRailItem]);
// The folded column and the tree floated out of it share one scrolling
// list. Scrolled down the column, the tree opened at that same offset, which
// in the longer tree was somewhere else: a hover now puts the hovered item
// back under the pointer, All folders starts at the top (and the focus
// brings the open folder into view), and folding back returns the column
// to where it was.
const railScrollTop = useRef<number | null>(null);
useLayoutEffect(() => {
const nav = navRef.current;
if (!nav) return;
if (hoverExpanded) {
if (railScrollTop.current !== null) return;
railScrollTop.current = nav.scrollTop;
const hovered = railOpen ? null : hoveredRailItem.current;
const item = hovered
? Array.from(nav.querySelectorAll<HTMLElement>('[data-rail-key]')).find((el) => el.dataset.railKey === hovered.key)
: null;
nav.scrollTop = item && hovered ? nav.scrollTop + item.getBoundingClientRect().top - hovered.top : 0;
return;
}
if (railScrollTop.current === null) return;
const railTop = railScrollTop.current;
railScrollTop.current = null;
// Unfolded meanwhile: the full list keeps its own place.
if (!isCollapsed) return;
nav.scrollTop = railTop;
// A folder picked in the tree is shown in the column too.
const current = nav.querySelector<HTMLElement>('[aria-current="page"]');
if (!current) return;
const view = nav.getBoundingClientRect();
const box = current.getBoundingClientRect();
if (box.top < view.top) nav.scrollTop += box.top - view.top;
else if (box.bottom > view.bottom) nav.scrollTop += box.bottom - view.bottom;
}, [hoverExpanded, railOpen, isCollapsed]);
// Folded, the arrows, Home and End go from item to item, Enter opens.
const moveInRail = useCallback((e: React.KeyboardEvent<HTMLElement>) => {
if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp' && e.key !== 'Home' && e.key !== 'End') return;
if (e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) return;
const items = Array.from(e.currentTarget.querySelectorAll<HTMLElement>('[data-testid="folder-row"] > button:not(:disabled)'));
if (items.length === 0) return;
const at = items.indexOf(document.activeElement as HTMLElement);
const next = e.key === 'Home' ? 0
: e.key === 'End' ? items.length - 1
: at < 0 ? 0
: e.key === 'ArrowDown' ? Math.min(at + 1, items.length - 1) : Math.max(at - 1, 0);
e.preventDefault();
e.stopPropagation();
items[next].focus();
}, []);
const { primaryIdentity: _primaryIdentity, activeAccountId } = useAuthStore(useShallow((state) => ({ primaryIdentity: state.primaryIdentity, activeAccountId: state.activeAccountId })));
const [expandedFolders, setExpandedFolders] = useState<Set<string>>(new Set());
const [expandedTags, setExpandedTags] = useState<Set<string>>(new Set());
@@ -1681,6 +1817,7 @@ function SidebarImpl({
colorful={colorfulSidebarIcons}
onContextMenu={active ? handleMailboxContextMenu : undefined}
dragAccountId={dragAccountId}
initials={tree.length > 1}
/>
))}
</div>
@@ -1770,6 +1907,31 @@ function SidebarImpl({
</div>
);
}
if (isCollapsed) {
// Folded, a shared account is one item: its inbox opens, or
// without one the drawer with the account unfolded. It was
// left out, and only its heading's rule stayed behind.
const inbox = account.children.find((child) => child.role === 'inbox');
const selectedHere = !!selected && subtreeHas(account, selected);
return (
<SidebarRow
key={account.id}
icon={<User className={getIconClass(selectedHere, false, false)} />}
label={account.name}
isSelected={selectedHere}
unread={subtreeUnread(account)}
onClick={() => {
if (inbox) { onSelect?.(inbox.id); return; }
if (!expanded) onToggle();
if (!accountExpanded) toggleSharedAccount(account.id);
setRailOpen(true);
}}
isCollapsed
testShared
railKey={account.id}
/>
);
}
return (
<div key={account.id}>
<SidebarSectionHeader
@@ -1780,6 +1942,7 @@ function SidebarImpl({
sub
icon={<User className="w-3.5 h-3.5 text-muted-foreground" />}
testId="section-shared-account"
railKey={account.id}
onContextMenu={active && menuAccountId
? (e) => handleSharedAccountContextMenu(e, menuAccountId)
: undefined}
@@ -2067,8 +2230,8 @@ function SidebarImpl({
<div
ref={rootRef}
// The peek of the collapsed rail; not with hover opening turned off.
onMouseEnter={sidebarCollapsed && !isDrawer ? (e) => armRailHover(e.target) : undefined}
onMouseMove={sidebarCollapsed && !isDrawer && !mvShell && !railHovered ? (e) => armRailHover(e.target) : undefined}
onMouseEnter={sidebarCollapsed && !isDrawer ? armRailHover : undefined}
onMouseMove={sidebarCollapsed && !isDrawer && !mvShell && !railHovered ? armRailHover : undefined}
onMouseLeave={sidebarCollapsed && !isDrawer ? () => {
if (railHoverTimer.current) clearTimeout(railHoverTimer.current);
railHoverTimer.current = null;
@@ -2211,7 +2374,19 @@ function SidebarImpl({
{!isCollapsed && <VacationBanner />}
{/* Mailbox List */}
<nav aria-label={t("folders")} className="flex-1 overflow-y-auto" data-tour="sidebar" data-folder-nav="" data-pane="folders">
<nav
ref={navRef}
aria-label={t("folders")}
// Folded, the column scrolls on its own, never sideways, with a thin
// scrollbar (globals.css) and the same gutter on both sides so the
// icons stay centred under the buttons above and below it.
className={cn("flex-1 min-h-0 overflow-y-auto", isCollapsed && "overflow-x-hidden py-1 [scrollbar-gutter:stable_both-edges]")}
data-tour="sidebar"
data-folder-nav=""
data-folder-rail={isCollapsed && !mvShell ? "" : undefined}
data-pane="folders"
onKeyDown={isCollapsed ? moveInRail : undefined}
>
{unifiedSectionShown && (
<div>
<SidebarSectionHeader
+18 -35
View File
@@ -79,7 +79,8 @@ import { useContactStore } from "@/stores/contact-store";
import { useIdentityStore } from "@/stores/identity-store";
import { useUIStore, sidebarFolded, listPaneCssSize, SIDEBAR_MIN, SIDEBAR_MAX, EMAIL_LIST_MIN, EMAIL_LIST_MAX, EMAIL_LIST_HEIGHT_MIN, EMAIL_LIST_HEIGHT_MAX, READING_PANE_MIN_WIDTH, READING_PANE_MIN_HEIGHT, COMPOSER_PANE_MIN_HEIGHT } from "@/stores/ui-store";
import { atLeast, PHONE_BELOW, useDeviceDetection } from "@/hooks/use-media-query";
import { useFocusTrap } from "@/hooks/use-focus-trap";
import { useEdgeDrawer } from "@/hooks/use-edge-drawer";
import { DrawerScrim } from "@/components/layout/edge-drawer";
import { usePaneSize } from "@/hooks/use-pane-size";
import { useIsFocusedProTab, usePaneId } from "@/hooks/use-pane-context";
import { useKeyboardShortcuts, type GoToMailboxTarget } from "@/hooks/use-keyboard-shortcuts";
@@ -2621,29 +2622,18 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) {
// Pro can mount two mail panes at once, so the sidebar id must be per-instance.
const sidebarId = useId();
const listHeadingId = useId();
// The phone drawer keeps Tab inside until it closes, and Escape closes it.
// The phone drawer keeps Tab inside until it closes, Escape closes it, and
// the focus goes back to the toggle however it closes (Escape, X, a pick,
// the scrim), unless it has moved on to something outside the drawer. The
// toggle lives in whichever MobileHeader the current view renders, so it is
// looked up inside this app instance when the one that opened it is gone.
const phoneDrawerOpen = isMobile && sidebarOpen;
const sidebarContainerRef = useFocusTrap({
isActive: phoneDrawerOpen,
onEscape: () => setSidebarOpen(false),
restoreFocus: false,
const closeSidebarDrawer = useCallback(() => setSidebarOpen(false), [setSidebarOpen]);
const sidebarContainerRef = useEdgeDrawer({
open: phoneDrawerOpen,
onClose: closeSidebarDrawer,
returnFocus: () => appRootRef.current?.querySelector<HTMLElement>('[data-sidebar-toggle]'),
});
const sidebarWasOpen = useRef(false);
useEffect(() => {
if (phoneDrawerOpen) {
sidebarWasOpen.current = true;
return;
}
if (!sidebarWasOpen.current) return;
sidebarWasOpen.current = false;
// Back to the toggle however it closed (Escape, X, a pick, the scrim),
// unless the focus has moved on to something outside the drawer. The
// toggle lives in whichever MobileHeader the current view renders, so
// look it up inside this app instance rather than threading a ref through.
const active = document.activeElement;
if (active && active !== document.body && !sidebarContainerRef.current?.contains(active)) return;
appRootRef.current?.querySelector<HTMLElement>('[data-sidebar-toggle]')?.focus();
}, [phoneDrawerOpen, sidebarContainerRef]);
// The folded column's tree open over the page as a drawer (Sidebar's
// onDrawerChange): the function that closes it, for the scrim.
const [closeFolderDrawer, setCloseFolderDrawer] = useState<(() => void) | null>(null);
@@ -5890,20 +5880,13 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) {
scope to the pane via `absolute` so the backdrop stays inside
the pane instead of covering the whole window. */}
{((isMobile && sidebarOpen) || closeFolderDrawer) && !inlineApp && (
<div
aria-hidden="true"
<DrawerScrim
data-testid="folder-drawer-scrim"
data-drawer-scrim=""
className={cn(
"inset-0 bg-black/50 z-40",
// The folded column's drawer opens on a desktop, so only the
// phone's scrim goes with the phone layout.
isEmbedded ? "absolute" : cn("fixed", !closeFolderDrawer && "desk:hidden")
)}
onClick={() => {
if (closeFolderDrawer) closeFolderDrawer();
else setSidebarOpen(false);
}}
contained={isEmbedded}
// The folded column's drawer opens on a desktop, so only the
// phone's scrim goes with the phone layout.
className={!isEmbedded && !closeFolderDrawer ? "desk:hidden" : undefined}
onClose={closeFolderDrawer ?? closeSidebarDrawer}
/>
)}