ihasmail 2.0: rebuild as Stalwart-first JMAP webmail
Replace the FastAPI/HTMX prototype with a Node/Hono session proxy and a React 19/Vite SPA. Mail (conversation view, search operators, labels, sanitised HTML, privacy image proxy, invites, undo send, templates), calendar (month/week/day/agenda, invites, free/busy, categories, context menus), contacts (JSContact, groups, vCard), files, Sieve filter builder (incl. filter-from-message with retroactive apply), vacation, identities with default + Reply-To, PWA/mobile layout, push via SSE, in-memory mock Stalwart for dev, Docker + CI.
This commit is contained in:
@@ -0,0 +1,280 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import { Plus, Trash2, Camera, X } from "lucide-react";
|
||||
import type { ContactCard, JSContactAddress, JSContactEmail, JSContactPhone } from "@/jmap/types";
|
||||
import { useContacts } from "@/store/contacts";
|
||||
import { buildName, contactDisplayName, nameParts, newKey } from "@/lib/contacts";
|
||||
import { Dialog } from "@/ui/dialog";
|
||||
import { toast } from "@/ui/toast";
|
||||
import { client } from "@/jmap/client";
|
||||
|
||||
interface Props {
|
||||
card: Partial<ContactCard>;
|
||||
defaultBookId: string | null;
|
||||
onClose: () => void;
|
||||
onSaved: (id: string) => void;
|
||||
}
|
||||
|
||||
const EMAIL_CTX = ["private", "work", "other"];
|
||||
const PHONE_CTX = ["mobile", "private", "work", "fax", "other"];
|
||||
const ADDR_CTX = ["private", "work", "other"];
|
||||
|
||||
type EmailRow = { key: string; address: string; ctx: string };
|
||||
type PhoneRow = { key: string; number: string; ctx: string };
|
||||
type AddrRow = { key: string; ctx: string; street: string; city: string; region: string; postcode: string; country: string };
|
||||
|
||||
export function ContactEditor({ card, defaultBookId, onClose, onSaved }: Props) {
|
||||
const contacts = useContacts();
|
||||
const isNew = !card.id;
|
||||
const np = card.id ? nameParts(card as ContactCard) : { given: "", surname: "", middle: "", prefix: "", suffix: "" };
|
||||
const [kind, setKind] = useState<"individual" | "group" | "org">((card.kind as "individual" | "group" | "org") ?? "individual");
|
||||
const [given, setGiven] = useState(np.given);
|
||||
const [surname, setSurname] = useState(np.surname);
|
||||
const [prefix, setPrefix] = useState(np.prefix);
|
||||
const [middle, setMiddle] = useState(np.middle);
|
||||
const [suffix, setSuffix] = useState(np.suffix);
|
||||
const [nickname, setNickname] = useState(Object.values(card.nicknames ?? {})[0]?.name ?? "");
|
||||
const [company, setCompany] = useState(Object.values(card.organizations ?? {})[0]?.name ?? "");
|
||||
const [jobTitle, setJobTitle] = useState(Object.values(card.titles ?? {})[0]?.name ?? "");
|
||||
const [emails, setEmails] = useState<EmailRow[]>(() => Object.entries(card.emails ?? {}).map(([key, e]) => ({ key, address: e.address, ctx: Object.keys(e.contexts ?? {})[0] ?? "other" })));
|
||||
const [phones, setPhones] = useState<PhoneRow[]>(() => Object.entries(card.phones ?? {}).map(([key, p]) => ({ key, number: p.number, ctx: Object.keys(p.features ?? {})[0] ?? Object.keys(p.contexts ?? {})[0] ?? "other" })));
|
||||
const [addrs, setAddrs] = useState<AddrRow[]>(() => Object.entries(card.addresses ?? {}).map(([key, a]) => {
|
||||
const get = (k: string) => (a.components ?? []).filter((c) => c.kind === k).map((c) => c.value).join(" ");
|
||||
return { key, ctx: Object.keys(a.contexts ?? {})[0] ?? "other", street: [get("number"), get("name"), get("apartment")].filter(Boolean).join(" ") || (a.full ?? ""), city: get("locality"), region: get("region"), postcode: get("postcode"), country: get("country") };
|
||||
}));
|
||||
const [birthday, setBirthday] = useState(() => {
|
||||
const b = Object.values(card.anniversaries ?? {}).find((a) => a.kind === "birth")?.date;
|
||||
return b?.year && b.month && b.day ? `${b.year}-${String(b.month).padStart(2, "0")}-${String(b.day).padStart(2, "0")}` : "";
|
||||
});
|
||||
const [website, setWebsite] = useState(Object.values(card.links ?? {})[0]?.uri ?? "");
|
||||
const [note, setNote] = useState(Object.values(card.notes ?? {})[0]?.note ?? "");
|
||||
const [bookId, setBookId] = useState(Object.keys(card.addressBookIds ?? {})[0] ?? defaultBookId ?? "");
|
||||
const [photo, setPhoto] = useState<{ dataUrl: string; type: string } | null>(null);
|
||||
const [removePhoto, setRemovePhoto] = useState(false);
|
||||
const [memberUids, setMemberUids] = useState<string[]>(Object.keys(card.members ?? {}));
|
||||
const [memberQuery, setMemberQuery] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const books = Object.values(contacts.books);
|
||||
const existingPhoto = card.id && contacts.accountId ? Object.values(card.media ?? {}).find((m) => m.kind === "photo") : undefined;
|
||||
|
||||
const memberCandidates = useMemo(() => {
|
||||
if (!memberQuery.trim()) return [];
|
||||
return contacts.search(memberQuery).filter((c) => c.kind !== "group" && !memberUids.includes(c.uid)).slice(0, 6);
|
||||
}, [memberQuery, contacts, memberUids]);
|
||||
|
||||
const save = async () => {
|
||||
if (!bookId) {
|
||||
toast.error("Choose an address book");
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
try {
|
||||
const obj: Record<string, unknown> = {};
|
||||
obj.kind = kind;
|
||||
const name = buildName({ given, surname, middle, prefix, suffix });
|
||||
if (kind === "individual") obj.name = name ?? null;
|
||||
else {
|
||||
obj.name = company ? { "@type": "Name", full: company } : (name ?? null);
|
||||
}
|
||||
obj.nicknames = nickname ? { [newKey("n")]: { "@type": "Nickname", name: nickname } } : null;
|
||||
obj.organizations = company ? { [newKey("o")]: { "@type": "Organization", name: company } } : null;
|
||||
obj.titles = jobTitle ? { [newKey("t")]: { "@type": "Title", name: jobTitle, kind: "title" } } : null;
|
||||
const em: Record<string, JSContactEmail> = {};
|
||||
emails.filter((e) => e.address.trim()).forEach((e, i) => { em[e.key] = { "@type": "EmailAddress", address: e.address.trim(), contexts: e.ctx !== "other" ? { [e.ctx]: true } : undefined, pref: i === 0 ? 1 : undefined }; });
|
||||
obj.emails = Object.keys(em).length ? em : null;
|
||||
const ph: Record<string, JSContactPhone> = {};
|
||||
phones.filter((p) => p.number.trim()).forEach((p) => { ph[p.key] = { "@type": "Phone", number: p.number.trim(), ...(["mobile", "fax"].includes(p.ctx) ? { features: { [p.ctx === "mobile" ? "mobile" : "fax"]: true } } : p.ctx !== "other" ? { contexts: { [p.ctx]: true } } : {}) }; });
|
||||
obj.phones = Object.keys(ph).length ? ph : null;
|
||||
const ad: Record<string, JSContactAddress> = {};
|
||||
addrs.filter((a) => a.street || a.city || a.country || a.postcode).forEach((a) => {
|
||||
const components: JSContactAddress["components"] = [];
|
||||
if (a.street) components.push({ "@type": "AddressComponent", kind: "name", value: a.street });
|
||||
if (a.city) components.push({ "@type": "AddressComponent", kind: "locality", value: a.city });
|
||||
if (a.region) components.push({ "@type": "AddressComponent", kind: "region", value: a.region });
|
||||
if (a.postcode) components.push({ "@type": "AddressComponent", kind: "postcode", value: a.postcode });
|
||||
if (a.country) components.push({ "@type": "AddressComponent", kind: "country", value: a.country });
|
||||
ad[a.key] = { "@type": "Address", components, contexts: a.ctx !== "other" ? { [a.ctx]: true } : undefined };
|
||||
});
|
||||
obj.addresses = Object.keys(ad).length ? ad : null;
|
||||
if (birthday) {
|
||||
const [y, m, d] = birthday.split("-").map(Number) as [number, number, number];
|
||||
obj.anniversaries = { [newKey("a")]: { "@type": "Anniversary", kind: "birth", date: { "@type": "PartialDate", year: y, month: m, day: d } } };
|
||||
} else obj.anniversaries = null;
|
||||
obj.links = website ? { [newKey("l")]: { "@type": "Link", uri: /^https?:/i.test(website) ? website : `https://${website}` } } : null;
|
||||
obj.notes = note.trim() ? { [newKey("x")]: { "@type": "Note", note: note.trim() } } : null;
|
||||
obj.members = kind === "group" && memberUids.length ? Object.fromEntries(memberUids.map((u) => [u, true])) : null;
|
||||
if (photo) {
|
||||
const m = /^data:([^;]+);base64,(.*)$/s.exec(photo.dataUrl);
|
||||
if (m) {
|
||||
const bin = atob(m[2]!);
|
||||
const bytes = new Uint8Array(bin.length);
|
||||
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
|
||||
const up = await client.upload(contacts.accountId!, new Blob([bytes], { type: m[1]! }), { type: m[1]! });
|
||||
obj.media = { [newKey("p")]: { "@type": "Media", kind: "photo", blobId: up.blobId, mediaType: m[1]! } };
|
||||
}
|
||||
} else if (removePhoto) obj.media = null;
|
||||
if (isNew) {
|
||||
const id = await contacts.createCard(obj as Partial<ContactCard>, bookId);
|
||||
toast.success("Contact created");
|
||||
onSaved(id);
|
||||
} else {
|
||||
const patch: Record<string, unknown> = { ...obj };
|
||||
const curBook = Object.keys(card.addressBookIds ?? {})[0];
|
||||
if (curBook !== bookId) patch.addressBookIds = { [bookId]: true };
|
||||
if (!photo && !removePhoto) delete patch.media;
|
||||
await contacts.updateCard(card.id!, patch);
|
||||
toast.success("Contact saved");
|
||||
onSaved(card.id!);
|
||||
}
|
||||
} catch (err) {
|
||||
toast.error((err as Error).message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const onPhoto = (f: File) => {
|
||||
const img = new Image();
|
||||
const url = URL.createObjectURL(f);
|
||||
img.onload = () => {
|
||||
const size = 256;
|
||||
const c = document.createElement("canvas");
|
||||
c.width = size;
|
||||
c.height = size;
|
||||
const ctx = c.getContext("2d")!;
|
||||
const s = Math.min(img.width, img.height);
|
||||
ctx.drawImage(img, (img.width - s) / 2, (img.height - s) / 2, s, s, 0, 0, size, size);
|
||||
setPhoto({ dataUrl: c.toDataURL("image/jpeg", 0.85), type: "image/jpeg" });
|
||||
setRemovePhoto(false);
|
||||
URL.revokeObjectURL(url);
|
||||
};
|
||||
img.src = url;
|
||||
};
|
||||
|
||||
const photoSrc = photo?.dataUrl ?? (!removePhoto && existingPhoto ? (existingPhoto.uri?.startsWith("data:") ? existingPhoto.uri : existingPhoto.blobId ? client.downloadUrl(contacts.accountId!, existingPhoto.blobId, "photo", existingPhoto.mediaType ?? "image/jpeg", true) : null) : null);
|
||||
|
||||
return (
|
||||
<Dialog open onClose={onClose} title={isNew ? "New contact" : `Edit ${contactDisplayName(card as ContactCard)}`} size="lg" footer={<><button className="btn" onClick={onClose}>Cancel</button><button className="btn btn-primary" disabled={busy} onClick={() => void save()}>{busy ? "Saving…" : "Save"}</button></>}>
|
||||
<div className="contact-form">
|
||||
<div className="row" style={{ gap: 16, marginBottom: 12 }}>
|
||||
<label className="avatar xl" style={{ background: "var(--bg-sunken)", color: "var(--fg-muted)", cursor: "pointer", position: "relative" }} title="Change photo">
|
||||
{photoSrc ? <img src={photoSrc} alt="" /> : <Camera size={28} />}
|
||||
<input type="file" accept="image/*" hidden onChange={(e) => { const f = e.target.files?.[0]; if (f) onPhoto(f); e.target.value = ""; }} />
|
||||
</label>
|
||||
{photoSrc && <button className="btn btn-ghost btn-sm" onClick={() => { setPhoto(null); setRemovePhoto(true); }}><X size={14} /> Remove photo</button>}
|
||||
<span className="spacer" />
|
||||
<div className="field" style={{ marginBottom: 0, width: 160 }}>
|
||||
<label>Type</label>
|
||||
<select className="select" value={kind} onChange={(e) => setKind(e.target.value as typeof kind)}>
|
||||
<option value="individual">Person</option>
|
||||
<option value="org">Organization</option>
|
||||
<option value="group">Group</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="field" style={{ marginBottom: 0, width: 200 }}>
|
||||
<label>Address book</label>
|
||||
<select className="select" value={bookId} onChange={(e) => setBookId(e.target.value)}>
|
||||
{books.map((b) => <option key={b.id} value={b.id}>{b.name}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
{kind === "individual" ? (
|
||||
<>
|
||||
<div className="field-row">
|
||||
<div className="field"><label>First name</label><input className="input" value={given} onChange={(e) => setGiven(e.target.value)} autoFocus /></div>
|
||||
<div className="field"><label>Last name</label><input className="input" value={surname} onChange={(e) => setSurname(e.target.value)} /></div>
|
||||
</div>
|
||||
<details>
|
||||
<summary className="hint" style={{ cursor: "pointer", marginBottom: 8 }}>More name fields</summary>
|
||||
<div className="field-row">
|
||||
<div className="field"><label>Prefix</label><input className="input" value={prefix} onChange={(e) => setPrefix(e.target.value)} placeholder="Dr." /></div>
|
||||
<div className="field"><label>Middle name</label><input className="input" value={middle} onChange={(e) => setMiddle(e.target.value)} /></div>
|
||||
<div className="field"><label>Suffix</label><input className="input" value={suffix} onChange={(e) => setSuffix(e.target.value)} placeholder="Jr." /></div>
|
||||
<div className="field"><label>Nickname</label><input className="input" value={nickname} onChange={(e) => setNickname(e.target.value)} /></div>
|
||||
</div>
|
||||
</details>
|
||||
<div className="field-row">
|
||||
<div className="field"><label>Company</label><input className="input" value={company} onChange={(e) => setCompany(e.target.value)} /></div>
|
||||
<div className="field"><label>Job title</label><input className="input" value={jobTitle} onChange={(e) => setJobTitle(e.target.value)} /></div>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="field"><label>{kind === "group" ? "Group name" : "Organization name"}</label><input className="input" value={company} onChange={(e) => setCompany(e.target.value)} autoFocus /></div>
|
||||
)}
|
||||
|
||||
{kind === "group" && (
|
||||
<div className="field">
|
||||
<label>Members</label>
|
||||
<div className="row wrap gap-4 mb-8">
|
||||
{memberUids.map((uid) => {
|
||||
const m = Object.values(contacts.cards).find((x) => x.uid === uid);
|
||||
return <span key={uid} className="chip">{m ? contactDisplayName(m) : uid}<button className="chip-x" onClick={() => setMemberUids(memberUids.filter((u) => u !== uid))}><X size={12} /></button></span>;
|
||||
})}
|
||||
</div>
|
||||
<div style={{ position: "relative" }}>
|
||||
<input className="input" placeholder="Search contacts to add…" value={memberQuery} onChange={(e) => setMemberQuery(e.target.value)} />
|
||||
{memberCandidates.length > 0 && (
|
||||
<div className="suggest-list" style={{ width: "100%" }}>
|
||||
{memberCandidates.map((c) => <div key={c.id} className="suggest-item" onMouseDown={(e) => { e.preventDefault(); setMemberUids([...memberUids, c.uid]); setMemberQuery(""); }}><span className="s-name">{contactDisplayName(c)}</span><span className="s-email">{Object.values(c.emails ?? {})[0]?.address}</span></div>)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="field">
|
||||
<label>Email</label>
|
||||
<div className="multi">
|
||||
{emails.map((e, i) => (
|
||||
<div key={e.key} className="multi-row">
|
||||
<input className="input" type="email" value={e.address} placeholder="[email protected]" onChange={(ev) => setEmails(emails.map((x, j) => (j === i ? { ...x, address: ev.target.value } : x)))} />
|
||||
<select className="select" value={e.ctx} onChange={(ev) => setEmails(emails.map((x, j) => (j === i ? { ...x, ctx: ev.target.value } : x)))}>{EMAIL_CTX.map((c) => <option key={c} value={c}>{c}</option>)}</select>
|
||||
<button className="icon-btn sm danger" onClick={() => setEmails(emails.filter((_, j) => j !== i))} aria-label="Remove"><Trash2 size={16} /></button>
|
||||
</div>
|
||||
))}
|
||||
<button className="btn btn-ghost btn-sm" style={{ alignSelf: "flex-start" }} onClick={() => setEmails([...emails, { key: newKey("e"), address: "", ctx: emails.length ? "work" : "private" }])}><Plus size={14} /> Add email</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label>Phone</label>
|
||||
<div className="multi">
|
||||
{phones.map((p, i) => (
|
||||
<div key={p.key} className="multi-row">
|
||||
<input className="input" type="tel" value={p.number} placeholder="+1 555 0100" onChange={(ev) => setPhones(phones.map((x, j) => (j === i ? { ...x, number: ev.target.value } : x)))} />
|
||||
<select className="select" value={p.ctx} onChange={(ev) => setPhones(phones.map((x, j) => (j === i ? { ...x, ctx: ev.target.value } : x)))}>{PHONE_CTX.map((c) => <option key={c} value={c}>{c}</option>)}</select>
|
||||
<button className="icon-btn sm danger" onClick={() => setPhones(phones.filter((_, j) => j !== i))} aria-label="Remove"><Trash2 size={16} /></button>
|
||||
</div>
|
||||
))}
|
||||
<button className="btn btn-ghost btn-sm" style={{ alignSelf: "flex-start" }} onClick={() => setPhones([...phones, { key: newKey("p"), number: "", ctx: "mobile" }])}><Plus size={14} /> Add phone</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label>Address</label>
|
||||
<div className="multi">
|
||||
{addrs.map((a, i) => (
|
||||
<div key={a.key} className="card" style={{ marginBottom: 0 }}>
|
||||
<div className="row mb-8">
|
||||
<select className="select" style={{ width: 140 }} value={a.ctx} onChange={(ev) => setAddrs(addrs.map((x, j) => (j === i ? { ...x, ctx: ev.target.value } : x)))}>{ADDR_CTX.map((c) => <option key={c} value={c}>{c}</option>)}</select>
|
||||
<span className="spacer" />
|
||||
<button className="icon-btn sm danger" onClick={() => setAddrs(addrs.filter((_, j) => j !== i))} aria-label="Remove"><Trash2 size={16} /></button>
|
||||
</div>
|
||||
<div className="addr-grid">
|
||||
<input className="input" style={{ gridColumn: "1 / -1" }} placeholder="Street" value={a.street} onChange={(ev) => setAddrs(addrs.map((x, j) => (j === i ? { ...x, street: ev.target.value } : x)))} />
|
||||
<input className="input" placeholder="City" value={a.city} onChange={(ev) => setAddrs(addrs.map((x, j) => (j === i ? { ...x, city: ev.target.value } : x)))} />
|
||||
<input className="input" placeholder="State / Region" value={a.region} onChange={(ev) => setAddrs(addrs.map((x, j) => (j === i ? { ...x, region: ev.target.value } : x)))} />
|
||||
<input className="input" placeholder="Postal code" value={a.postcode} onChange={(ev) => setAddrs(addrs.map((x, j) => (j === i ? { ...x, postcode: ev.target.value } : x)))} />
|
||||
<input className="input" placeholder="Country" value={a.country} onChange={(ev) => setAddrs(addrs.map((x, j) => (j === i ? { ...x, country: ev.target.value } : x)))} />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
<button className="btn btn-ghost btn-sm" style={{ alignSelf: "flex-start" }} onClick={() => setAddrs([...addrs, { key: newKey("a"), ctx: "private", street: "", city: "", region: "", postcode: "", country: "" }])}><Plus size={14} /> Add address</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="field-row">
|
||||
<div className="field"><label>Birthday</label><input className="input" type="date" value={birthday} onChange={(e) => setBirthday(e.target.value)} /></div>
|
||||
<div className="field"><label>Website</label><input className="input" value={website} onChange={(e) => setWebsite(e.target.value)} placeholder="https://" /></div>
|
||||
</div>
|
||||
<div className="field"><label>Notes</label><textarea className="textarea" value={note} onChange={(e) => setNote(e.target.value)} /></div>
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useLocation } from "wouter";
|
||||
import { ArrowLeft, Book, Download, Mail, MoreVertical, Pencil, Plus, Search, Share2, Trash2, Upload, Users, Phone, MapPin, Building2, Cake, StickyNote, Globe, Calendar as CalIcon, Star, Pin } from "lucide-react";
|
||||
import { useContacts } from "@/store/contacts";
|
||||
import { useCompose } from "@/store/compose";
|
||||
import type { AddressBook, ContactCard } from "@/jmap/types";
|
||||
import { contactDisplayName, contactEmails, contactPhoto, formatAddressLines, sortKey, toVCard } from "@/lib/contacts";
|
||||
import { Avatar, Empty, Spinner, useIsNarrow } from "@/ui/misc";
|
||||
import { MenuItem, MenuSep, Popover, useMenu } from "@/ui/popover";
|
||||
import { confirmDialog, promptDialog } from "@/ui/dialog";
|
||||
import { toast } from "@/ui/toast";
|
||||
import { ContactEditor } from "./ContactEditor";
|
||||
import { ShareDialog } from "../settings/ShareDialog";
|
||||
import { avatarColor } from "@/lib/address";
|
||||
|
||||
export function ContactsView({ id }: { id?: string }) {
|
||||
const [, navigate] = useLocation();
|
||||
const contacts = useContacts();
|
||||
const narrow = useIsNarrow();
|
||||
const [q, setQ] = useState("");
|
||||
const [bookId, setBookId] = useState<string | "all">("all");
|
||||
const [editing, setEditing] = useState<Partial<ContactCard> | null>(null);
|
||||
const [share, setShare] = useState<AddressBook | null>(null);
|
||||
const bookMenu = useMenu();
|
||||
const [menuBook, setMenuBook] = useState<AddressBook | null>(null);
|
||||
const openCompose = useCompose((s) => s.open);
|
||||
|
||||
useEffect(() => {
|
||||
if (contacts.available && !contacts.loaded && !contacts.loading) void contacts.loadAll();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [contacts.available, contacts.loaded]);
|
||||
|
||||
useEffect(() => {
|
||||
const onNew = () => setEditing({});
|
||||
window.addEventListener("ihm:new-contact", onNew);
|
||||
return () => window.removeEventListener("ihm:new-contact", onNew);
|
||||
}, []);
|
||||
|
||||
const list = useMemo(() => {
|
||||
const all = contacts.search(q);
|
||||
return bookId === "all" ? all : all.filter((c) => c.addressBookIds?.[bookId]);
|
||||
}, [contacts, q, bookId]);
|
||||
|
||||
const selected = id ? contacts.cards[id] : undefined;
|
||||
const books = Object.values(contacts.books).sort((a, b) => a.sortOrder - b.sortOrder || a.name.localeCompare(b.name));
|
||||
const groups = useMemo(() => {
|
||||
const out: Array<{ letter: string; items: ContactCard[] }> = [];
|
||||
for (const c of list) {
|
||||
const letter = (sortKey(c)[0] ?? "#").toUpperCase();
|
||||
const key = /[A-Z]/.test(letter) ? letter : "#";
|
||||
const g = out[out.length - 1];
|
||||
if (g && g.letter === key) g.items.push(c);
|
||||
else out.push({ letter: key, items: [c] });
|
||||
}
|
||||
return out;
|
||||
}, [list]);
|
||||
|
||||
if (!contacts.available) {
|
||||
return <div className="p-16"><Empty icon={<Users size={40} />} title="Contacts are not available">This account does not have the JMAP contacts capability.</Empty></div>;
|
||||
}
|
||||
|
||||
const exportAll = () => {
|
||||
const text = list.map(toVCard).join("");
|
||||
const a = document.createElement("a");
|
||||
a.href = URL.createObjectURL(new Blob([text], { type: "text/vcard" }));
|
||||
a.download = "contacts.vcf";
|
||||
a.click();
|
||||
};
|
||||
|
||||
const importFile = async (f: File) => {
|
||||
const book = bookId !== "all" ? contacts.books[bookId] : (books.find((b) => b.isDefault) ?? books[0]);
|
||||
if (!book) {
|
||||
toast.error("Create an address book first");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const n = await contacts.importVCard(await f.text(), book.id);
|
||||
toast.success(`Imported ${n} contact${n === 1 ? "" : "s"}`);
|
||||
} catch (err) {
|
||||
toast.error((err as Error).message);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={`contacts-layout ${selected || editing ? "detail" : ""}`}>
|
||||
<aside className="contacts-books">
|
||||
<button className={`nav-item ${bookId === "all" ? "active" : ""}`} style={{ width: "100%" }} onClick={() => setBookId("all")}>
|
||||
<Users size={18} /><span className="nav-label">All contacts</span><span className="nav-count">{Object.keys(contacts.cards).length}</span>
|
||||
</button>
|
||||
<div className="nav-section"><span>Address books</span>
|
||||
<button className="icon-btn" title="New address book" onClick={async () => { const n = await promptDialog({ title: "New address book", placeholder: "Name" }); if (n?.trim()) { try { await contacts.createBook(n.trim()); } catch (err) { toast.error((err as Error).message); } } }}><Plus size={16} /></button>
|
||||
</div>
|
||||
{books.map((b) => (
|
||||
<button key={b.id} className={`nav-item ${bookId === b.id ? "active" : ""}`} style={{ width: "100%" }} onClick={() => setBookId(b.id)} onContextMenu={(e) => { e.preventDefault(); setMenuBook(b); bookMenu.openAt(e.clientX, e.clientY); }}>
|
||||
<Book size={18} /><span className="nav-label">{b.name}</span>
|
||||
<span className="icon-btn nav-more" onClick={(e) => { e.stopPropagation(); setMenuBook(b); bookMenu.open(e); }}><MoreVertical size={16} /></span>
|
||||
</button>
|
||||
))}
|
||||
<div style={{ padding: "12px 8px" }} className="col gap-8">
|
||||
<label className="btn btn-sm btn-block"><Upload size={14} /> Import vCard<input type="file" accept=".vcf,text/vcard" hidden onChange={(e) => { const f = e.target.files?.[0]; if (f) void importFile(f); e.target.value = ""; }} /></label>
|
||||
<button className="btn btn-sm btn-block" onClick={exportAll}><Download size={14} /> Export {bookId === "all" ? "all" : "book"}</button>
|
||||
</div>
|
||||
<Popover anchor={bookMenu.anchor} onClose={bookMenu.close} width={220}>
|
||||
{menuBook && (
|
||||
<>
|
||||
<MenuItem icon={<Pencil size={16} />} label="Rename" onClick={async () => { const n = await promptDialog({ title: "Rename address book", defaultValue: menuBook.name }); if (n?.trim()) void contacts.updateBook(menuBook.id, { name: n.trim() }).catch((err) => toast.error((err as Error).message)); }} />
|
||||
<MenuItem icon={<Share2 size={16} />} label="Share…" onClick={() => setShare(menuBook)} />
|
||||
<MenuItem icon={<Star size={16} />} label={menuBook.isDefault ? "Default book" : "Make default"} disabled={menuBook.isDefault} onClick={() => void contacts.updateBook(menuBook.id, { isDefault: true } as Partial<AddressBook>).catch((err) => toast.error((err as Error).message))} />
|
||||
<MenuSep />
|
||||
<MenuItem danger icon={<Trash2 size={16} />} label="Delete" disabled={!menuBook.myRights.mayDelete} onClick={async () => { if (await confirmDialog({ title: `Delete “${menuBook.name}”?`, message: "All contacts in it will be deleted.", confirmLabel: "Delete", danger: true })) void contacts.destroyBook(menuBook.id).catch((err) => toast.error((err as Error).message)); }} />
|
||||
</>
|
||||
)}
|
||||
</Popover>
|
||||
</aside>
|
||||
|
||||
<section className="contacts-list">
|
||||
<div className="list-search row">
|
||||
<div className="search-input" style={{ flex: 1, height: 38, background: "var(--bg-sunken)", borderRadius: 999, display: "flex", alignItems: "center", gap: 8, padding: "0 12px" }}>
|
||||
<Search size={16} className="muted" />
|
||||
<input style={{ flex: 1, border: 0, background: "transparent", outline: "none" }} placeholder="Search contacts" value={q} onChange={(e) => setQ(e.target.value)} />
|
||||
</div>
|
||||
<button className="icon-btn" title="New contact" onClick={() => setEditing({})}><Plus size={20} /></button>
|
||||
</div>
|
||||
<div className="contacts-scroll">
|
||||
{contacts.loading && !contacts.loaded ? <Spinner label="Loading contacts…" /> : !list.length ? (
|
||||
<Empty icon={<Users size={36} />} title={q ? "No matches" : "No contacts yet"}>{q ? "Try another search." : "Add a contact or import a vCard file."}</Empty>
|
||||
) : groups.map((g) => (
|
||||
<div key={g.letter}>
|
||||
<div className="contact-letter">{g.letter}</div>
|
||||
{g.items.map((c) => {
|
||||
const email = contactEmails(c)[0]?.email;
|
||||
const photo = contacts.accountId ? contactPhoto(c, contacts.accountId) : null;
|
||||
return (
|
||||
<div key={c.id} className={`contact-row ${id === c.id ? "active" : ""}`} onClick={() => navigate(`/contacts/${c.id}`)}>
|
||||
<span className="avatar" style={{ background: photo ? "transparent" : avatarColor(email ?? contactDisplayName(c)) }}>{photo ? <img src={photo} alt="" /> : c.kind === "group" ? <Users size={16} /> : contactDisplayName(c).slice(0, 1).toUpperCase()}</span>
|
||||
<div className="grow" style={{ minWidth: 0 }}>
|
||||
<div className="c-name">{contactDisplayName(c)}{c.kind === "group" ? <span className="hint"> · group</span> : ""}</div>
|
||||
<div className="c-email">{email ?? Object.values(c.phones ?? {})[0]?.number ?? Object.values(c.organizations ?? {})[0]?.name ?? ""}</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="contact-detail">
|
||||
{selected ? (
|
||||
<ContactDetail card={selected} onBack={() => navigate("/contacts")} onEdit={() => setEditing(selected)} narrow={narrow} onEmail={(addr) => openCompose({ to: [{ name: contactDisplayName(selected), email: addr }] })} />
|
||||
) : (
|
||||
<div className="no-thread"><Users size={48} style={{ color: "var(--fg-faint)" }} /><div>Select a contact</div></div>
|
||||
)}
|
||||
</section>
|
||||
{editing && <ContactEditor card={editing} defaultBookId={bookId !== "all" ? bookId : (books.find((b) => b.isDefault)?.id ?? books[0]?.id ?? null)} onClose={() => setEditing(null)} onSaved={(cid) => { setEditing(null); navigate(`/contacts/${cid}`); }} />}
|
||||
{share && <ShareDialog kind="AddressBook" id={share.id} name={share.name} shareWith={share.shareWith} onClose={() => setShare(null)} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ContactDetail({ card: c, onBack, onEdit, narrow, onEmail }: { card: ContactCard; onBack: () => void; onEdit: () => void; narrow: boolean; onEmail: (addr: string) => void }) {
|
||||
const contacts = useContacts();
|
||||
const [, navigate] = useLocation();
|
||||
const photo = contacts.accountId ? contactPhoto(c, contacts.accountId) : null;
|
||||
const name = contactDisplayName(c);
|
||||
const org = Object.values(c.organizations ?? {})[0];
|
||||
const title = Object.values(c.titles ?? {})[0];
|
||||
const books = Object.keys(c.addressBookIds ?? {}).map((id) => contacts.books[id]?.name).filter(Boolean);
|
||||
const members = c.kind === "group" ? Object.keys(c.members ?? {}).map((uid) => Object.values(contacts.cards).find((x) => x.uid === uid)).filter((x): x is ContactCard => Boolean(x)) : [];
|
||||
const ctxLabel = (ctx?: Record<string, boolean>, label?: string) => label || Object.keys(ctx ?? {}).join(", ") || "";
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="row" style={{ marginBottom: 12 }}>
|
||||
{narrow && <button className="icon-btn" onClick={onBack} aria-label="Back"><ArrowLeft size={20} /></button>}
|
||||
<span className="spacer" />
|
||||
<button className="btn btn-sm" onClick={onEdit}><Pencil size={14} /> Edit</button>
|
||||
<button className="btn btn-sm" onClick={() => { const a = document.createElement("a"); a.href = URL.createObjectURL(new Blob([toVCard(c)], { type: "text/vcard" })); a.download = `${name.replace(/[^\w.-]+/g, "_")}.vcf`; a.click(); }}><Download size={14} /> vCard</button>
|
||||
<button className="btn btn-sm btn-ghost" style={{ color: "var(--danger)" }} onClick={async () => { if (await confirmDialog({ title: `Delete ${name}?`, confirmLabel: "Delete", danger: true })) { try { await contacts.destroyCards([c.id]); toast.success("Contact deleted"); navigate("/contacts"); } catch (err) { toast.error((err as Error).message); } } }}><Trash2 size={14} /></button>
|
||||
</div>
|
||||
<div className="contact-hero">
|
||||
<span className="avatar xl" style={{ background: photo ? "transparent" : avatarColor(contactEmails(c)[0]?.email ?? name) }}>{photo ? <img src={photo} alt="" /> : c.kind === "group" ? <Users size={36} /> : name.slice(0, 1).toUpperCase()}</span>
|
||||
<div>
|
||||
<h1>{name}</h1>
|
||||
{(title?.name || org?.name) && <div className="sub">{[title?.name, org?.name].filter(Boolean).join(" · ")}</div>}
|
||||
{Object.values(c.nicknames ?? {})[0]?.name && <div className="sub">“{Object.values(c.nicknames ?? {})[0]!.name}”</div>}
|
||||
{books.length > 0 && <div className="hint">{books.join(", ")}</div>}
|
||||
</div>
|
||||
</div>
|
||||
{Object.values(c.emails ?? {}).length > 0 && (
|
||||
<div className="contact-section"><h3>Email</h3>
|
||||
{Object.values(c.emails ?? {}).map((e, i) => (
|
||||
<div key={i} className="contact-kv"><span className="k">{ctxLabel(e.contexts, e.label) || "email"}</span><span className="v row gap-8"><a href={`mailto:${e.address}`} onClick={(ev) => { ev.preventDefault(); onEmail(e.address); }}>{e.address}</a><button className="icon-btn xs" title="Compose" onClick={() => onEmail(e.address)}><Mail size={14} /></button></span></div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{Object.values(c.phones ?? {}).length > 0 && (
|
||||
<div className="contact-section"><h3>Phone</h3>
|
||||
{Object.values(c.phones ?? {}).map((p, i) => (
|
||||
<div key={i} className="contact-kv"><span className="k">{ctxLabel({ ...p.contexts, ...p.features }, p.label) || "phone"}</span><span className="v row gap-8"><Phone size={14} className="muted" /><a href={`tel:${p.number}`}>{p.number}</a></span></div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{Object.values(c.addresses ?? {}).length > 0 && (
|
||||
<div className="contact-section"><h3>Address</h3>
|
||||
{Object.values(c.addresses ?? {}).map((a, i) => (
|
||||
<div key={i} className="contact-kv"><span className="k">{ctxLabel(a.contexts) || "address"}</span><span className="v row gap-8" style={{ alignItems: "flex-start" }}><MapPin size={14} className="muted" style={{ marginTop: 3 }} /><span>{formatAddressLines(a).map((l, j) => <div key={j}>{l}</div>)}</span></span></div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{(org || Object.values(c.titles ?? {}).length > 1) && (
|
||||
<div className="contact-section"><h3>Work</h3>
|
||||
{org?.name && <div className="contact-kv"><span className="k">Company</span><span className="v row gap-8"><Building2 size={14} className="muted" />{org.name}{org.units?.length ? ` · ${org.units.map((u) => u.name).join(", ")}` : ""}</span></div>}
|
||||
{Object.values(c.titles ?? {}).map((t, i) => <div key={i} className="contact-kv"><span className="k">{t.kind === "role" ? "Role" : "Title"}</span><span className="v">{t.name}</span></div>)}
|
||||
</div>
|
||||
)}
|
||||
{Object.values(c.anniversaries ?? {}).length > 0 && (
|
||||
<div className="contact-section"><h3>Dates</h3>
|
||||
{Object.values(c.anniversaries ?? {}).map((a, i) => <div key={i} className="contact-kv"><span className="k">{a.kind === "birth" ? "Birthday" : a.kind === "wedding" ? "Anniversary" : a.kind}</span><span className="v row gap-8"><Cake size={14} className="muted" />{fmtPartial(a.date)}</span></div>)}
|
||||
</div>
|
||||
)}
|
||||
{(Object.values(c.links ?? {}).length > 0 || Object.values(c.onlineServices ?? {}).length > 0) && (
|
||||
<div className="contact-section"><h3>Online</h3>
|
||||
{Object.values(c.links ?? {}).map((l, i) => <div key={`l${i}`} className="contact-kv"><span className="k">{l.label ?? "Website"}</span><span className="v row gap-8"><Globe size={14} className="muted" /><a href={l.uri} target="_blank" rel="noreferrer">{l.uri}</a></span></div>)}
|
||||
{Object.values(c.onlineServices ?? {}).map((s, i) => <div key={`s${i}`} className="contact-kv"><span className="k">{s.service ?? s.label ?? "IM"}</span><span className="v">{s.user ?? s.uri}</span></div>)}
|
||||
</div>
|
||||
)}
|
||||
{Object.values(c.notes ?? {}).length > 0 && (
|
||||
<div className="contact-section"><h3>Notes</h3>
|
||||
{Object.values(c.notes ?? {}).map((n, i) => <div key={i} className="contact-kv"><span className="k"><StickyNote size={14} /></span><span className="v" style={{ whiteSpace: "pre-wrap" }}>{n.note}</span></div>)}
|
||||
</div>
|
||||
)}
|
||||
{c.kind === "group" && (
|
||||
<div className="contact-section"><h3>Members ({Object.keys(c.members ?? {}).length})</h3>
|
||||
{members.map((m) => <div key={m.id} className="contact-kv"><span className="k"><Avatar who={{ name: contactDisplayName(m), email: contactEmails(m)[0]?.email }} size="sm" /></span><span className="v"><a href={`/contacts/${m.id}`} onClick={(e) => { e.preventDefault(); navigate(`/contacts/${m.id}`); }}>{contactDisplayName(m)}</a> <span className="hint">{contactEmails(m)[0]?.email}</span></span></div>)}
|
||||
{members.length > 0 && <button className="btn btn-sm mt-8" onClick={() => useCompose.getState().open({ to: members.flatMap((m) => contactEmails(m).slice(0, 1)) })}><Mail size={14} /> Email group</button>}
|
||||
</div>
|
||||
)}
|
||||
{c.keywords && Object.keys(c.keywords).length > 0 && <div className="row wrap gap-4 mt-8">{Object.keys(c.keywords).map((k) => <span key={k} className="chip"><Pin size={12} /> {k}</span>)}</div>}
|
||||
{c.updated && <p className="hint mt-16"><CalIcon size={12} /> Updated {new Date(c.updated).toLocaleDateString()}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function fmtPartial(d: { year?: number; month?: number; day?: number; utc?: string }): string {
|
||||
if (d.utc) return new Date(d.utc).toLocaleDateString();
|
||||
if (d.year && d.month && d.day) return new Date(d.year, d.month - 1, d.day).toLocaleDateString(undefined, { year: "numeric", month: "long", day: "numeric" });
|
||||
if (d.month && d.day) return new Date(2000, d.month - 1, d.day).toLocaleDateString(undefined, { month: "long", day: "numeric" });
|
||||
return [d.year, d.month, d.day].filter(Boolean).join("-");
|
||||
}
|
||||
Reference in New Issue
Block a user