Back from a group returns to your own mail (#133) #137

Merged
jcoffey-dev merged 1 commits from fix/back-to-main-account into main 2026-11-20 22:47:41 +00:00
4 changed files with 229 additions and 7 deletions

No files matched your search

+7 -2
View File
@@ -25,6 +25,7 @@ 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 { DEFAULT_APP_NAME } from "@/lib/brand";
const ContactsView = lazy(() => import("@/views/contacts/ContactsView").then((m) => ({ default: m.ContactsView })));
@@ -95,12 +96,16 @@ 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) });
if (!hasUnsavedChanges()) {
navigate(to, options);
go();
return;
}
void confirmLeaveUnsaved().then((ok) => {
if (ok) navigate(to, options);
if (ok) go();
});
}}
>
@@ -0,0 +1,114 @@
import { beforeEach, describe, expect, it } 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";
/**
* #133: after switching to a group's mail, Back closed the installed app.
* The account shown isn't in the address, so the history had nothing that
* could bring your own mail back. Each page now carries the account it was
* showing, and Back onto it switches back.
*/
const session = {
capabilities: { [CAP.core]: { maxCallsInRequest: 16, maxObjectsInGet: 500 }, [CAP.mail]: {} },
accounts: {
own: { name: "[email protected]", isPersonal: true, accountCapabilities: { [CAP.mail]: {} } },
group: { name: "[email protected]", isPersonal: false, accountCapabilities: { [CAP.mail]: {} } },
sales: { name: "[email protected]", isPersonal: false, accountCapabilities: { [CAP.mail]: {} } },
},
primaryAccounts: { [CAP.mail]: "own" },
state: "s",
} as unknown as JmapSession;
beforeEach(() => {
useSession.setState({
status: "authenticated",
session,
accountId: "own",
viewing: null,
sharedMail: [
{ id: "group", name: "[email protected]" },
{ id: "sales", name: "[email protected]" },
],
});
});
describe("the account a page was showing", () => {
it("is written into the page's state and read back", () => {
expect(viewingIn(withViewing(undefined, "group"))).toBe("group");
expect(viewingIn(withViewing(null, null))).toBeNull();
});
it("keeps whatever else the page's state held", () => {
expect(withViewing({ other: 1 }, "group")).toEqual({ other: 1, inbuxaViewing: "group" });
});
it("is your own account on a page with no mark, such as the one the app opened on", () => {
for (const state of [null, undefined, "x", 3, {}, { inbuxaViewing: "" }, { inbuxaViewing: 7 }]) {
expect(viewingIn(state)).toBeNull();
}
});
});
describe("Back and Forward across an account switch", () => {
it("brings your own mail back from a group", () => {
useSession.getState().view("group");
expect(followHistory(withViewing(null, null), false)).toBe("switched");
expect(useSession.getState().viewing).toBeNull();
});
it("goes forward into the group again", () => {
expect(followHistory(withViewing(null, "group"), false)).toBe("switched");
expect(useSession.getState().viewing).toBe("group");
});
it("goes from one group back to the one before it", () => {
useSession.getState().view("sales");
expect(followHistory(withViewing(null, "group"), false)).toBe("switched");
expect(useSession.getState().viewing).toBe("group");
});
it("does nothing between pages of the same account", () => {
useSession.getState().view("group");
expect(followHistory(withViewing(null, "group"), false)).toBe("same");
expect(followHistory(withViewing(null, "group"), true)).toBe("same");
expect(useSession.getState().viewing).toBe("group");
});
it("shows your own mail for a page whose account is gone", () => {
useSession.getState().view("group");
useSession.setState({ sharedMail: [{ id: "sales", name: "[email protected]" }] });
useSession.getState().view("sales");
expect(followHistory(withViewing(null, "group"), false)).toBe("switched");
expect(useSession.getState().viewing).toBeNull();
});
it("keeps the account while a message is being written in it", () => {
useSession.getState().view("group");
expect(followHistory(withViewing(null, null), true)).toBe("kept");
expect(useSession.getState().viewing).toBe("group");
});
});
describe("the order on Back", () => {
it("switches the account before the router hears of the move", () => {
// The router adds its listener when it first renders, after this module loaded
const order: string[] = [];
const router = () => order.push("router");
window.addEventListener("popstate", router);
const undo = onHistoryMove(() => order.push("account"));
window.dispatchEvent(new PopStateEvent("popstate", { state: withViewing(null, "group") }));
undo();
window.removeEventListener("popstate", router);
expect(order).toEqual(["account", "router"]);
});
it("stops handling once the shell lets go", () => {
const seen: string[] = [];
onHistoryMove(() => seen.push("x"))();
window.dispatchEvent(new PopStateEvent("popstate", { state: null }));
expect(seen).toEqual([]);
});
});
+71
View File
@@ -0,0 +1,71 @@
import type { Id } from "@/jmap/types";
import { useSession } from "@/store/session";
/*
* Which account a page in the history was showing (#133).
*
* The account in view -- your own, or a shared or group mailbox, or a locked
* account handed to you -- isn't part of the address: /mail/<folder> reads the
* same whichever account it belongs to. So each page the app puts in the
* history carries the account it was showing in `history.state`, and Back or
* Forward onto a page that showed another account switches back to it.
*
* A page with no mark is your own account. That covers the page the app was
* opened on, since a fresh start always shows your own mail.
*/
const KEY = "inbuxaViewing";
/** `state` with the account in view written into it, for pushState/replaceState. */
export function withViewing(state: unknown, viewing: Id | null): Record<string, unknown> {
const base = state !== null && typeof state === "object" && !Array.isArray(state) ? (state as Record<string, unknown>) : {};
return { ...base, [KEY]: viewing };
}
/** The account a history entry was showing; null for your own. */
export function viewingIn(state: unknown): Id | null {
if (state === null || typeof state !== "object") return null;
const v = (state as Record<string, unknown>)[KEY];
return typeof v === "string" && v ? v : null;
}
/**
* Follow Back or Forward onto a page that showed another account.
*
* - "same": the page shows the account already in view; nothing to do.
* - "kept": a message is being written, and it belongs to the account it was
* started in, as for the switch in the menu; the account doesn't change.
* - "switched": the account in view now matches the page, or is your own if
* the page's account is gone since (a share taken away, a delegation
* ended, someone else signed in on this tab).
*/
export function followHistory(state: unknown, writing: boolean): "same" | "kept" | "switched" {
const want = viewingIn(state);
const session = useSession.getState();
if (want === session.viewing) return "same";
if (writing) return "kept";
session.view(want);
if (useSession.getState().viewing !== want) session.view(null);
return "switched";
}
/*
* One popstate listener, added when this module loads -- before anything
* renders, so before the router's. Listeners on window run in the order they
* were added, whatever their phase, and this one has to go first: the
* account must change before the page for the new address renders, or the
* mail view looks up one account's folder in the other's list, doesn't find
* it, and says the folder no longer exists. The router adds its listener
* when it first renders, and adds it again whenever it has been dropped, so
* it always comes after this one.
*/
let onMove: ((e: PopStateEvent) => void) | null = null;
if (typeof window !== "undefined") window.addEventListener("popstate", (e) => onMove?.(e));
/** Handle Back and Forward ahead of the router. Returns the undo. */
export function onHistoryMove(handler: (e: PopStateEvent) => void): () => void {
onMove = handler;
return () => {
if (onMove === handler) onMove = null;
};
}
+37 -5
View File
@@ -30,6 +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";
// 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,12 +202,43 @@ export function AppShell({ children }: { children: ReactNode }) {
return;
}
useSession.getState().view(id);
// Replace, in a tab as in the installed app (#128): the account shown
// isn't in the URL, so a page left in the history can't bring the old
// account back -- Back would land on the inbox already showing and seem
// to do nothing.
navigate("/mail", { replace: true });
if (useSession.getState().viewing !== id) return;
// A new page, marked with the account it shows (see lib/accountHistory),
// so Back undoes the switch: from a group, Back goes to your own mail
// first, and only then out of the app (#133). The page left behind is
// marked with the account it showed, so it brings that account back.
navigate("/mail");
};
/*
* Back or Forward onto a page that showed another account (#133). The
* history has already moved by the time this runs, so the account follows
* the page (see followHistory). When a message being written keeps it,
* the page is replaced with this account's mail, since the folder in its
* address belongs to the other one. onHistoryMove runs it ahead of the
* router, which matters; see there.
*/
useEffect(
() =>
onHistoryMove((e) => {
if (followHistory(e.state, useCompose.getState().drafts.length > 0) !== "kept") return;
toast.show(t("Send or close the message you're writing first."));
navigate("/mail", { replace: true });
}),
[navigate],
);
/*
* Mark the page the shell starts on with the account actually in view. A
* reload starts on your own mail, whichever account the page showed before
* it, and Back and Forward onto it must agree with what's on screen.
*/
useEffect(() => {
const viewing = useSession.getState().viewing;
if (viewingIn(window.history.state) !== viewing) {
window.history.replaceState(withViewing(window.history.state, viewing), "");
}
}, []);
const composeOff = section !== "files" && section !== "calendar" && section !== "contacts" && composeBlocked() !== null;
return (