From 6807df85e0b9724409fbfab16e8927d2e2ef0d88 Mon Sep 17 00:00:00 2001 From: John Coffey Date: Sat, 21 Nov 2026 17:20:39 -0700 Subject: [PATCH] Back and groups: keep the list's place, step back home, folder settings in a group MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Settings › Folders in a group, shared mailbox or locked account no longer marks every folder hidden or offers Hide/Show: subscriptions are the reader's own, and they have none there (#140). A failed Hide/Show now says why instead of looking like nothing happened. - Back from a message returns to where the list was scrolled, on a phone and with the reading pane off (#141). - In the installed app, going to the inbox with the inbox behind steps back to it, so the first Back no longer lands on the same inbox (#142). - "Back to my mail", and choosing your own mail in the account menu, step back past the other account's pages instead of adding one, so Back doesn't go through the group again (#143). Pages now carry their position and what's behind them in history.state; a page without them falls back to the old behaviour, with a replace. Fixes #140, #141, #142, #143 --- web/src/App.tsx | 30 +++++++- web/src/lib/__tests__/accountHistory.test.ts | 62 +++++++++++++++- web/src/lib/__tests__/backStack.test.ts | 44 ++++++++++- web/src/lib/accountHistory.ts | 77 ++++++++++++++++++++ web/src/lib/backStack.ts | 50 ++++++++++++- web/src/views/AppShell.tsx | 13 +++- web/src/views/DelegatedBar.tsx | 8 +- web/src/views/mail/MessageList.tsx | 15 ++++ web/src/views/settings/FoldersSettings.tsx | 10 ++- 9 files changed, 288 insertions(+), 21 deletions(-) diff --git a/web/src/App.tsx b/web/src/App.tsx index f3639c3..c045474 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -25,7 +25,9 @@ import { listenForVerification, renewWebPush } from "@/lib/notify/webpushEnable" import { plural, t, useLanguageVersion, whenLanguageReady } from "@/lib/i18n"; import { confirmLeaveUnsaved, hasUnsavedChanges } from "@/lib/unsavedChanges"; import { BASE_PATH, withBase } from "@/lib/basePath"; -import { withViewing } from "@/lib/accountHistory"; +import { viewingIn, withPositions, withViewing } from "@/lib/accountHistory"; +import { inboxIdOf, isHome, stepsBackHome, withBehind } from "@/lib/backStack"; +import { isInstalledApp } from "@/lib/mailhandler"; import { DEFAULT_APP_NAME } from "@/lib/brand"; const ContactsView = lazy(() => import("@/views/contacts/ContactsView").then((m) => ({ default: m.ContactsView }))); @@ -97,9 +99,29 @@ export function App() { base={BASE_PATH} aroundNav={(navigate, to, options) => { // Each page remembers the account it shows, so Back can bring that - // account back (#133). Read when the move happens, not when it was - // asked for: an account switch changes it just before navigating. - const go = () => navigate(to, { ...options, state: withViewing(options?.state, useSession.getState().viewing) }); + // account back (#133), its position, so "Back to my mail" can step + // back to your own (#143), and whether the inbox is behind it, so + // going to the inbox can step back to it (#142). Read when the move + // happens, not when it was asked for: an account switch changes the + // account just before navigating. + const go = () => { + const current: unknown = window.history.state; + const viewing = useSession.getState().viewing; + const replace = Boolean(options?.replace); + const path = window.location.pathname; + const from = BASE_PATH && path.startsWith(BASE_PATH) ? path.slice(BASE_PATH.length) || "/" : path; + const inboxId = inboxIdOf(useMail.getState().mailboxes); + // Only from a page showing the account in view: one Back has just + // moved to while a message being written kept the account isn't. + if (viewingIn(current) === viewing && stepsBackHome(from, String(to), inboxId, isInstalledApp(), replace, current, viewing)) { + window.history.back(); + return; + } + let state = withViewing(options?.state, viewing); + state = withPositions(state, current, replace, viewing); + state = withBehind(state, current, replace, isHome(from, inboxId), viewingIn(current)); + navigate(to, { ...options, state }); + }; if (!hasUnsavedChanges()) { go(); return; diff --git a/web/src/lib/__tests__/accountHistory.test.ts b/web/src/lib/__tests__/accountHistory.test.ts index aa0edba..739b755 100644 --- a/web/src/lib/__tests__/accountHistory.test.ts +++ b/web/src/lib/__tests__/accountHistory.test.ts @@ -1,8 +1,8 @@ -import { beforeEach, describe, expect, it } from "vitest"; +import { beforeEach, describe, expect, it, vi } from "vitest"; import { CAP } from "@/jmap/client"; import type { JmapSession } from "@/jmap/types"; import { useSession } from "@/store/session"; -import { followHistory, onHistoryMove, viewingIn, withViewing } from "@/lib/accountHistory"; +import { backToOwnMail, followHistory, onHistoryMove, positionsIn, startPositions, stepsBackToOwn, viewingIn, withPositions, withViewing } from "@/lib/accountHistory"; /** * #133: after switching to a group's mail, Back closed the installed app. @@ -112,3 +112,61 @@ describe("the order on Back", () => { expect(seen).toEqual([]); }); }); + +describe("Back to my mail (#143)", () => { + // Your own inbox, then a switch to the group, a folder there, a message + const start = startPositions(null, null); + const switched = withPositions(withViewing(undefined, "group"), start, false, "group"); + const folder = withPositions(withViewing(undefined, "group"), switched, true, "group"); + const message = withPositions(withViewing(undefined, "group"), folder, false, "group"); + + it("counts the pages since your own mail was last shown", () => { + expect(positionsIn(start)).toEqual({ pos: 0, own: 0 }); + expect(stepsBackToOwn(switched)).toBe(1); + expect(stepsBackToOwn(folder)).toBe(1); + expect(stepsBackToOwn(message)).toBe(2); + }); + + it("starts again from a page that shows your own mail", () => { + const own = withPositions(withViewing(undefined, null), message, false, null); + expect(positionsIn(own)).toEqual({ pos: 3, own: 3 }); + expect(stepsBackToOwn(own)).toBe(0); + }); + + it("keeps a page's position through a reload, now on your own mail", () => { + expect(positionsIn(startPositions(message, null))).toEqual({ pos: 2, own: 2 }); + }); + + it("doesn't guess after a page with no positions", () => { + expect(positionsIn(withPositions({}, {}, false, "group"))).toBeNull(); + expect(stepsBackToOwn(withPositions({}, null, false, "group"))).toBe(0); + for (const bad of [{ inbuxaPos: 1, inbuxaOwnPos: 2 }, { inbuxaPos: 1.5, inbuxaOwnPos: 0 }, { inbuxaPos: "2", inbuxaOwnPos: 0 }]) { + expect(positionsIn(bad)).toBeNull(); + } + }); + + it("steps back past the group's pages instead of adding a page", () => { + useSession.getState().view("group"); + window.history.replaceState(message, ""); + const go = vi.spyOn(window.history, "go").mockImplementation(() => {}); + const navigate = vi.fn(); + backToOwnMail(navigate, false); + expect(go).toHaveBeenCalledWith(-2); + expect(navigate).not.toHaveBeenCalled(); + go.mockRestore(); + }); + + it("switches and replaces the page while a message is being written, or with no positions", () => { + for (const [state, writing] of [[message, true], [{}, false]] as const) { + useSession.getState().view("group"); + window.history.replaceState(state, ""); + const go = vi.spyOn(window.history, "go").mockImplementation(() => {}); + const navigate = vi.fn(); + backToOwnMail(navigate, writing); + expect(go).not.toHaveBeenCalled(); + expect(useSession.getState().viewing).toBeNull(); + expect(navigate).toHaveBeenCalledWith("/mail", { replace: true }); + go.mockRestore(); + } + }); +}); diff --git a/web/src/lib/__tests__/backStack.test.ts b/web/src/lib/__tests__/backStack.test.ts index 8e32379..3bc131b 100644 --- a/web/src/lib/__tests__/backStack.test.ts +++ b/web/src/lib/__tests__/backStack.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { isHome, sidewaysReplaces } from "../backStack"; +import { homeIsBehind, inboxIdOf, isHome, sidewaysReplaces, stepsBackHome, withBehind } from "../backStack"; describe("Back in the installed app (#96)", () => { it("treats the inbox, by path or by id, as home", () => { @@ -23,3 +23,45 @@ describe("Back in the installed app (#96)", () => { expect(sidewaysReplaces("/calendar", "inbox1", false)).toBe(false); }); }); + +describe("going to the inbox steps back to it (#142)", () => { + const start = {}; + // Inbox -> folder pushes, recording that the inbox is behind + const folder = withBehind({}, start, false, true, null); + // folder -> another folder replaces, keeping what is behind + const other = withBehind({}, folder, true, false, null); + + it("records the inbox behind a page pushed from it, and keeps it through replaces", () => { + expect(homeIsBehind(folder, null)).toBe(true); + expect(homeIsBehind(other, null)).toBe(true); + expect(homeIsBehind(withBehind({}, folder, false, false, null), null)).toBe(false); + }); + + it("steps back instead of replacing the folder with a second inbox", () => { + expect(stepsBackHome("/mail/archive2", "/mail/inbox1", "inbox1", true, true, other, null)).toBe(true); + expect(stepsBackHome("/calendar", "/mail", "inbox1", true, true, other, null)).toBe(true); + }); + + it("doesn't step back from the inbox, to anywhere else, or without the inbox behind", () => { + expect(stepsBackHome("/mail/inbox1", "/mail", "inbox1", true, true, other, null)).toBe(false); + expect(stepsBackHome("/mail/archive2", "/mail/sent3", "inbox1", true, true, other, null)).toBe(false); + expect(stepsBackHome("/mail/archive2", "/mail/inbox1", "inbox1", true, true, {}, null)).toBe(false); + expect(stepsBackHome("/mail/archive2", "/mail/inbox1", "inbox1", true, true, null, null)).toBe(false); + }); + + it("doesn't step back into another account's inbox", () => { + // Your own inbox, then a group: the group's folder has your inbox behind it + const groupFolder = withBehind({}, {}, false, true, null); + expect(stepsBackHome("/mail/g-archive", "/mail/g-inbox", "g-inbox", true, true, groupFolder, "group")).toBe(false); + }); + + it("leaves a browser tab's history alone", () => { + expect(stepsBackHome("/mail/archive2", "/mail/inbox1", "inbox1", false, true, other, null)).toBe(false); + expect(stepsBackHome("/mail/archive2", "/mail/inbox1", "inbox1", true, false, other, null)).toBe(false); + }); + + it("finds the inbox among the folders", () => { + expect(inboxIdOf({ a: { id: "a", role: "sent" }, b: { id: "b", role: "inbox" } })).toBe("b"); + expect(inboxIdOf({})).toBeUndefined(); + }); +}); diff --git a/web/src/lib/accountHistory.ts b/web/src/lib/accountHistory.ts index d2bdccb..17491e8 100644 --- a/web/src/lib/accountHistory.ts +++ b/web/src/lib/accountHistory.ts @@ -1,5 +1,6 @@ import type { Id } from "@/jmap/types"; import { useSession } from "@/store/session"; +import { confirmLeaveUnsaved, hasUnsavedChanges } from "@/lib/unsavedChanges"; /* * Which account a page in the history was showing (#133). @@ -29,6 +30,82 @@ export function viewingIn(state: unknown): Id | null { return typeof v === "string" && v ? v : null; } +/* + * Where each page sits, for "Back to my mail" (#143). The bar's button used to + * open your own mail as a new page, so Back afterwards walked through the + * group's pages again. Each page the app puts in the history now carries its + * position, and the position of the last page that showed your own mail, so + * the button can step back that far, the way pressing Back would. + * + * A page without them -- one added outside the router -- leaves the button + * to fall back on replacing the page instead. + */ + +const POS = "inbuxaPos"; +const OWN = "inbuxaOwnPos"; + +function record(state: unknown): Record { + return state !== null && typeof state === "object" && !Array.isArray(state) ? (state as Record) : {}; +} + +/** A page's position, and that of the last page at or before it that showed your own mail. */ +export function positionsIn(state: unknown): { pos: number; own: number } | null { + const r = record(state); + const pos = r[POS]; + const own = r[OWN]; + if (typeof pos !== "number" || typeof own !== "number" || !Number.isInteger(pos) || !Number.isInteger(own) || own < 0 || own > pos) return null; + return { pos, own }; +} + +/** + * `next`, the state for a page about to be pushed or to replace the current + * one, with its positions worked out from `current`'s. When the current page + * has none, neither does the next: a guess could step back too far. + */ +export function withPositions(next: Record, current: unknown, replace: boolean, viewing: Id | null): Record { + const { [POS]: _pos, [OWN]: _own, ...rest } = next; + const cur = positionsIn(current); + if (!cur) return rest; + const pos = replace ? cur.pos : cur.pos + 1; + return { ...rest, [POS]: pos, [OWN]: viewing === null ? pos : cur.own }; +} + +/** The page the app starts on: position 0 unless it already has one, showing `viewing`. */ +export function startPositions(state: unknown, viewing: Id | null): Record { + const cur = positionsIn(state); + const pos = cur?.pos ?? 0; + return { ...record(state), [POS]: pos, [OWN]: viewing === null ? pos : (cur?.own ?? pos) }; +} + +/** How many pages back your own mail was last shown; 0 when it isn't known. */ +export function stepsBackToOwn(state: unknown): number { + const cur = positionsIn(state); + return cur ? cur.pos - cur.own : 0; +} + +/** + * "Back to my mail" (#143): step back to the page your own mail was last on, + * so the other account's pages leave the history, as Back would have done; + * the popstate handler switches the account (followHistory). With a message + * being written, which keeps the account it was started in on Back, or + * without positions to go by, switch here and replace the page instead. + */ +export function backToOwnMail(navigate: (to: string, options?: { replace?: boolean }) => void, writing: boolean): void { + const steps = writing ? 0 : stepsBackToOwn(window.history.state); + if (steps > 0) { + // A step back skips the router, and with it the question it asks before + // leaving unsaved changes; ask it here. + if (!hasUnsavedChanges()) window.history.go(-steps); + else + void confirmLeaveUnsaved().then((ok) => { + if (ok) window.history.go(-steps); + }); + return; + } + useSession.getState().view(null); + navigate("/mail", { replace: true }); +} + /** * Follow Back or Forward onto a page that showed another account. * diff --git a/web/src/lib/backStack.ts b/web/src/lib/backStack.ts index cd1812d..0d9304b 100644 --- a/web/src/lib/backStack.ts +++ b/web/src/lib/backStack.ts @@ -17,6 +17,51 @@ export function isHome(location: string, inboxId: string | undefined): boolean { return path === "/" || path === "/mail" || (inboxId !== undefined && path === `/mail/${inboxId}`); } +/** The id of the inbox among `mailboxes`, if it has loaded. */ +export function inboxIdOf(mailboxes: Record): string | undefined { + for (const m of Object.values(mailboxes)) if (m.role === "inbox") return m.id; + return undefined; +} + +/* + * What the page behind this one shows (#142). Replacing every sideways move + * keeps the inbox behind a folder, but going from that folder to the inbox + * replaced the folder with a second inbox: Back then landed on the inbox + * already on screen and seemed to do nothing. So a pushed page records + * whether the page it was pushed from was the inbox, and whose; a replaced + * page keeps what the one it replaced had. Going to the inbox with the same + * account's inbox behind steps back to it instead. + */ + +const BEHIND = "inbuxaBehind"; + +/** `next` with what is behind it recorded: the current page when pushing, or what is behind the current page when replacing it. */ +export function withBehind(next: Record, current: unknown, replace: boolean, currentIsHome: boolean, currentViewing: string | null): Record { + const { [BEHIND]: _old, ...rest } = next; + if (!replace) return { ...rest, [BEHIND]: { home: currentIsHome, viewing: currentViewing } }; + const kept = current !== null && typeof current === "object" ? (current as Record)[BEHIND] : undefined; + return kept === undefined ? rest : { ...rest, [BEHIND]: kept }; +} + +/** Whether the page behind `state`'s is the inbox of the account `viewing`. */ +export function homeIsBehind(state: unknown, viewing: string | null): boolean { + if (state === null || typeof state !== "object") return false; + const b = (state as Record)[BEHIND]; + if (b === null || typeof b !== "object") return false; + const { home, viewing: whose } = b as { home?: unknown; viewing?: unknown }; + return home === true && (typeof whose === "string" ? whose : null) === viewing; +} + +/** + * Whether a move from `from` to `to` should be a step back instead: in the + * installed app, a sideways move (one that would replace the page) to the + * inbox, from a page that isn't the inbox, with that inbox behind it. + */ +export function stepsBackHome(from: string, to: string, inboxId: string | undefined, installed: boolean, replace: boolean, state: unknown, viewing: string | null): boolean { + const target = to.split(/[?#]/)[0] ?? to; + return installed && replace && isHome(target, inboxId) && !isHome(from, inboxId) && homeIsBehind(state, viewing); +} + /** Whether a move to another folder or section should replace the current page. */ export function sidewaysReplaces(location: string, inboxId: string | undefined, installed: boolean): boolean { return installed && !isHome(location, inboxId); @@ -25,9 +70,6 @@ export function sidewaysReplaces(location: string, inboxId: string | undefined, /** sidewaysReplaces for the page being shown. Pass the result as a link's or navigate's `replace`. */ export function useSidewaysReplace(): boolean { const [location] = useLocation(); - const inboxId = useMail((s) => { - for (const m of Object.values(s.mailboxes)) if (m.role === "inbox") return m.id; - return undefined; - }); + const inboxId = useMail((s) => inboxIdOf(s.mailboxes)); return sidewaysReplaces(location, inboxId, isInstalledApp()); } diff --git a/web/src/views/AppShell.tsx b/web/src/views/AppShell.tsx index dd575b0..46797b6 100644 --- a/web/src/views/AppShell.tsx +++ b/web/src/views/AppShell.tsx @@ -30,7 +30,7 @@ import { hasAdministration } from "@/lib/admin/adminAccess"; import { usePermissions } from "./admin/usePermissions"; import { AdminNav } from "./admin/AdminNav"; import { useSidewaysReplace } from "@/lib/backStack"; -import { followHistory, onHistoryMove, viewingIn, withViewing } from "@/lib/accountHistory"; +import { backToOwnMail, followHistory, onHistoryMove, startPositions, withViewing } from "@/lib/accountHistory"; // The other sections' sidebars load with the section, as their views already do. const FilesTree = lazy(() => import("./files/FilesTree").then((m) => ({ default: m.FilesTree }))); @@ -201,6 +201,12 @@ export function AppShell({ children }: { children: ReactNode }) { toast.show(t("Send or close the message you're writing first.")); return; } + // Back to your own mail steps back past the other account's pages, as + // "Back to my mail" does (#143) + if (id === null) { + backToOwnMail(navigate, false); + return; + } useSession.getState().view(id); if (useSession.getState().viewing !== id) return; // A new page, marked with the account it shows (see lib/accountHistory), @@ -235,9 +241,8 @@ export function AppShell({ children }: { children: ReactNode }) { */ useEffect(() => { const viewing = useSession.getState().viewing; - if (viewingIn(window.history.state) !== viewing) { - window.history.replaceState(withViewing(window.history.state, viewing), ""); - } + // ...and with its position, which every later page counts from (#143) + window.history.replaceState(startPositions(withViewing(window.history.state, viewing), viewing), ""); }, []); const composeOff = section !== "files" && section !== "calendar" && section !== "contacts" && composeBlocked() !== null; diff --git a/web/src/views/DelegatedBar.tsx b/web/src/views/DelegatedBar.tsx index 1e685fd..0872bab 100644 --- a/web/src/views/DelegatedBar.tsx +++ b/web/src/views/DelegatedBar.tsx @@ -1,6 +1,8 @@ import { Lock, Users } from "lucide-react"; import { useLocation } from "wouter"; import { useSession, useViewingDelegation, useViewingShared } from "@/store/session"; +import { useCompose } from "@/store/compose"; +import { backToOwnMail } from "@/lib/accountHistory"; import { t } from "@/lib/i18n"; import type { DelegationAccess } from "@/lib/delegation"; @@ -27,10 +29,8 @@ export function DelegatedBar() { const delegation = useViewingDelegation(); const shared = useViewingShared(); const [, navigate] = useLocation(); - const back = () => { - useSession.getState().view(null); - navigate("/mail"); - }; + // Steps back past this account's pages rather than adding one (#143) + const back = () => backToOwnMail(navigate, useCompose.getState().drafts.length > 0); // MA-A: a shared or group mailbox in view says whose it is, with the same way back if (viewing && shared) { return ( diff --git a/web/src/views/mail/MessageList.tsx b/web/src/views/mail/MessageList.tsx index 9765d22..c1bcb7b 100644 --- a/web/src/views/mail/MessageList.tsx +++ b/web/src/views/mail/MessageList.tsx @@ -91,6 +91,15 @@ interface Props { isSearch: boolean; } +/* + * Where the list was scrolled to, for the list it was showing (#141). On a + * phone, and with the reading pane off, opening a message takes the list off + * the screen, and Back puts up a new one. Without this it starts at the top, + * however far down the reader had gone. Only the list last shown is kept: + * Back returns to it, and a different folder or search starts at the top. + */ +let lastScroll: { key: string; offset: number } | null = null; + export function MessageList({ title, list, openThreadId, openMessageId, focusId, setFocusId, onOpen, actions, mailboxId, isSearch }: Props) { const [, navigate] = useLocation(); const emails = useMail((s) => s.emails); @@ -143,11 +152,17 @@ export function MessageList({ title, list, openThreadId, openMessageId, focusId, const isDrafts = mailbox?.role === "drafts"; const rowHeight = twoLine ? (settings.density === "compact" ? 56 : settings.density === "comfortable" ? 78 : 66) : settings.density === "compact" ? 36 : settings.density === "comfortable" ? 52 : 44; + const mailAccount = useMail((s) => s.accountId); + const scrollKey = list ? `${mailAccount ?? ""}|${list.key}` : null; const virtualizer = useVirtualizer({ count: ids.length + (list && !list.exhausted ? 1 : 0), getScrollElement: () => parentRef.current, estimateSize: () => rowHeight, overscan: 12, + initialOffset: () => (scrollKey !== null && lastScroll?.key === scrollKey ? lastScroll.offset : 0), + onChange: (v) => { + if (scrollKey !== null && v.scrollOffset !== null) lastScroll = { key: scrollKey, offset: v.scrollOffset }; + }, }); // Re-measure when the row height changes (one-line ↔ two-line, density). diff --git a/web/src/views/settings/FoldersSettings.tsx b/web/src/views/settings/FoldersSettings.tsx index d95899b..ac11eaf 100644 --- a/web/src/views/settings/FoldersSettings.tsx +++ b/web/src/views/settings/FoldersSettings.tsx @@ -1,6 +1,7 @@ import { useMemo, useState } from "react"; import { Eye, EyeOff, Folder, Pencil, Plus, Share2, Trash2, Inbox } from "lucide-react"; import { useMail } from "@/store/mail"; +import { useSession } from "@/store/session"; import { confirmDialog, promptDialog } from "@/ui/dialog"; import { toast } from "@/ui/toast"; import { formatSize } from "@/lib/format"; @@ -31,6 +32,11 @@ const FIXED_ROLES = new Set(["inbox", "junk", "trash"]); export function FoldersSettings() { const mailboxes = useMail((s) => s.mailboxes); + // Hiding a folder is the reader's own subscription, and they have none in a + // shared or group mailbox or a locked account, so every folder there would + // read "hidden" and the folder list shows them all anyway (MailboxTree). + // Hide/Show has nothing to do there, and isn't offered (#140). + const viewingOther = useSession((s) => s.viewing !== null); const mailboxPath = useMail((s) => s.mailboxPath); const [share, setShare] = useState(null); const list = useMemo(() => Object.values(mailboxes).map((m) => ({ m, path: mailboxPath(m.id) })).sort((a, b) => a.path.localeCompare(b.path)), [mailboxes, mailboxPath]); @@ -87,7 +93,7 @@ export function FoldersSettings() { {list.map(({ m, path }) => ( -
{m.role === "inbox" ? : }{mailboxDisplayPath(m, mailboxes)}{!m.isSubscribed && {t("hidden")}}
+
{m.role === "inbox" ? : }{mailboxDisplayPath(m, mailboxes)}{!viewingOther && !m.isSubscribed && {t("hidden")}}