Email for professionals and teams
Fix message selection and keep the focused message visible (#229)
Antonio241378130ea7
diff --git a/src/app/(dashboard)/inbox/[messageId]/page.tsx b/src/app/(dashboard)/inbox/[messageId]/page.tsxindex 058f6b0..1d43c8e 100644--- a/src/app/(dashboard)/inbox/[messageId]/page.tsx+++ b/src/app/(dashboard)/inbox/[messageId]/page.tsx@@ -5,7 +5,7 @@ import { useEffect, useState } from "react";import { Cloud, ExternalLink } from "@/components/icons";import { useLanguage } from "@/components/language-provider";import { formatUserDate } from "@/lib/time/utils";-import { MarkAsRead } from "@/components/mark-read";+import { markMessageRead } from "@/components/mark-read";import { useSelectedMailbox } from "@/components/mailbox-provider";import { ContactDetailsTrigger } from "@/components/contacts/contact-details";import { ContactAvatar } from "@/components/contacts/contact-avatar";@@ -82,6 +82,7 @@ export default function MessageDetailPage() {if (cachedData?.message && cachedData.body) {setData(cachedData);setLoading(false);+ if (!cachedData.message.read) void markMessageRead(cachedData.message.id);if (cachedData.attachments !== undefined) return;try {const metadata = await fetchMessageMetadata(messageId);@@ -96,6 +97,7 @@ export default function MessageDetailPage() {if (!cancelled) {setData(nextData);setLoading(false);+ if ("message" in nextData && nextData.message && !nextData.message.read) void markMessageRead(nextData.message.id);}}@@ -110,6 +112,22 @@ export default function MessageDetailPage() {setDetailsOpen(false);}, [messageId]);+ // A bulk read/unread action can include the message that is already open.+ // Keep the mounted reader in sync with the cache instead of remounting it.+ useEffect(() => {+ function syncCachedReadState() {+ const cached = getCachedMessageDetailForDisplay(messageId);+ if (!cached?.message) return;+ const cachedRead = cached.message.read;+ setData((current) => {+ if (!current?.message || current.message.read === cachedRead) return current;+ return { ...current, message: { ...current.message, read: cachedRead } };+ });+ }+ window.addEventListener("mailflare:messages-changed", syncCachedReadState);+ return () => window.removeEventListener("mailflare:messages-changed", syncCachedReadState);+ }, [messageId]);+if (loading) {return <MessageDetailSkeleton />;}@@ -199,8 +217,6 @@ export default function MessageDetailPage() {</div><div ref={scrollRef} onScroll={handleScroll} className="h-full overflow-y-auto overscroll-contain scrollbar-gutter-stable flex-1 min-h-0">- {!message.read && <MarkAsRead messageId={message.id} />}-<h1 className={clsx(!isAnyPanelVisible ? "sm:pl-16" : "sm:pl-10", "px-4 pb-2 pt-2 text-2xl text-neutral-900 sm:pr-6")} title={message.subject ?? t("list.noSubject")}>{message.subject ?? t("list.noSubject")}</h1>diff --git a/src/components/mark-read.ts b/src/components/mark-read.tsnew file mode 100644index 0000000..887d6de--- /dev/null+++ b/src/components/mark-read.ts@@ -0,0 +1,16 @@+"use client";++import { authFetch } from "@/lib/auth/client";+import { markMessagesReadInCaches } from "@/hooks/utils";++/** Mark a message read after it is opened, and mirror the change into client caches. */+export async function markMessageRead(messageId: string) {+ try {+ const response = await authFetch(`/api/messages/${messageId}/read`, { method: "POST" });+ if (!response.ok) return;+ markMessagesReadInCaches([messageId], true);+ window.dispatchEvent(new Event("mailflare:messages-changed"));+ } catch {+ // silently fail+ }+}diff --git a/src/components/mark-read.tsx b/src/components/mark-read.tsxdeleted file mode 100644index 3513915..0000000--- a/src/components/mark-read.tsx+++ /dev/null@@ -1,21 +0,0 @@-"use client";--import { useEffect } from "react";-import { authFetch } from "@/lib/auth/client";-import { markMessagesReadInCaches } from "@/hooks/utils";--export function MarkAsRead({ messageId }: { messageId: string }) {- useEffect(() => {- authFetch(`/api/messages/${messageId}/read`, { method: "POST" })- .then((response) => {- if (!response.ok) return;- markMessagesReadInCaches([messageId], true);- window.dispatchEvent(new Event("mailflare:messages-changed"));- })- .catch(() => {- // silently fail- });- }, [messageId]);-- return null;-}diff --git a/src/components/messages/bulk-message-selection-pane.tsx b/src/components/messages/bulk-message-action-bar.tsxsimilarity index 50%rename from src/components/messages/bulk-message-selection-pane.tsxrename to src/components/messages/bulk-message-action-bar.tsxindex 9f7fc58..0375517 100644--- a/src/components/messages/bulk-message-selection-pane.tsx+++ b/src/components/messages/bulk-message-action-bar.tsx@@ -1,19 +1,22 @@"use client";-import { CheckSquare2 } from "@/components/icons";import { useState } from "react";import type { BulkMessageAction } from "@/app/api/messages/bulk/types";import { useLanguage } from "@/components/language-provider";import { BulkMessageToolbar } from "./bulk-message-toolbar";-import type { BulkMessageSelectionPaneProps } from "./types";+import type { BulkMessageActionBarProps } from "./types";import { PartialDeleteError } from "@/lib/messages/permanent-delete-utils";import { runBulkMessageAction } from "./utils";-export function BulkMessageSelectionPane({+/**+ * Bulk actions for a selection whose messages are listed in the split-view+ * sidebar. It sits above the focused message instead of replacing it.+ */+export function BulkMessageActionBar({folder,selectedMessages,onClearSelection,-}: BulkMessageSelectionPaneProps) {+}: BulkMessageActionBarProps) {const { t } = useLanguage();const [pending, setPending] = useState(false);const [error, setError] = useState<string | null>(null);@@ -40,30 +43,22 @@ export function BulkMessageSelectionPane({}return (- <div className="flex h-full items-center justify-center p-8">- <div className="w-full max-w-xl text-center">- <div className="mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-blue-50 text-blue-700">- <CheckSquare2 className="h-6 w-6" />- </div>- <h2 className="mt-4 text-lg font-semibold text-neutral-900">- {t("common.selectedCount", { count: selectedMessages.length })}- </h2>- <p className="mt-1 text-sm text-neutral-500">- {t("common.chooseBulkAction")}- </p>- <div className="mt-5 rounded-xl border border-neutral-200 bg-white p-3 shadow-sm">- <BulkMessageToolbar- selectedCount={selectedMessages.length}- hasUnreadSelection={hasUnreadSelection}- onAction={runAction}- onClearSelection={onClearSelection}- pending={pending}- folder={folder}- hideSelectedCount- />- </div>- {error && <p role="alert" className="mt-3 text-sm font-medium text-red-700">{error}</p>}+ <div+ role="region"+ aria-label={t("common.selectedCount", { count: selectedMessages.length })}+ className="shrink-0 border-b border-blue-100 bg-blue-50/50 px-3 py-2"+ >+ <div className="min-w-0 overflow-x-auto">+ <BulkMessageToolbar+ selectedCount={selectedMessages.length}+ hasUnreadSelection={hasUnreadSelection}+ onAction={runAction}+ onClearSelection={onClearSelection}+ pending={pending}+ folder={folder}+ /></div>+ {error && <p role="alert" className="mt-1 text-sm font-medium text-red-700">{error}</p>}</div>);}diff --git a/src/components/messages/message-folder-page.tsx b/src/components/messages/message-folder-page.tsxindex 7cbcc33..c179c1c 100644--- a/src/components/messages/message-folder-page.tsx+++ b/src/components/messages/message-folder-page.tsx@@ -1,7 +1,7 @@"use client";import Link from "next/link";-import { useEffect, useMemo, useState } from "react";+import { useEffect, useMemo, useRef, useState } from "react";import type { MouseEvent } from "react";import { Archive, ChevronLeft, ChevronRight, ListFilter, Mail, MailOpen, Trash2 } from "@/components/icons";import { useLanguage } from "@/components/language-provider";@@ -19,6 +19,7 @@ import type { BulkMessageAction } from "@/app/api/messages/bulk/types";import type { Message } from "@/hooks/types";import { setMessageDragData } from "@/lib/messages/drag-utils";import { BulkMessageToolbar } from "./bulk-message-toolbar";+import { useMessageListState } from "./message-list-state";import { SwipeableRow } from "./swipeable-row";import { MessageListRowActions } from "./message-list-row-actions";import { dispatchMessageCountsDelta, toggleMessageStar } from "./message-list-row-actions-utils";@@ -301,23 +302,30 @@ export function MessageFolderPage({config,compact = false,selectedMessageId,- selection,}: MessageFolderPageProps) {const { t } = useLanguage();const title = config.titleKey ? t(config.titleKey) : config.title;const { selectedMailbox, isLoading: mailboxesLoading } = useSelectedMailbox();const { query } = useMailSearch();const isMobile = useIsMobile();- const [offset, setOffset] = useState(0);+ const listState = useMessageListState();+ const usesSharedListState = listState !== null;+ const [internalOffset, setInternalOffset] = useState(0);const [internalSelectedMessages, setInternalSelectedMessages] = useState<Array<{ id: string; read: boolean }>>([]);+ const [internalUnreadOnly, setInternalUnreadOnly] = useState(false);const [pendingBulkAction, setPendingBulkAction] = useState(false);const [emptyingFolder, setEmptyingFolder] = useState(false);const [actionError, setActionError] = useState<string | null>(null);- const [unreadOnly, setUnreadOnly] = useState(false);const [conversationView] = useConversationView();const grouped = conversationView && config.folder !== "drafts";+ const offset = listState?.offset ?? internalOffset;+ const setOffset = listState?.setOffset ?? setInternalOffset;+ const selectedMessages = listState?.selectedMessages ?? internalSelectedMessages;+ const setSelectedMessages = listState?.setSelectedMessages ?? setInternalSelectedMessages;+ const unreadOnly = listState?.unreadOnly ?? internalUnreadOnly;+ const setUnreadOnly = listState?.setUnreadOnly ?? setInternalUnreadOnly;const { messages, isLoading, total, limit, updateMessages } = useMessages(config.folder, selectedMailbox?.id, {query,limit: pageSize,@@ -337,9 +345,6 @@ export function MessageFolderPage({const mailboxAddress = getMailboxAddress(selectedMailbox);const currentAccountName = selectedMailbox?.displayName ?? selectedMailbox?.localPart;const pageRange = getPageRange(offset, messages.length, total);- const selectedMessages = selection?.selectedMessages ?? internalSelectedMessages;- const setSelectedMessages =- selection?.setSelectedMessages ?? setInternalSelectedMessages;const selectedIds = useMemo(() => selectedMessages.map((message) => message.id),[selectedMessages],@@ -352,14 +357,20 @@ export function MessageFolderPage({const expandSelectedIds = (ids: string[]) =>ids.flatMap((id) => rowMessageIds(messages.find((message) => message.id === id) ?? { id } as Message));+ // A split-layout list keeps this state in MessageSplitLayout, which resets+ // it when the list view changes. Standalone lists (drafts) own it here.useEffect(() => {+ if (usesSharedListState) return;setOffset(0);setSelectedMessages([]);- }, [query, selectedMailbox?.id, config.folder, config.folderId, unreadOnly, grouped]);+ }, [usesSharedListState, query, selectedMailbox?.id, config.folder, config.folderId, unreadOnly, grouped, setOffset, setSelectedMessages]);+ const previousOffset = useRef(offset);useEffect(() => {+ if (previousOffset.current === offset) return;+ previousOffset.current = offset;setSelectedMessages([]);- }, [offset]);+ }, [offset, setSelectedMessages]);useEffect(() => {const originalTitle = document.title;@@ -385,12 +396,12 @@ export function MessageFolderPage({const remaining = current.filter((item) => messages.some((message) => message.id === item.id));return remaining.length === current.length ? current : remaining;});- }, [messages, isLoading]);+ }, [messages, isLoading, setSelectedMessages]);useEffect(() => {if (isLoading || offset === 0 || messages.length > 0) return;setOffset(total > 0 ? Math.floor((total - 1) / limit) * limit : 0);- }, [isLoading, offset, messages.length, total, limit]);+ }, [isLoading, offset, messages.length, total, limit, setOffset]);function updateSelectedMessage(messageId: string, selected: boolean) {const message = messages.find((item) => item.id === messageId);diff --git a/src/components/messages/message-list-state.tsx b/src/components/messages/message-list-state.tsxnew file mode 100644index 0000000..65ed16a--- /dev/null+++ b/src/components/messages/message-list-state.tsx@@ -0,0 +1,15 @@+"use client";++import { createContext, useContext } from "react";+import type { MessageListStateControl } from "./types";++/**+ * List state owned by the folder layout. Opening a message swaps the+ * full-width list for the split-view list, so selection, pagination and the+ * unread filter have to leave the page that unmounts.+ */+export const MessageListStateContext = createContext<MessageListStateControl | null>(null);++export function useMessageListState() {+ return useContext(MessageListStateContext);+}diff --git a/src/components/messages/message-split-layout.tsx b/src/components/messages/message-split-layout.tsxindex 196e2af..a07940d 100644--- a/src/components/messages/message-split-layout.tsx+++ b/src/components/messages/message-split-layout.tsx@@ -1,26 +1,36 @@"use client";import { usePathname } from "next/navigation";-import { useEffect, useLayoutEffect, useRef, useState } from "react";+import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";import { useLanguage } from "@/components/language-provider";import { useSidebar } from "@/components/sidebar-state";import { useAssistantOpen } from "@/components/agent/assistant-open-state";+import { useMailSearch } from "@/components/mail-search/mail-search-context";+import { useSelectedMailbox } from "@/components/mailbox-provider";+import { useIsDesktop } from "@/components/sidebar-mobile-utils";import { readColumnWidth, readInitialColumnWidth, saveColumnWidth } from "@/components/column-width-preferences";import { ResizeHandle } from "@/components/ui/resize-handle";-import { BulkMessageSelectionPane } from "./bulk-message-selection-pane";+import { BulkMessageActionBar } from "./bulk-message-action-bar";import { MessageFolderPage } from "./message-folder-page";import { MessageDetailNavigationProvider } from "./message-detail-navigation";+import { MessageListStateContext } from "./message-list-state";import { MessageListVisibilityContext } from "./message-list-visibility";import { readInitialMessageListVisible, saveMessageListVisible } from "./message-list-visibility-utils";+import { useConversationView } from "./use-conversation-view";import { useTwoColumnReading } from "./use-two-column-reading";-import type { MessageSplitLayoutProps, SelectedMessage } from "./types";+import type { MessageListStateControl, MessageSplitLayoutProps, SelectedMessage } from "./types";export function MessageSplitLayout({children,config,}: MessageSplitLayoutProps) {const pathname = usePathname();+ const { query } = useMailSearch();+ const { selectedMailbox } = useSelectedMailbox();+ const [conversationView] = useConversationView();const [selectedMessages, setSelectedMessages] = useState<SelectedMessage[]>([]);+ const [offset, setOffset] = useState(0);+ const [unreadOnly, setUnreadOnly] = useState(false);const [listWidth, setListWidth] = useState(360);const [widthReady, setWidthReady] = useState(false);const [containerWidth, setContainerWidth] = useState(0);@@ -31,6 +41,7 @@ export function MessageSplitLayout({const resizedWidth = useRef(listWidth);const { t } = useLanguage();const { userId, setForcedMinimal } = useSidebar();+ const isDesktop = useIsDesktop();const assistantOpen = useAssistantOpen();const listVisible = twoColumnReading && !assistantOpen && manualListVisible;const detailPrefix = `${config.hrefPrefix}/`;@@ -38,6 +49,37 @@ export function MessageSplitLayout({? pathname.slice(detailPrefix.length).split("/")[0]: undefined;const renderedListWidth = Math.max(250, Math.min(listWidth, (containerWidth || 1000) - 280));+ const grouped = conversationView && config.folder !== "drafts";+ const listState = useMemo<MessageListStateControl>(() => ({+ selectedMessages,+ setSelectedMessages,+ offset,+ setOffset,+ unreadOnly,+ setUnreadOnly,+ }), [selectedMessages, offset, unreadOnly]);+ // The layout outlives the page that renders the list, so a filter change+ // resets the shared list here instead of from the page that happens to be+ // mounted. Comparing keys keeps the initial mount from wiping a selection+ // that the split view is about to show.+ const viewKey = [query, selectedMailbox?.id ?? "", config.folder, config.folderId ?? "", grouped, unreadOnly].join("\u0000");+ const previousViewKey = useRef(viewKey);+ const folderKey = `${config.folder}\u0000${config.folderId ?? ""}`;+ const previousFolderKey = useRef(folderKey);+ const showBulkBar = selectedMessages.length > 0 && twoColumnReading && isDesktop;++ useEffect(() => {+ if (previousViewKey.current === viewKey) return;+ previousViewKey.current = viewKey;+ setOffset(0);+ setSelectedMessages([]);+ }, [viewKey]);++ useEffect(() => {+ if (previousFolderKey.current === folderKey) return;+ previousFolderKey.current = folderKey;+ setUnreadOnly(false);+ }, [folderKey]);useLayoutEffect(() => {setListWidth(readInitialColumnWidth("message-list", 360, 250, 1200));@@ -68,48 +110,54 @@ export function MessageSplitLayout({useEffect(() => () => setForcedMinimal(false), [setForcedMinimal]);- if (!selectedMessageId) return children;+ if (!selectedMessageId) {+ return (+ <MessageListStateContext.Provider value={listState}>+ {children}+ </MessageListStateContext.Provider>+ );+ }return (- <div ref={containerRef} className="h-full min-h-0 overflow-hidden lg:grid lg:transition-[grid-template-columns] lg:ease-in-out motion-reduce:transition-none" style={{ gridTemplateColumns: twoColumnReading ? `${listVisible ? renderedListWidth : 0}px minmax(0,1fr)` : "minmax(0,1fr)", transitionDuration: widthReady ? "300ms" : "0ms" }}>- {twoColumnReading && (- <aside className={`relative hidden min-h-0 min-w-0 overflow-hidden bg-white lg:block ${listVisible ? "border-r border-neutral-200" : "pointer-events-none"}`} aria-hidden={!listVisible} inert={!listVisible}>- <div className={`h-full overflow-hidden transition-transform duration-300 ease-in-out motion-reduce:transition-none ${listVisible ? "translate-x-0" : "-translate-x-full"}`} style={{ width: renderedListWidth }}>- <MessageFolderPage- config={config}- compact- selectedMessageId={selectedMessageId}- selection={{ selectedMessages, setSelectedMessages }}- />- </div>- <ResizeHandle- label={t("list.resize")}- onResizeStart={() => { startWidth.current = listWidth; resizedWidth.current = listWidth; }}- onResize={(delta) => {- const requestedWidth = startWidth.current + delta;- setForcedMinimal(requestedWidth < 250);- resizedWidth.current = Math.max(250, Math.min(requestedWidth, Math.max(250, (containerRef.current?.clientWidth ?? 1000) - 280)));- setListWidth(resizedWidth.current);- }}- onResizeEnd={() => saveColumnWidth(userId, "message-list", resizedWidth.current)}- />- </aside>- )}- <MessageListVisibilityContext.Provider value={{ visible: listVisible, toggle: () => { const visible = !manualListVisible; setManualListVisible(visible); saveMessageListVisible(visible); }, singleColumn: !twoColumnReading, backHref: config.hrefPrefix, backLabel: config.titleKey ? t(config.titleKey) : config.title }}>- <MessageDetailNavigationProvider config={config}>- <section className="min-h-0 min-w-0 overflow-hidden bg-white flex flex-col h-full">- {twoColumnReading && selectedMessages.length > 0 ? (- <BulkMessageSelectionPane- folder={config.folder}- selectedMessages={selectedMessages}- onClearSelection={() => setSelectedMessages([])}+ <MessageListStateContext.Provider value={listState}>+ <div ref={containerRef} className="h-full min-h-0 overflow-hidden lg:grid lg:transition-[grid-template-columns] lg:ease-in-out motion-reduce:transition-none" style={{ gridTemplateColumns: twoColumnReading ? `${listVisible ? renderedListWidth : 0}px minmax(0,1fr)` : "minmax(0,1fr)", transitionDuration: widthReady ? "300ms" : "0ms" }}>+ {twoColumnReading && (+ <aside className={`relative hidden min-h-0 min-w-0 overflow-hidden bg-white lg:block ${listVisible ? "border-r border-neutral-200" : "pointer-events-none"}`} aria-hidden={!listVisible} inert={!listVisible}>+ <div className={`h-full overflow-hidden transition-transform duration-300 ease-in-out motion-reduce:transition-none ${listVisible ? "translate-x-0" : "-translate-x-full"}`} style={{ width: renderedListWidth }}>+ <MessageFolderPage+ config={config}+ compact+ selectedMessageId={selectedMessageId}+ />+ </div>+ <ResizeHandle+ label={t("list.resize")}+ onResizeStart={() => { startWidth.current = listWidth; resizedWidth.current = listWidth; }}+ onResize={(delta) => {+ const requestedWidth = startWidth.current + delta;+ setForcedMinimal(requestedWidth < 250);+ resizedWidth.current = Math.max(250, Math.min(requestedWidth, Math.max(250, (containerRef.current?.clientWidth ?? 1000) - 280)));+ setListWidth(resizedWidth.current);+ }}+ onResizeEnd={() => saveColumnWidth(userId, "message-list", resizedWidth.current)}/>- ) : (- children+ </aside>)}- </section>- </MessageDetailNavigationProvider>- </MessageListVisibilityContext.Provider>- </div>+ <MessageListVisibilityContext.Provider value={{ visible: listVisible, toggle: () => { const visible = !manualListVisible; setManualListVisible(visible); saveMessageListVisible(visible); }, singleColumn: !twoColumnReading, backHref: config.hrefPrefix, backLabel: config.titleKey ? t(config.titleKey) : config.title }}>+ <MessageDetailNavigationProvider config={config}>+ <section className="min-h-0 min-w-0 overflow-hidden bg-white flex flex-col h-full">+ {showBulkBar && (+ <BulkMessageActionBar+ folder={config.folderId ? undefined : config.folder}+ selectedMessages={selectedMessages}+ onClearSelection={() => setSelectedMessages([])}+ />+ )}+ {children}+ </section>+ </MessageDetailNavigationProvider>+ </MessageListVisibilityContext.Provider>+ </div>+ </MessageListStateContext.Provider>);}diff --git a/src/components/messages/types.d.ts b/src/components/messages/types.d.tsindex 1627521..b16edd6 100644--- a/src/components/messages/types.d.ts+++ b/src/components/messages/types.d.ts@@ -42,7 +42,6 @@ export type MessageFolderPageProps = {config: MessageFolderConfig;compact?: boolean;selectedMessageId?: string;- selection?: MessageSelectionControl;};export type MessageSplitLayoutProps = {@@ -71,12 +70,16 @@ export type BulkMessageToolbarProps = {export type SelectedMessage = Pick<Message, "id" | "read">;-export type MessageSelectionControl = {+export type MessageListStateControl = {selectedMessages: SelectedMessage[];setSelectedMessages: Dispatch<SetStateAction<SelectedMessage[]>>;+ offset: number;+ setOffset: Dispatch<SetStateAction<number>>;+ unreadOnly: boolean;+ setUnreadOnly: Dispatch<SetStateAction<boolean>>;};-export type BulkMessageSelectionPaneProps = {+export type BulkMessageActionBarProps = {folder?: MessageFolder;selectedMessages: SelectedMessage[];onClearSelection: () => void;diff --git a/src/components/sidebar-mobile-utils.ts b/src/components/sidebar-mobile-utils.tsindex e56444d..5776826 100644--- a/src/components/sidebar-mobile-utils.ts+++ b/src/components/sidebar-mobile-utils.ts@@ -1,21 +1,29 @@"use client";-import { useSyncExternalStore } from "react";+import { useCallback, useSyncExternalStore } from "react";const mobileQuery = "(max-width: 767px)";+const desktopQuery = "(min-width: 1024px)";++function useMediaQuery(query: string): boolean {+ const subscribe = useCallback((onChange: () => void) => {+ const media = window.matchMedia(query);+ media.addEventListener("change", onChange);+ return () => media.removeEventListener("change", onChange);+ }, [query]);+ const getSnapshot = useCallback(() => window.matchMedia(query).matches, [query]);+ return useSyncExternalStore(subscribe, getSnapshot, () => false);+}export function isMobileViewport(): boolean {return window.matchMedia(mobileQuery).matches;}export function useIsMobile(): boolean {- return useSyncExternalStore(- (onChange) => {- const media = window.matchMedia(mobileQuery);- media.addEventListener("change", onChange);- return () => media.removeEventListener("change", onChange);- },- isMobileViewport,- () => false,- );+ return useMediaQuery(mobileQuery);+}++/** Whether the split message list is actually rendered beside the reader. */+export function useIsDesktop(): boolean {+ return useMediaQuery(desktopQuery);}diff --git a/tests/message-selection-navigation.test.mjs b/tests/message-selection-navigation.test.mjsnew file mode 100644index 0000000..a728e9b--- /dev/null+++ b/tests/message-selection-navigation.test.mjs@@ -0,0 +1,316 @@+import assert from "node:assert/strict";+import { mkdtempSync, rmSync } from "node:fs";+import { join } from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";+import test, { after } from "node:test";+import { build } from "esbuild";+import { JSDOM } from "jsdom";++const root = fileURLToPath(new URL("../", import.meta.url));+const temp = mkdtempSync(join(root, "node_modules", "mailflare-message-selection-"));+after(() => rmSync(temp, { recursive: true, force: true }));++const dom = new JSDOM("<!doctype html><html><body></body></html>", {+ url: "https://mail.example/inbox",+ pretendToBeVisual: true,+});+for (const key of ["window", "document", "HTMLElement", "Element", "Node", "Event", "MouseEvent", "HTMLInputElement", "CustomEvent"]) {+ globalThis[key] = key === "window" ? dom.window : dom.window[key];+}+globalThis.IS_REACT_ACT_ENVIRONMENT = true;+globalThis.requestAnimationFrame = dom.window.requestAnimationFrame.bind(dom.window);+globalThis.cancelAnimationFrame = dom.window.cancelAnimationFrame.bind(dom.window);+globalThis.ResizeObserver = class {+ observe() {}+ disconnect() {}+};++const mock = new Map([+ ["next/navigation", `+import React from "react";+let pathname = "/inbox";+const listeners = new Set();+globalThis.__setTestPathname = (next) => {+ pathname = next;+ for (const listener of listeners) listener();+};+export function usePathname() {+ const [value, setValue] = React.useState(pathname);+ React.useEffect(() => {+ const listener = () => setValue(pathname);+ listeners.add(listener);+ return () => listeners.delete(listener);+ }, []);+ return value;+}+export function useRouter() {+ return {+ push(next) { globalThis.__setTestPathname(next); },+ replace(next) { globalThis.__setTestPathname(next); },+ };+}+export function useParams() { return {}; }+`],+ ["next/link", `+import React from "react";+export default function Link({ href, children, ...props }) {+ return React.createElement("a", { href, ...props }, children);+}+`],+ ["@/components/language-provider", `+export function useLanguage() {+ return {+ t(key, vars) {+ return vars && vars.count !== undefined ? key + ":" + vars.count : key;+ },+ };+}+`],+ ["@/components/mail-search/mail-search-context", `+export function useMailSearch() {+ return { query: "", input: "", setQuery() {} };+}+`],+ ["@/components/mailbox-provider", `+export function useSelectedMailbox() {+ return globalThis.__testMailboxState;+}+`],+ ["@/hooks/use-messages", `+export function useMessages(folder, mailboxId, filters) {+ return globalThis.__testMessageList(filters);+}+`],+ ["@/hooks/use-message-counts", `+export function useMessageCounts() {+ return {+ counts: {+ folders: { inbox: { total: 30, unread: 30 } },+ customFolders: {},+ mailboxes: [],+ },+ isLoading: false,+ };+}+`],+ ["@/components/page-loading", `+export function usePageLoading() {}+`],+ ["@/components/sidebar-mobile-utils", `+export function useIsMobile() { return false; }+export function useIsDesktop() { return globalThis.__testIsDesktop !== false; }+`],+ ["@/components/messages/use-conversation-view", `+export function useConversationView() { return [true, () => {}]; }+`],+ ["@/components/messages/use-two-column-reading", `+export function useTwoColumnReading() { return [true, () => {}]; }+`],+ ["@/components/follow-ups/due-follow-ups", `+export function DueFollowUps() { return null; }+`],+]);++const relativeStub = `+import React from "react";+export function MessageDetailNavigationProvider({ children }) { return children; }+export function useMessageNavigation() { return { progress: null, onNavigate() {} }; }+export function MessageNavigationProgress() { return null; }+export function MessageListRowActions() { return null; }+export function SwipeableRow({ children }) { return children; }+`;++await build({+ stdin: {+ contents: `+ import React from "react";+ import { usePathname } from "next/navigation";+ import { MessageSplitLayout } from "./src/components/messages/message-split-layout.tsx";+ import { MessageFolderPage } from "./src/components/messages/message-folder-page.tsx";+ import { inboxFolderConfig } from "./src/components/messages/message-folder-configs.ts";++ export function Harness() {+ const pathname = usePathname();+ const detailPrefix = "/inbox/";+ const detailId = pathname.startsWith(detailPrefix) ? pathname.slice(detailPrefix.length) : null;+ return React.createElement(+ MessageSplitLayout,+ { config: inboxFolderConfig },+ detailId+ ? React.createElement("div", { "data-testid": "message-detail", "data-message-id": detailId }, "Message detail")+ : React.createElement(MessageFolderPage, { config: inboxFolderConfig }),+ );+ }+ `,+ resolveDir: root,+ sourcefile: "message-selection-entry.tsx",+ loader: "tsx",+ },+ outfile: join(temp, "entry.mjs"),+ bundle: true,+ platform: "browser",+ format: "esm",+ jsx: "automatic",+ packages: "external",+ alias: { "@": join(root, "src") },+ plugins: [{+ name: "message-selection-test-stubs",+ setup(b) {+ b.onResolve({ filter: /.*/ }, (args) => {+ if (mock.has(args.path)) return { path: args.path, namespace: "test-stub" };+ if (["./message-detail-navigation", "./message-navigation", "./message-list-row-actions", "./swipeable-row"].includes(args.path)) {+ return { path: "relative-stub", namespace: "test-relative-stub" };+ }+ return undefined;+ });+ b.onLoad({ filter: /.*/, namespace: "test-stub" }, (args) => ({ contents: mock.get(args.path), loader: "tsx", resolveDir: root }));+ b.onLoad({ filter: /.*/, namespace: "test-relative-stub" }, () => ({ contents: relativeStub, loader: "tsx", resolveDir: root }));+ },+ }],+ logLevel: "silent",+});++const { createElement, act } = await import("react");+const { createRoot } = await import("react-dom/client");+const { Harness } = await import(pathToFileURL(join(temp, "entry.mjs")).href);++function message(id, read = false) {+ return {+ id,+ userId: "user-1",+ mailboxId: "mailbox-1",+ folderId: null,+ direction: "inbound",+ providerMessageId: null,+ fromAddr: "[email protected]",+ toAddr: "[email protected]",+ ccAddr: null,+ bccAddr: null,+ fromContactName: "Sender",+ subject: `Subject ${id}`,+ snippet: "Preview",+ status: "inbox",+ read,+ starred: false,+ threadId: null,+ createdAt: "2026-10-01T10:00:00.000Z",+ };+}++const allMessages = Array.from({ length: 30 }, (_, index) => message(`m${index + 1}`, index > 0));++globalThis.__testMailboxState = {+ selectedMailbox: {+ id: "mailbox-1",+ localPart: "tester",+ hostname: "example.com",+ displayName: "Tester",+ senderAddresses: ["[email protected]"],+ },+ isLoading: false,+ mailboxes: [],+};++globalThis.__testMessageList = (filters) => {+ const offset = filters?.offset ?? 0;+ const messages = allMessages.slice(offset, offset + 25);+ return {+ messages,+ isLoading: false,+ total: allMessages.length,+ limit: 25,+ updateMessages() {},+ };+};++async function renderInbox({ desktop = true } = {}) {+ globalThis.__testIsDesktop = desktop;+ globalThis.__setTestPathname("/inbox");+ const container = document.createElement("div");+ document.body.appendChild(container);+ const reactRoot = createRoot(container);+ await act(async () => {+ reactRoot.render(createElement(Harness));+ });+ return {+ container,+ async cleanup() {+ await act(async () => reactRoot.unmount());+ container.remove();+ },+ };+}++function checkedBoxes(container) {+ return [...container.querySelectorAll('input[type="checkbox"]:checked')];+}++test("opening a message keeps the selection made while no message was open", async (t) => {+ const { container, cleanup } = await renderInbox();+ t.after(cleanup);++ const rowCheckbox = container.querySelectorAll('input[type="checkbox"]')[1];+ await act(async () => {+ rowCheckbox.click();+ });+ assert.equal(checkedBoxes(container).length, 1, "the row is selected before opening a message");++ await act(async () => {+ globalThis.__setTestPathname("/inbox/m1");+ });++ assert.equal(checkedBoxes(container).length, 1, "the sidebar list keeps the selected row");+ assert.ok(container.querySelector('[data-testid="message-detail"]'), "the focused message stays visible");+ assert.match(container.textContent, /common\.selectedCount:1/, "the bulk action bar reports one selected message");++ const clearSelection = container.querySelector('button[aria-label="common.clearSelection"]');+ assert.ok(clearSelection, "the bulk action bar offers a way to clear the selection");+ await act(async () => {+ clearSelection.click();+ });+ assert.ok(container.querySelector('[data-testid="message-detail"]'), "clearing the selection keeps the message visible");+ assert.equal(checkedBoxes(container).length, 0, "clearing the selection unchecks the sidebar row");+ assert.doesNotMatch(container.textContent, /common\.selectedCount:1/, "the bulk action bar disappears");+});++test("opening a message keeps the selection on a page other than the first", async (t) => {+ const { container, cleanup } = await renderInbox();+ t.after(cleanup);++ const nextPage = container.querySelector('button[aria-label="list.nextPage"]');+ assert.ok(nextPage, "the first page has a next-page button");+ await act(async () => {+ nextPage.click();+ });++ const rowCheckbox = container.querySelectorAll('input[type="checkbox"]')[1];+ await act(async () => {+ rowCheckbox.click();+ });+ assert.equal(checkedBoxes(container).length, 1, "a row on the second page is selected");++ await act(async () => {+ globalThis.__setTestPathname("/inbox/m26");+ });++ assert.equal(checkedBoxes(container).length, 1, "the sidebar list stays on the same page and keeps the selected row");+ assert.ok(container.querySelector('[data-testid="message-detail"]'), "the focused message stays visible on the second page too");+});++test("the focused-message bulk bar stays in the split view", async (t) => {+ const { container, cleanup } = await renderInbox({ desktop: false });+ t.after(cleanup);++ const rowCheckbox = container.querySelectorAll('input[type="checkbox"]')[1];+ await act(async () => {+ rowCheckbox.click();+ });++ await act(async () => {+ globalThis.__setTestPathname("/inbox/m1");+ });++ assert.ok(container.querySelector('[data-testid="message-detail"]'), "single-column reading still opens the message");+ assert.equal(checkedBoxes(container).length, 1, "the selection survives");+ assert.equal(container.querySelector('[role="region"]'), null, "the bulk bar is hidden without a visible split list");+});