Attach a file that is already in Files

Attaching meant uploading, even when the file was sitting in the account
already -- picking it off disk again to send the server a copy of what it
was holding.

The composer can now attach from Files. A blob the account can already
see needs no upload at all: an attachment carrying a `blobId` is what a
forward produces, so the send path has always known what to do with one.
Attaching a large file the server is already storing now costs nothing
and takes no time.

A file in an account somebody *shared* is different, because blobs belong
to the account they were uploaded to and a draft in yours cannot
reference one in theirs. Those are fetched and uploaded to your account,
and the picker says so before you attach rather than leaving someone
wondering why one file was instant and another was not.

The picker borrows the Files store, so it browses what Files browses,
shared accounts included, and puts the file manager back where it was on
the way out -- a detour through somebody's shared folder to find an
attachment should not leave Files somewhere else afterwards.

Verified against the mock, and worth recording how, because the first
attempt measured nothing: `client.upload` uses XMLHttpRequest, since it
reports progress, so a counter wrapped around `fetch` sees no uploads
whether or not any happen and agrees with you either way. Counted at
XHR instead: attaching one's own file issues no upload, and attaching a
shared one issues exactly one, to the reader's own account.
This commit is contained in:
2026-08-27 10:18:49 -07:00
parent ad94efb65b
commit 52299ce8ef
3 changed files with 198 additions and 1 deletions
+52
View File
@@ -25,6 +25,15 @@ export interface ComposeAttachment {
abort?: AbortController;
}
/** A file in Files, enough of it to attach. */
export interface AttachableFile {
accountId: Id;
name: string;
type: string | null;
size: number | null;
blobId: Id;
}
export type Priority = "high" | "normal" | "low";
export interface Draft {
@@ -76,6 +85,8 @@ interface ComposeState {
close(key: string, opts?: { discard?: boolean }): Promise<void>;
focus(key: string): void;
addFiles(key: string, files: File[]): void;
/** Attach files already in Files, by reference where the account allows it. */
addFromFiles(key: string, nodes: AttachableFile[]): Promise<void>;
removeAttachment(key: string, attId: string): void;
saveDraft(key: string, opts?: { silent?: boolean }): Promise<Id | null>;
send(key: string): Promise<void>;
@@ -361,6 +372,47 @@ export const useCompose = create<ComposeState>((set, get) => ({
}
},
/*
* Attach something already in Files.
*
* A blob the account can already see needs no upload: an attachment carrying
* a `blobId` is exactly what a forward produces, so the send path already
* knows what to do with one. Attaching a 20 MB file the server is holding
* anyway then costs nothing and takes no time.
*
* A file in an account somebody *shared* is a different matter. Blobs belong
* to the account they were uploaded to, so a draft in your account cannot
* reference one in theirs; it is fetched and uploaded to yours. Slower, and
* unavoidable, but it happens without the reader having to know any of this.
*/
async addFromFiles(key, nodes) {
const accountId = useMail.getState().accountId;
if (!accountId || !nodes.length) return;
const max = client.maxSizeUpload;
const atts: ComposeAttachment[] = nodes.map((n) => ({
id: uid("a"),
name: n.name,
type: n.type || "application/octet-stream",
size: n.size ?? 0,
blobId: n.accountId === accountId ? n.blobId : null,
progress: n.accountId === accountId ? 100 : 0,
error: (n.size ?? 0) > max ? `Larger than ${Math.round(max / 1048576)} MB limit` : null,
}));
get().update(key, { attachments: [...(get().drafts.find((d) => d.key === key)?.attachments ?? []), ...atts] });
for (const [i, a] of atts.entries()) {
if (a.error || a.blobId) continue;
const node = nodes[i]!;
try {
const blob = await client.fetchBlob(node.accountId, node.blobId, a.type);
const up = await client.upload(accountId, blob, { type: a.type });
patchAtt(key, a.id, { blobId: up.blobId, progress: 100, size: up.size || a.size }, set);
} catch (err) {
patchAtt(key, a.id, { error: (err as Error).message || "Could not attach" }, set);
}
}
},
removeAttachment(key, attId) {
const d = get().drafts.find((x) => x.key === key);
const a = d?.attachments.find((x) => x.id === attId);
+8 -1
View File
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { AlertTriangle, ChevronDown, FileText, Maximize2, Minimize2, Minus, MoreVertical, Paperclip, Send, Trash2, X, Type, Clock, CheckCheck, ChevronsDown } from "lucide-react";
import { AlertTriangle, ChevronDown, FileText, FolderOpen, Maximize2, Minimize2, Minus, MoreVertical, Paperclip, Send, Trash2, X, Type, Clock, CheckCheck, ChevronsDown } from "lucide-react";
import { useCompose, type Draft } from "@/store/compose";
import { useMail } from "@/store/mail";
import { useSettings } from "@/store/settings";
@@ -12,6 +12,8 @@ import { formatSize, formatRelative } from "@/lib/format";
import { htmlToText, textToHtml } from "@/lib/text";
import { isValidEmail } from "@/lib/address";
import { attachmentIcon } from "../mail/MessageView";
import { FilePicker } from "./FilePicker";
import { useFiles } from "@/store/files";
import { keyboard } from "@/lib/keyboard";
import { useIsMobile } from "@/ui/misc";
import { toast } from "@/ui/toast";
@@ -25,6 +27,9 @@ export function Composer({ draft }: { draft: Draft }) {
const send = useCompose((s) => s.send);
const saveDraft = useCompose((s) => s.saveDraft);
const addFiles = useCompose((s) => s.addFiles);
const addFromFiles = useCompose((s) => s.addFromFiles);
const filesAvailable = useFiles((s) => s.available);
const [pickerOpen, setPickerOpen] = useState(false);
const removeAttachment = useCompose((s) => s.removeAttachment);
const setIdentity = useCompose((s) => s.setIdentity);
const insertTemplate = useCompose((s) => s.insertTemplate);
@@ -239,11 +244,13 @@ export function Composer({ draft }: { draft: Draft }) {
<MenuItem icon={<Clock size={16} />} label={`Undo window: ${settings.undoSendSeconds}s`} onClick={() => updateSettings({ undoSendSeconds: settings.undoSendSeconds >= 30 ? 0 : settings.undoSendSeconds + 5 })} />
{canSchedule && <ScheduleMenuItems maxMs={scheduleMax} onPick={scheduleFor} onCustom={() => { sendMenu.close(); setScheduleOpen(true); }} />}
</Popover>
{pickerOpen && <FilePicker onPick={(picked) => void addFromFiles(key, picked)} onClose={() => setPickerOpen(false)} />}
{canSchedule && scheduleOpen && (
<ScheduleDialog open maxMs={scheduleMax} initial={d.sendAt} onClose={() => setScheduleOpen(false)} onPick={scheduleFor} />
)}
<span className="more-actions">
<button className="icon-btn" title="Attach files" onClick={() => fileRef.current?.click()}><Paperclip size={18} /></button>
{filesAvailable && <button className="icon-btn" title="Attach from Files" onClick={() => setPickerOpen(true)}><FolderOpen size={18} /></button>}
<input ref={fileRef} type="file" multiple hidden onChange={(e) => { const files = Array.from(e.target.files ?? []); if (files.length) addFiles(key, files); e.target.value = ""; }} />
{d.format === "html" && <button className={`icon-btn ${showToolbar ? "active" : ""}`} title="Formatting options" onClick={() => setShowToolbar((v) => !v)}><Type size={18} /></button>}
{settings.templates.length > 0 && <button className="icon-btn" title="Insert template" onClick={templateMenu.open}><FileText size={18} /></button>}
+138
View File
@@ -0,0 +1,138 @@
import { useEffect, useState } from "react";
import { ChevronRight, File as FileIcon, Folder, HardDrive, Users } from "lucide-react";
import { Dialog } from "@/ui/dialog";
import { Spinner } from "@/ui/misc";
import { useFiles } from "@/store/files";
import type { AttachableFile } from "@/store/compose";
import type { FileNode } from "@/jmap/types";
import { formatSize } from "@/lib/format";
/**
* Pick something already in Files to attach.
*
* Browsing is the store's, so this shows the same folders the Files view does,
* shared accounts included -- a file somebody shared with you is a file you can
* send on, and having to download it first only to upload it again would be
* the sort of detour the rest of this avoids.
*
* It borrows the Files store rather than keeping its own copy, which means
* opening the picker moves where Files is browsing. Closing it puts that back:
* a detour through somebody's shared folder to find an attachment should not
* leave the file manager somewhere else afterwards.
*/
export function FilePicker({ onPick, onClose }: { onPick: (files: AttachableFile[]) => void; onClose: () => void }) {
const files = useFiles();
const [cur, setCur] = useState<string | null>(null);
const [picked, setPicked] = useState<Record<string, FileNode>>({});
const [returnTo] = useState(() => files.accountId);
useEffect(() => {
void files.loadChildren(cur);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [cur, files.accountId]);
const close = () => {
if (files.accountId !== returnTo) files.openAccount(returnTo);
onClose();
};
const openAccount = (accountId: string | null) => {
files.openAccount(accountId);
setCur(null);
setPicked({});
};
const nodes = (files.children[cur ?? "root"] ?? []).map((id) => files.nodes[id]).filter((n): n is FileNode => Boolean(n));
const path = files.pathTo(cur);
const chosen = Object.values(picked);
const viewingShare = files.accountId !== files.ownAccountId;
return (
<Dialog
open
onClose={close}
title="Attach from Files"
size="md"
footer={
<>
<button className="btn" onClick={close}>Cancel</button>
<button
className="btn btn-primary"
disabled={!chosen.length}
onClick={() => {
onPick(chosen.map((n) => ({ accountId: files.accountId!, name: n.name, type: n.type, size: n.size, blobId: n.blobId! })));
close();
}}
>
{chosen.length > 1 ? `Attach ${chosen.length} files` : "Attach"}
</button>
</>
}
>
{files.sharedAccounts.length > 0 && (
<div className="row wrap gap-4" style={{ marginBottom: 10 }}>
<button className={`btn btn-sm ${viewingShare ? "" : "btn-primary"}`} onClick={() => openAccount(files.ownAccountId)}>
<HardDrive size={14} /> My files
</button>
{files.sharedAccounts.map((a) => (
<button key={a.id} className={`btn btn-sm ${files.accountId === a.id ? "btn-primary" : ""}`} onClick={() => openAccount(a.id)}>
<Users size={14} /> {a.name}
</button>
))}
</div>
)}
<div className="breadcrumb mb-8">
<button onClick={() => setCur(null)}><HardDrive size={14} /></button>
{path.map((n) => (
<span key={n.id} className="row gap-4">
<ChevronRight size={12} />
<button onClick={() => setCur(n.id)}>{n.name}</button>
</span>
))}
</div>
{files.loading && !nodes.length ? (
<Spinner />
) : !nodes.length ? (
<p className="hint">This folder is empty.</p>
) : (
nodes.map((n) =>
n.nodeType === "directory" ? (
<button key={n.id} className="menu-item" onClick={() => setCur(n.id)}>
<Folder size={16} />
<span className="grow truncate">{n.name}</span>
<ChevronRight size={14} />
</button>
) : (
<label key={n.id} className="menu-item" style={{ cursor: n.blobId ? "pointer" : "not-allowed", opacity: n.blobId ? 1 : 0.5 }}>
<input
type="checkbox"
disabled={!n.blobId}
checked={Boolean(picked[n.id])}
onChange={(e) =>
setPicked((p) => {
const next = { ...p };
if (e.target.checked) next[n.id] = n;
else delete next[n.id];
return next;
})
}
/>
<FileIcon size={16} />
<span className="grow truncate">{n.name}</span>
<span className="hint">{formatSize(n.size)}</span>
</label>
),
)
)}
{viewingShare && chosen.length > 0 && (
// Blobs belong to the account holding them, so one from a share has to
// be copied into yours before a draft can reference it. Worth saying,
// because it is the difference between instant and a wait.
<p className="hint" style={{ marginTop: 10 }}>Shared files are copied to your account when attached.</p>
)}
</Dialog>
);
}