Back and groups: keep the list's place, step back home, folder settings in a group #144

Merged
jcoffey-dev merged 1 commits from fix/back-and-group-folders into main 2026-11-22 00:52:41 +00:00
9 changed files with 288 additions and 21 deletions

No files matched your search

+26 -4
View File
@@ -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;
+60 -2
View File
@@ -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();
}
});
});
+43 -1
View File
@@ -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();
});
});
+77
View File
@@ -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<string, unknown> {
return state !== null && typeof state === "object" && !Array.isArray(state) ? (state as Record<string, unknown>) : {};
}
/** 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<string, unknown>, current: unknown, replace: boolean, viewing: Id | null): Record<string, unknown> {
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<string, unknown> {
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.
*
+46 -4
View File
@@ -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, { id: string; role?: string | null }>): 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<string, unknown>, current: unknown, replace: boolean, currentIsHome: boolean, currentViewing: string | null): Record<string, unknown> {
const { [BEHIND]: _old, ...rest } = next;
if (!replace) return { ...rest, [BEHIND]: { home: currentIsHome, viewing: currentViewing } };
const kept = current !== null && typeof current === "object" ? (current as Record<string, unknown>)[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<string, unknown>)[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());
}
+9 -4
View File
@@ -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;
+4 -4
View File
@@ -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 (
+15
View File
@@ -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).
+8 -2
View File
@@ -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<string>(["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<Mailbox | null>(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() {
<tbody>
{list.map(({ m, path }) => (
<tr key={m.id}>
<td><div className="row gap-8">{m.role === "inbox" ? <Inbox size={16} /> : <Folder size={16} />}<span>{mailboxDisplayPath(m, mailboxes)}</span>{!m.isSubscribed && <span className="badge muted">{t("hidden")}</span>}</div></td>
<td><div className="row gap-8">{m.role === "inbox" ? <Inbox size={16} /> : <Folder size={16} />}<span>{mailboxDisplayPath(m, mailboxes)}</span>{!viewingOther && !m.isSubscribed && <span className="badge muted">{t("hidden")}</span>}</div></td>
<td>
<select
className="input"
@@ -113,7 +119,7 @@ export function FoldersSettings() {
<button className="icon-btn sm" title={t("Rename")} disabled={Boolean(m.role) && m.role !== "subscribed"} onClick={async () => { const n = await // The server's own name, never the localized one: this box writes
// back whatever it is prefilled with.
promptDialog({ title: t("Rename folder"), defaultValue: m.name }); if (n?.trim() && n !== m.name) { try { await useMail.getState().updateMailbox(m.id, { name: n.trim() }); } catch (err) { toast.error((err as Error).message); } } }}><Pencil size={16} /></button>
<button className="icon-btn sm" title={m.isSubscribed ? t("Hide") : t("Show")} disabled={m.role === "inbox"} onClick={() => void useMail.getState().updateMailbox(m.id, { isSubscribed: !m.isSubscribed })}>{m.isSubscribed ? <EyeOff size={16} /> : <Eye size={16} />}</button>
{!viewingOther && <button className="icon-btn sm" title={m.isSubscribed ? t("Hide") : t("Show")} disabled={m.role === "inbox"} onClick={async () => { try { await useMail.getState().updateMailbox(m.id, { isSubscribed: !m.isSubscribed }); } catch (err) { toast.error((err as Error).message); } }}>{m.isSubscribed ? <EyeOff size={16} /> : <Eye size={16} />}</button>}
{Object.keys(m.shareWith ?? {}).length > 0 && <button className="icon-btn sm" title={t("Stop sharing")} onClick={() => setShare(m)}><Share2 size={16} /></button>}
<button className="icon-btn sm danger" title={t("Delete")} disabled={Boolean(m.role) && m.role !== "subscribed"} onClick={async () => { if (await confirmDialog({ title: t("Delete “{name}”?", { name: m.name }), message: plural(m.totalEmails, { one: "{n} message will be permanently deleted.", other: "{n} messages will be permanently deleted." }), confirmLabel: t("Delete"), danger: true })) { try { await useMail.getState().destroyMailbox(m.id, true); } catch (err) { toast.error((err as Error).message); } } }}><Trash2 size={16} /></button>
</div>