Files
webmail/lib/offline/state.ts
T
Linus Rath 5c5d982f9d feat: save drafts and keep attachments while offline
A draft saved offline now stays on the device under a stand-in id and
goes to the server by itself when it's back. Until now every save was
refused and the composer showed "not saved".

- `lib/store/drafts`: one pending create per draft, however often it's
  saved. A draft from the server edited offline is replaced by create,
  then destroy, so a failure leaves a copy. Each create has a fixed
  Message-ID, looked up in Drafts after a lost response. A refused
  draft stays on the device with its error and can be opened. Changed
  on another device: both are kept and the user is told.
- `JMAPClient`: stand-in ids in Email/get and Email/set resolve like
  calendar's, also when answering from the device. A file attached
  offline stays readable, and is uploaded before a save that names it.
- Held files and kept mail files are stored in 1 MB chunks. Orphans are
  dropped at the end of a flush, counting what drafts need.
- `lib/store/mail/attachments.ts`: attachments, inline images and raw
  messages per scope, newest first, after everything else in a pass,
  with eviction that spares pinned mail and never sees held files.
- `mail.rawBlob` and `mail.rawStatus` for an offline export.

Changed test assertions: `outbox.heldFile` and `mail.getBlob` return
`blob` instead of `data`, so a file isn't held whole in memory. The
attachment tests ignore raw downloads, and mail-sync runs with
attachments off, because raw messages add a commit per message.
2026-11-03 08:49:19 +01:00

111 lines
3.8 KiB
TypeScript

/**
* What offline mode (#523) shows: which accounts keep mail on this device,
* whether the browser is offline, what waits in the outbox, how much the
* local store uses. The switch itself ("Keep mail on this device") is per account
* and per browser, in localStorage, never synced: it is off until the user
* turns it on here.
*/
import { create } from 'zustand';
import type { ConflictEntry, LocalDraftRow, OutboxEntry, OutboxError } from './queue';
/** localStorage: the local account ids that keep mail on this device. */
export const OFFLINE_ACCOUNTS_KEY = 'bulwark-offline-accounts';
export interface OutboxRow {
id: number;
account: string;
createdAt: number;
subject: string;
to: string[];
status: OutboxEntry['status'];
error?: OutboxError;
}
interface OfflineState {
/** Accounts with "Keep mail on this device" on. */
enabled: string[];
/** The browser says it has no network. */
browserOffline: boolean;
/** Mail servers (their URLs) that couldn't be reached at the last request. */
downServers: string[];
/** The app started without the server, from the mail on this device. */
startedOffline: boolean;
outbox: OutboxRow[];
pendingChanges: number;
/** Changes the server refused, or that met a message changed on another device. */
conflicts: ConflictEntry[];
/** Drafts that are only on this device: on their way up, or refused by the server. */
localDrafts: LocalDraftRow[];
/** A local draft the user asked to open, for the mail page to pick up. */
draftToOpen: { account: string; jmap: string; id: string } | null;
usageBytes: number;
/** Accounts whose mail is being brought onto the device right now. */
syncing: string[];
lastSyncedAt: Record<string, number>;
}
function readEnabled(): string[] {
try {
const raw = typeof localStorage === 'undefined' ? null : localStorage.getItem(OFFLINE_ACCOUNTS_KEY);
const parsed = raw ? JSON.parse(raw) : [];
return Array.isArray(parsed) ? parsed.filter((id): id is string => typeof id === 'string') : [];
} catch {
return [];
}
}
export const useOfflineStore = create<OfflineState>()(() => ({
enabled: readEnabled(),
browserOffline: typeof navigator !== 'undefined' && navigator.onLine === false,
downServers: [],
startedOffline: false,
outbox: [],
pendingChanges: 0,
conflicts: [],
localDrafts: [],
draftToOpen: null,
usageBytes: 0,
syncing: [],
lastSyncedAt: {},
}));
export function writeEnabled(enabled: string[]): void {
useOfflineStore.setState({ enabled });
try {
if (enabled.length) localStorage.setItem(OFFLINE_ACCOUNTS_KEY, JSON.stringify(enabled));
else localStorage.removeItem(OFFLINE_ACCOUNTS_KEY);
} catch {
/* storage unavailable */
}
}
export function serverKey(url: string): string {
return url.replace(/\/+$/, '').toLowerCase();
}
/** The browser is offline, or this mail server (any, without one) couldn't be reached. */
export function isOfflineNow(serverUrl?: string): boolean {
const { browserOffline, downServers } = useOfflineStore.getState();
if (browserOffline) return true;
return serverUrl ? downServers.includes(serverKey(serverUrl)) : downServers.length > 0;
}
export function setServerDown(serverUrl: string, down: boolean): boolean {
const key = serverKey(serverUrl);
const { downServers } = useOfflineStore.getState();
const was = downServers.includes(key);
if (was !== down) useOfflineStore.setState({ downServers: down ? [...downServers, key] : downServers.filter((s) => s !== key) });
return was;
}
/** The switch as another tab left it (it changed in localStorage there). */
export function readEnabledFrom(raw: string | null): string[] {
try {
const parsed = raw ? JSON.parse(raw) : [];
return Array.isArray(parsed) ? parsed.filter((id): id is string => typeof id === 'string') : [];
} catch {
return [];
}
}