Skip to content

Native iCloud apps for Windows and Linux, built in Rust. Notes, Reminders, Calendar, Contacts, Drive and Photos, offline and in sync with your iPhone.

Contacts: lists sidebar — create, rename, delete, add by menu or drag, remove; instant, merged with Apple's copy

Yashwanth Kamireddia563c33ba46c
diff --git a/.uiverify/contacts-lists.mjs b/.uiverify/contacts-lists.mjs
new file mode 100644
index 0000000..acec60c
--- /dev/null
+++ b/.uiverify/contacts-lists.mjs
@@ -0,0 +1,107 @@
+// Contacts' lists, as on the Mac and icloud.com: All Contacts and each list in a column,
+// a list shows only its people, and every change — a new list, a rename, someone added by
+// menu or by dragging, someone taken out, a list deleted — shows the moment it is made,
+// though Apple takes most of a second to answer. A change Apple refuses goes back.
+import { engine } from "./engine.mjs";
+import { SERVICES, installStub, openScreen } from "./stub.mjs";
+const b = await engine.launch();
+const ctx = await b.newContext({ viewport: { width: 1280, height: 800 } });
+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, contactsFixture: true });
+const page = await ctx.newPage();
+page.on("dialog", (d) => d.accept());
+await page.goto("http://localhost:4173", { waitUntil: "networkidle" });
+await openScreen(page, "Contacts");
+await page.waitForTimeout(400);
+
+const failures = [];
+const check = (ok, what) => {
+ console.log(`${ok ? "ok " : "FAIL"} ${what}`);
+ if (!ok) failures.push(what);
+};
+const side = page.locator(".contacts-lists");
+const row = (name) => side.locator(".notes-folder-row", { has: page.locator(".notes-folder-name", { hasText: new RegExp(`^${name}$`) }) });
+// textContent, not innerText: a hovered row hides its count to make room for its ⋯.
+const count = async (name) => Number((await row(name).locator(".notes-folder-count").textContent()).trim() || 0);
+const people = async () =>
+ (await page.locator(".contact-row-name").allInnerTexts()).map((t) => t.trim());
+const quick = 200; // well inside the stub's 700 ms answer
+
+check((await side.locator(".notes-folder-name").allInnerTexts()).join("|") === "All Contacts|Family", "the column holds All Contacts, then the lists");
+await row("Family").locator(".notes-folder").click();
+check((await page.locator(".contacts-list h1").innerText()) === "Family", "a list's name heads the people");
+check(JSON.stringify(await people()) === JSON.stringify(["Amma"]), "a list shows only its people");
+
+// Add by the right-click menu, a step into its lists.
+await row("All Contacts").locator(".notes-folder").click();
+await page.locator(".contact-row", { hasText: "Zoya Ahuja" }).click({ button: "right" });
+await page.getByRole("menuitem", { name: "Add to List…" }).click();
+await page.getByRole("menuitem", { name: "Family" }).click();
+await page.waitForTimeout(quick);
+check((await count("Family")) === 2, "added by menu, the count moves at once");
+
+// A new list, named in place.
+await side.getByRole("button", { name: "New List" }).click();
+const naming = side.getByRole("textbox", { name: "New list name" });
+check(await naming.isVisible(), "New List opens its name for typing straight away");
+await naming.fill("Work");
+await naming.press("Enter");
+await page.waitForTimeout(quick);
+check(await row("Work").isVisible(), "the new list is in the column at once");
+await page.waitForTimeout(900);
+
+// Dragged onto a list, as on the Mac.
+await page.locator(".contact-rows > li", { hasText: "Northfield University" }).dragTo(row("Work"));
+await page.waitForTimeout(quick);
+check((await count("Work")) === 1, "a contact dragged onto a list joins it at once");
+await page.waitForTimeout(900);
+
+// Rename from the row's ⋯.
+await row("Work").hover();
+await row("Work").getByRole("button", { name: "Actions for Work" }).click();
+await page.getByRole("menuitem", { name: "Rename List" }).click();
+const rename = side.getByRole("textbox", { name: "Rename Work" });
+await rename.fill("Office");
+await rename.press("Enter");
+await page.waitForTimeout(quick);
+check(await row("Office").isVisible(), "a rename shows at once");
+await page.waitForTimeout(900);
+
+// Taken out from the card.
+await row("Office").locator(".notes-folder").click();
+await page.locator(".contact-row", { hasText: "Northfield University" }).click();
+await page.getByRole("button", { name: "Remove from List" }).click();
+await page.waitForTimeout(quick);
+check((await people()).length === 0 && (await count("Office")) === 0, "taken out of a list, they leave it at once");
+await page.waitForTimeout(900);
+
+// Refused by Apple: drawn, then put back, with the reason.
+await page.evaluate(() => { window.__listFail = true; });
+await row("All Contacts").locator(".notes-folder").click();
+await page.locator(".contact-row", { hasText: "Zoya Ahuja" }).click();
+await page.getByRole("button", { name: "Add to List" }).click();
+await page.getByRole("menuitem", { name: "Office" }).click();
+await page.waitForTimeout(quick);
+const drawn = await count("Office");
+await page.waitForTimeout(1100);
+check(drawn === 1 && (await count("Office")) === 0, "a refused add shows, then goes back");
+check(await page.locator(".notice").first().isVisible().catch(() => false), "and says why");
+await page.evaluate(() => { window.__listFail = false; });
+
+// Deleted.
+await row("Office").hover();
+await row("Office").getByRole("button", { name: "Actions for Office" }).click();
+await page.getByRole("menuitem", { name: "Delete List…" }).click();
+await page.waitForTimeout(quick);
+check((await row("Office").count()) === 0, "a deleted list leaves the column at once");
+await page.waitForTimeout(900);
+
+const writes = await page.evaluate(() => window.__listWrites);
+check(
+ JSON.stringify(writes.map((w) => Object.keys(w).sort().join(","))) ===
+ JSON.stringify(["add,guid", "add,name", "add,guid", "guid,name", "guid,remove", "add,guid", "delete,guid"]),
+ "each change goes to Apple as what changed, not a guessed whole list"
+);
+
+await b.close();
+console.log(failures.length ? `FAIL ${failures.length} contacts-lists check(s)` : "PASS contacts lists, instant and as Apple keeps them");
+process.exitCode = failures.length ? 1 : 0;
diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjs
index 96a0ae0..7b0a854 100644
--- a/.uiverify/stub.mjs
+++ b/.uiverify/stub.mjs
@@ -235,6 +235,27 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
case "contact_save": (window.__contactSaves ??= []).push(args); return "C-new";
case "contact_delete": return null;
case "contacts_list": return !contactsFixture ? [] : contactList;
+ case "contact_lists": return !contactsFixture ? [] : (window.__lists ??= [
+ { guid: "L1", name: "Family", members: ["c2"], etag: "e1" },
+ ]).map((l) => ({ ...l, members: [...l.members] }));
+ case "contact_list_write": {
+ // Slow on purpose, as Apple is: the screen must not wait for this to redraw.
+ (window.__listWrites ??= []).push(args);
+ await new Promise((r) => setTimeout(r, 700));
+ if (window.__listFail) throw "Contacts refused the list.";
+ const lists = (window.__lists ??= [{ guid: "L1", name: "Family", members: ["c2"], etag: "e1" }]);
+ if (!args.guid) {
+ const guid = `L${lists.length + 1}`;
+ lists.push({ guid, name: args.name ?? "Untitled List", members: args.add ?? [], etag: "e" });
+ return guid;
+ }
+ const l = lists.find((x) => x.guid === args.guid);
+ if (args.delete) { window.__lists = lists.filter((x) => x.guid !== args.guid); return args.guid; }
+ if (args.name) l.name = args.name;
+ l.members = l.members.filter((m) => !(args.remove ?? []).includes(m));
+ for (const m of args.add ?? []) if (!l.members.includes(m)) l.members.push(m);
+ return l.guid;
+ }
case "drive_thumbnails": return driveFixture ? { "FILE::d": "data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='80' height='60'><rect width='80' height='60' fill='%23eee'/></svg>" } : {};
case "drive_duplicate": (window.__dups ??= []).push(args.drivewsid); return null;
case "storage_info": return { usedBytes: 182196857, totalBytes: 5368709120 };
diff --git a/check.sh b/check.sh
index f6dbe7c..37207b3 100755
--- a/check.sh
+++ b/check.sh
@@ -61,6 +61,7 @@ step "list info" node .uiverify/reminders-list-info.mjs
step "reminder date" node .uiverify/reminders-date.mjs
step "reminder keys" node .uiverify/reminders-keys.mjs
step "contacts order" node .uiverify/contacts-order.mjs
+step "contacts lists" node .uiverify/contacts-lists.mjs
step "calendar alerts" node .uiverify/calendar-alerts.mjs
step "calendar repeat" node .uiverify/calendar-repeat.mjs
step "reminder add/done" node .uiverify/reminders-add-done.mjs
diff --git a/crates/quince-icloud/src/contacts.rs b/crates/quince-icloud/src/contacts.rs
index 8b65cbd..b514bf8 100644
--- a/crates/quince-icloud/src/contacts.rs
+++ b/crates/quince-icloud/src/contacts.rs
@@ -184,6 +184,31 @@ pub struct Tokens {
///
/// The tokens come from the same response as the contacts, so asking for both at once is
/// one request rather than two, and the tokens are guaranteed to match the data.
+/// The whole address book — people and lists — with the tokens a write needs, in one read.
+pub async fn fetch_book_with_tokens(
+ http: &reqwest::Client,
+ root: &str,
+ params: Vec<(String, String)>,
+) -> Result<(AddressBook, Tokens)> {
+ let body = startup(http, root, params).await?;
+ let token = |key: &str| {
+ body.get(key)
+ .and_then(Value::as_str)
+ .map(ToString::to_string)
+ .ok_or_else(|| Error::Protocol(format!("/co/startup carried no {key}")))
+ };
+ Ok((
+ AddressBook {
+ contacts: parse(&body),
+ lists: parse_lists(&body),
+ },
+ Tokens {
+ sync: token("syncToken")?,
+ pref: token("prefToken")?,
+ },
+ ))
+}
+
pub async fn fetch_with_tokens(
http: &reqwest::Client,
root: &str,
@@ -544,7 +569,32 @@ async fn write_list(
text.chars().take(200).collect::<String>()
)));
}
- Ok(serde_json::from_str(&text).unwrap_or(Value::Null))
+ let body: Value = serde_json::from_str(&text).unwrap_or(Value::Null);
+ refused_group(&body)?;
+ Ok(body)
+}
+
+/// Apple answers a refused group write with 200 and the reason in `errors` — a 409 when
+/// the etag sent is no longer the list's. Read as success, a lost write would look saved.
+fn refused_group(body: &Value) -> Result<()> {
+ let Some(error) = body
+ .get("errors")
+ .and_then(Value::as_array)
+ .and_then(|e| e.first())
+ else {
+ return Ok(());
+ };
+ match error.get("errorCode").and_then(Value::as_i64) {
+ Some(409) | Some(412) => Err(Error::Conflict),
+ code => Err(Error::Protocol(format!(
+ "Contacts refused the list ({}): {}",
+ code.map_or_else(|| "no code".into(), |c| c.to_string()),
+ error
+ .get("errorMessage")
+ .and_then(Value::as_str)
+ .unwrap_or("no reason given")
+ ))),
+ }
}
/// Make a list, with these people in it. Answers with its id.
@@ -685,6 +735,21 @@ pub fn apply(library: &mut quince_core::Library, book: AddressBook) -> Result<us
#[cfg(test)]
mod list_tests {
+ #[test]
+ fn a_refused_group_write_is_an_error_not_a_save() {
+ let busy = serde_json::json!({ "errors": [{ "groupId": "G", "etag": "e", "errorCode": 409, "errorMessage": "Conflict" }] });
+ assert!(matches!(
+ super::refused_group(&busy),
+ Err(crate::Error::Conflict)
+ ));
+ let other = serde_json::json!({ "errors": [{ "groupId": "G", "errorCode": 400, "errorMessage": "Bad" }] });
+ assert!(matches!(
+ super::refused_group(&other),
+ Err(crate::Error::Protocol(_))
+ ));
+ assert!(super::refused_group(&serde_json::json!({ "groups": [], "errors": [] })).is_ok());
+ }
+
use super::*;
/// Lists come out in the account's own order — `groupsOrder` — with their members.
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index e5544a3..823855c 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -1393,6 +1393,110 @@ async fn resync_contacts(
.map_err(|e| e.to_string())
}
+/// The Contacts lists, as the last pass stored them.
+#[tauri::command]
+async fn contact_lists(
+ data: State<'_, Data>,
+) -> UiResult<Vec<quince_icloud::contacts::ContactList>> {
+ let library = data.0.lock().await;
+ Ok(quince_icloud::contacts::stored_lists(&library))
+}
+
+/// One Contacts list write at a time. Each reads the list as Apple holds it and sends it
+/// back whole; two at once would both read the same etag and one would be refused.
+static CONTACT_LISTS: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
+
+/// Change a Contacts list: make one (no `guid`), rename it, add people to it or take them
+/// out, or delete it. Answers with the list's id.
+///
+/// Apple only takes a list whole, so membership is sent as what to add and remove and laid
+/// over the list as Apple holds it at the moment of writing — someone added on the phone a
+/// second ago stays in. A write that loses to one made elsewhere is read again and retried.
+#[tauri::command]
+#[allow(clippy::too_many_arguments)]
+async fn contact_list_write(
+ guid: Option<String>,
+ name: Option<String>,
+ add: Option<Vec<String>>,
+ remove: Option<Vec<String>>,
+ delete: Option<bool>,
+ auth: State<'_, Auth>,
+ data: State<'_, Data>,
+) -> UiResult<String> {
+ let _one = CONTACT_LISTS.lock().await;
+ let (http, root, params) = contacts_context(&auth).await?;
+ let add = add.unwrap_or_default();
+ let remove = remove.unwrap_or_default();
+ let mut attempt = 0;
+ let done = loop {
+ attempt += 1;
+ let (book, tokens) =
+ quince_icloud::contacts::fetch_book_with_tokens(&http, &root, params.clone())
+ .await
+ .map_err(|e| e.to_string())?;
+ let written = match guid.as_deref().filter(|g| !g.is_empty()) {
+ None => {
+ quince_icloud::contacts::create_list(
+ &http,
+ &root,
+ params.clone(),
+ &tokens,
+ name.as_deref().unwrap_or("Untitled List"),
+ &add,
+ )
+ .await
+ }
+ Some(guid) => {
+ let Some(mut list) = book
+ .lists
+ .into_iter()
+ .find(|l| l.guid.eq_ignore_ascii_case(guid))
+ else {
+ // Already gone — deleted here a moment ago, or on another device.
+ break guid.to_string();
+ };
+ if delete.unwrap_or(false) {
+ quince_icloud::contacts::delete_list(
+ &http,
+ &root,
+ params.clone(),
+ &tokens,
+ &list.guid,
+ )
+ .await
+ } else {
+ if let Some(name) = name.as_deref().map(str::trim).filter(|n| !n.is_empty()) {
+ list.name = name.to_string();
+ }
+ list.members
+ .retain(|m| !remove.iter().any(|r| r.eq_ignore_ascii_case(m)));
+ for person in &add {
+ if !list.members.iter().any(|m| m.eq_ignore_ascii_case(person)) {
+ list.members.push(person.clone());
+ }
+ }
+ quince_icloud::contacts::update_list(
+ &http,
+ &root,
+ params.clone(),
+ &tokens,
+ &list,
+ )
+ .await
+ }
+ .map(|()| list.guid)
+ }
+ };
+ match written {
+ Ok(guid) => break guid,
+ Err(quince_icloud::Error::Conflict) if attempt < 3 => continue,
+ Err(e) => return Err(e.to_string()),
+ }
+ };
+ resync_contacts(&http, &root, params, &data).await?;
+ Ok(done)
+}
+
/// Create a contact, or save changes to one. Returns the id Apple knows it by.
///
/// An edit starts from Apple's own card, so everything this app does not model — a photo,
@@ -2535,6 +2639,8 @@ fn main() {
note_counts,
contacts_list,
contact_save,
+ contact_lists,
+ contact_list_write,
contact_delete,
drive_sync_folder,
drive_children,
diff --git a/src/components/RowMenu.tsx b/src/components/RowMenu.tsx
index 1647fde..b1f31f1 100644
--- a/src/components/RowMenu.tsx
+++ b/src/components/RowMenu.tsx
@@ -1,7 +1,8 @@
import { Portal } from "./Portal";
import { useEffect, useLayoutEffect, useRef, useState } from "react";
-export type MenuEntry = { label: string; run: () => void; danger?: boolean } | null;
+/** `keep` leaves the menu open — for an entry that leads on to a second step of choices. */
+export type MenuEntry = { label: string; run: () => void; danger?: boolean; keep?: boolean } | null;
/**
* A menu as macOS draws one: under the ⋯ that opened it or at the pointer for a right-click,
@@ -25,6 +26,7 @@ export function RowMenu({ at, entries, onClose }: {
left = Math.max(8, Math.min(left, window.innerWidth - width - 8));
if (top + height > window.innerHeight - 8) top = Math.max(8, at.y - height - (at.alignRight ? 36 : 0));
setPos({ left, top });
+ setActive(0);
el.focus();
}, [at]);
useEffect(() => {
@@ -39,7 +41,11 @@ export function RowMenu({ at, entries, onClose }: {
window.removeEventListener("resize", away);
};
}, [onClose]);
- const pick = (i: number) => { onClose(); items[i]?.run(); };
+ const pick = (i: number) => {
+ const item = items[i];
+ if (!item?.keep) onClose();
+ item?.run();
+ };
let n = -1;
return (
<Portal>
diff --git a/src/lib/ipc.ts b/src/lib/ipc.ts
index 15cb260..6683400 100644
--- a/src/lib/ipc.ts
+++ b/src/lib/ipc.ts
@@ -159,6 +159,14 @@ export const api = {
contactSave: (contact: Contact) => invoke<string>("contact_save", { contact }),
contactDelete: (guid: string) => invoke<void>("contact_delete", { guid }),
contactsList: (search: string | null) => invoke<Contact[]>("contacts_list", { search }),
+ /** Contacts' lists — Apple's groups — in the order Apple keeps them. */
+ contactLists: () => invoke<ContactList[]>("contact_lists"),
+ /**
+ * Make a list (no guid), rename one, add people to it or take them out, or delete it.
+ * Membership goes as changes, laid over the list as Apple holds it. Returns its id.
+ */
+ contactListWrite: (change: { guid?: string; name?: string; add?: string[]; remove?: string[]; delete?: boolean }) =>
+ invoke<string>("contact_list_write", change),
driveSyncFolder: (folderId: string) => invoke<number>("drive_sync_folder", { folderId }),
driveChildren: (folderId: string) => invoke<DriveItem[]>("drive_children", { folderId }),
@@ -409,6 +417,14 @@ export type Note = {
export type ContactMethod = { kind: string; label: string | null; value: string };
+export type ContactList = {
+ guid: string;
+ name: string;
+ /** The contacts in it, by guid. */
+ members: string[];
+ etag: string | null;
+};
+
export type Contact = {
guid: string;
firstName: string | null;
diff --git a/src/screens/ContactsView.tsx b/src/screens/ContactsView.tsx
index 708e6fc..903bebf 100644
--- a/src/screens/ContactsView.tsx
+++ b/src/screens/ContactsView.tsx
@@ -1,16 +1,23 @@
-import { Fragment, useCallback, useEffect, useMemo, useState } from "react";
+import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Notice } from "../components/Notice";
-import { ChevronLeft } from "lucide-react";
+import { ChevronLeft, Plus, UsersRound, UserRound } from "lucide-react";
import {
api,
displayName,
messageOf,
photoSrc,
type Contact,
+ type ContactList,
type ContactMethod,
} from "../lib/ipc";
import { useSync } from "../lib/sync";
import { Picker } from "../components/Picker";
+import { RowMenu, type MenuEntry } from "../components/RowMenu";
+
+/** The sidebar row that is every contact rather than a list. */
+const ALL = "";
+
+type MenuAt = { x: number; y: number; alignRight: boolean };
/** The kinds of detail a card can hold, in the order Apple lists them. */
const KINDS = [
@@ -92,6 +99,18 @@ export function ContactsView() {
/** The card being written, or null while simply looking. */
const [draft, setDraft] = useState<Contact | null>(null);
const [busy, setBusy] = useState(false);
+ const [lists, setLists] = useState<ContactList[]>([]);
+ /** The list being looked at, or ALL. */
+ const [list, setList] = useState<string>(ALL);
+ /** A list whose name is being typed: "new" for one not made yet. */
+ const [naming, setNaming] = useState<string | null>(null);
+ const [listMenu, setListMenu] = useState<(MenuAt & { list: ContactList }) | null>(null);
+ /** A contact's menu: its actions, or — one step in — the lists it can go into. */
+ const [contactMenu, setContactMenu] = useState<(MenuAt & { contact: Contact; lists: boolean }) | null>(null);
+ const [dragging, setDragging] = useState<string | null>(null);
+ const [dropOn, setDropOn] = useState<string | null>(null);
+ /** List writes go to Apple one after another, in the order they were made. */
+ const queue = useRef<Promise<unknown>>(Promise.resolve());
const read = useCallback(async (query: string) => {
const found = await api.contactsList(query.trim() || null);
@@ -116,12 +135,119 @@ export function ContactsView() {
// Re-reading on every keystroke is the point: the filter runs in SQLite.
}, [read, search, revision]);
+ const readLists = useCallback(async () => {
+ const found = await api.contactLists();
+ setLists(Array.isArray(found) ? found : []);
+ }, []);
+ useEffect(() => {
+ readLists().catch((e) => setError(messageOf(e)));
+ }, [readLists, revision]);
+ // A list deleted elsewhere is not left open, empty, with nothing to say why.
+ useEffect(() => {
+ if (list !== ALL && !lists.some((l) => l.guid === list)) setList(ALL);
+ }, [lists, list]);
+
+ /** Who shows: everyone, or the people in the open list. */
+ const shown = useMemo(() => {
+ if (list === ALL) return contacts;
+ const members = new Set((lists.find((l) => l.guid === list)?.members ?? []).map((m) => m.toUpperCase()));
+ return contacts.filter((c) => members.has(c.guid.toUpperCase()));
+ }, [contacts, lists, list]);
+
useEffect(() => {
- if (contacts.length === 0) return setOpenGuid(null);
+ if (shown.length === 0) return setOpenGuid(null);
setOpenGuid((current) =>
- current && contacts.some((c) => c.guid === current) ? current : contacts[0].guid
+ current && shown.some((c) => c.guid === current) ? current : sortedContacts(shown)[0].guid
+ );
+ }, [shown]);
+
+ /**
+ * A change to a list: drawn at once, then sent. When Apple says no, the lists are read
+ * back as Apple holds them, so nothing stays on screen that did not happen.
+ */
+ const changeList = useCallback(
+ (predict: (lists: ContactList[]) => ContactList[], change: Parameters<typeof api.contactListWrite>[0]) => {
+ setLists(predict);
+ setError(null);
+ const sent = queue.current.then(async () => {
+ try {
+ const guid = await api.contactListWrite(change);
+ await readLists();
+ return guid;
+ } catch (e) {
+ setError(messageOf(e));
+ await readLists().catch(() => {});
+ return null;
+ }
+ });
+ queue.current = sent;
+ return sent;
+ },
+ [readLists]
+ );
+
+ const createList = useCallback(
+ async (name: string, members: string[] = []) => {
+ const title = name.trim() || "Untitled List";
+ const standIn = `pending-list-${Date.now()}`;
+ const guid = await changeList(
+ (ls) => [...ls, { guid: standIn, name: title, members, etag: null }],
+ { name: title, add: members }
+ );
+ if (guid) setList((current) => (current === standIn ? guid : current));
+ else setList((current) => (current === standIn ? ALL : current));
+ },
+ [changeList]
+ );
+ const renameList = (l: ContactList, name: string) => {
+ setNaming(null);
+ const title = name.trim();
+ if (!title || title === l.name) return;
+ void changeList((ls) => ls.map((x) => (x.guid === l.guid ? { ...x, name: title } : x)), { guid: l.guid, name: title });
+ };
+ const deleteList = (l: ContactList) => {
+ // icloud.com's own words for it.
+ if (!window.confirm(`Delete \u201c${l.name}\u201d?\n\nThis list will be deleted from every device. The contacts in it stay in Contacts.`)) return;
+ if (list === l.guid) setList(ALL);
+ void changeList((ls) => ls.filter((x) => x.guid !== l.guid), { guid: l.guid, delete: true });
+ };
+ const addToList = (l: ContactList, people: string[]) => {
+ const fresh = people.filter((p) => !l.members.some((m) => m.toUpperCase() === p.toUpperCase()));
+ if (fresh.length === 0) return;
+ void changeList(
+ (ls) => ls.map((x) => (x.guid === l.guid ? { ...x, members: [...x.members, ...fresh] } : x)),
+ { guid: l.guid, add: fresh }
+ );
+ };
+ const removeFromList = (l: ContactList, people: string[]) => {
+ const gone = new Set(people.map((p) => p.toUpperCase()));
+ void changeList(
+ (ls) => ls.map((x) => (x.guid === l.guid ? { ...x, members: x.members.filter((m) => !gone.has(m.toUpperCase())) } : x)),
+ { guid: l.guid, remove: people }
);
- }, [contacts]);
+ };
+ const openList = lists.find((l) => l.guid === list) ?? null;
+
+ /** What a contact's menu offers — the same whether opened by right-click or the card. */
+ const contactEntries = (c: Contact, choosingList: boolean): MenuEntry[] => {
+ if (choosingList) {
+ const into = lists.filter((l) => !l.guid.startsWith("pending-") && !l.members.some((m) => m.toUpperCase() === c.guid.toUpperCase()));
+ return [
+ ...into.map((l) => ({ label: l.name, run: () => addToList(l, [c.guid]) })),
+ ...(into.length ? [null] : []),
+ { label: "New List\u2026", run: () => void createList("Untitled List", [c.guid]) },
+ ];
+ }
+ return [
+ { label: "Add to List\u2026", keep: true, run: () => setContactMenu((m) => (m ? { ...m, lists: true } : m)) },
+ ...(openList ? [{ label: `Remove from \u201c${openList.name}\u201d`, run: () => removeFromList(openList, [c.guid]) }] : []),
+ null,
+ { label: "Edit Contact", run: () => { setOpenGuid(c.guid); setDraft({ ...c }); } },
+ { label: "Delete Contact\u2026", danger: true, run: () => {
+ if (window.confirm(`Delete ${displayName(c)}?`)) void removeContact(c.guid);
+ } },
+ ];
+ };
/** Every write goes to Apple first, then the library is re-read. */
const write = useCallback(
@@ -130,7 +256,8 @@ export function ContactsView() {
setError(null);
try {
await run();
- await read(search);
+ // A deleted contact leaves every list it was in, so the lists are read again too.
+ await Promise.all([read(search), readLists()]);
return true;
} catch (e) {
setError(messageOf(e));
@@ -139,7 +266,7 @@ export function ContactsView() {
setBusy(false);
}
},
- [read, search]
+ [read, readLists, search]
);
const saveDraft = useCallback(async () => {
@@ -181,11 +308,70 @@ export function ContactsView() {
return (
// A contact being written is always what shows; it has its own Cancel.
<div className={`contacts${detail || draft ? " is-detail" : ""}`}>
+ <aside className="contacts-lists" aria-label="Contact lists">
+ <p className="notes-side-heading">iCloud</p>
+ <ListRow
+ name="All Contacts"
+ count={contacts.length}
+ current={list === ALL}
+ everyone
+ onOpen={() => setList(ALL)}
+ />
+ {lists.map((l) =>
+ naming === l.guid ? (
+ <NameField key={l.guid} initial={l.name} label={`Rename ${l.name}`} onDone={(name) => renameList(l, name)} onCancel={() => setNaming(null)} />
+ ) : (
+ <ListRow
+ key={l.guid}
+ name={l.name}
+ count={l.members.filter((m) => contacts.some((c) => c.guid.toUpperCase() === m.toUpperCase())).length}
+ current={list === l.guid}
+ menuOpen={listMenu?.list.guid === l.guid}
+ dropping={dropOn === l.guid}
+ onOpen={() => setList(l.guid)}
+ onMenu={l.guid.startsWith("pending-") ? undefined : (at) => setListMenu({ ...at, list: l })}
+ onDragOver={(e) => {
+ if (!dragging || l.guid.startsWith("pending-")) return;
+ e.preventDefault();
+ e.dataTransfer.dropEffect = "copy";
+ if (dropOn !== l.guid) setDropOn(l.guid);
+ }}
+ onDragLeave={() => setDropOn((d) => (d === l.guid ? null : d))}
+ onDrop={(e) => {
+ e.preventDefault();
+ const person = dragging;
+ setDragging(null);
+ setDropOn(null);
+ if (person) addToList(l, [person]);
+ }}
+ />
+ )
+ )}
+ {naming === "new" && (
+ <NameField initial="Untitled List" label="New list name" onDone={(name) => { setNaming(null); void createList(name); }} onCancel={() => setNaming(null)} />
+ )}
+ <button className="notes-new-folder" onClick={() => setNaming("new")}>
+ <Plus size={15} strokeWidth={2} aria-hidden="true" />
+ New List
+ </button>
+ {listMenu && (
+ <RowMenu
+ at={listMenu}
+ onClose={() => setListMenu(null)}
+ entries={[
+ { label: "Rename List", run: () => setNaming(listMenu.list.guid) },
+ null,
+ { label: "Delete List\u2026", danger: true, run: () => deleteList(listMenu.list) },
+ ]}
+ />
+ )}
+ </aside>
+
<section className="contacts-list" aria-label="Contacts">
<header className="cal-bar">
<div className="cal-nav">
- <h1>Contacts</h1>
- <span className="badge">{contacts.length}</span>
+ <h1>{openList?.name ?? "Contacts"}</h1>
+ <span className="badge">{shown.length}</span>
</div>
<div className="cal-actions">
<button className="quiet" disabled={busy} onClick={() => setDraft(blank())}>
@@ -203,15 +389,39 @@ export function ContactsView() {
type="search"
/>
+ {/* Shown only when the lists column has folded away. */}
+ <div className="contacts-list-picker">
+ <Picker
+ label="List"
+ value={list}
+ onChange={setList}
+ options={[{ value: ALL, label: "All Contacts" }, ...lists.map((l) => ({ value: l.guid, label: l.name }))]}
+ />
+ </div>
+
{error && <Notice message={error} onDismiss={() => setError(null)} />}
<ul className="contact-rows">
- {sortedContacts(contacts).map((contact, i, all) => (
+ {sortedContacts(shown).map((contact, i, all) => (
<Fragment key={contact.guid}>
{(i === 0 || letterOf(all[i - 1]) !== letterOf(contact)) && (
<li className="contact-letter" aria-hidden="true">{letterOf(contact)}</li>
)}
- <li>
+ <li
+ // Dragged onto a list, a person joins it — as in Contacts on the Mac.
+ draggable={lists.length > 0}
+ onDragStart={(e) => {
+ e.dataTransfer.effectAllowed = "copy";
+ e.dataTransfer.setData("text/plain", displayName(contact));
+ setDragging(contact.guid);
+ }}
+ onDragEnd={() => { setDragging(null); setDropOn(null); }}
+ onContextMenu={(e) => {
+ e.preventDefault();
+ setOpenGuid(contact.guid);
+ setContactMenu({ x: e.clientX, y: e.clientY, alignRight: false, contact, lists: false });
+ }}
+ >
<button
className="contact-row"
aria-current={openGuid === contact.guid}
@@ -228,8 +438,15 @@ export function ContactsView() {
))}
</ul>
- {loaded && contacts.length === 0 && !error && (
- <p className="cal-empty">{search ? "No matches." : "No contacts yet."}</p>
+ {loaded && shown.length === 0 && !error && (
+ <p className="cal-empty">{search ? "No matches." : openList ? "No one in this list yet." : "No contacts yet."}</p>
+ )}
+ {contactMenu && (
+ <RowMenu
+ at={contactMenu}
+ onClose={() => setContactMenu(null)}
+ entries={contactEntries(contactMenu.contact, contactMenu.lists)}
+ />
)}
</section>
@@ -447,6 +664,21 @@ export function ContactsView() {
<button className="quiet" disabled={busy} onClick={() => setDraft({ ...open })}>
Edit
</button>
+ <button
+ className="quiet"
+ aria-haspopup="menu"
+ onClick={(e) => {
+ const r = e.currentTarget.getBoundingClientRect();
+ setContactMenu({ x: r.left, y: r.bottom + 4, alignRight: false, contact: open, lists: true });
+ }}
+ >
+ Add to List
+ </button>
+ {openList && (
+ <button className="quiet" onClick={() => removeFromList(openList, [open.guid])}>
+ Remove from List
+ </button>
+ )}
<button
className="quiet danger"
disabled={busy}
@@ -469,6 +701,97 @@ export function ContactsView() {
);
}
+/** A row in the lists column: All Contacts, or one list, with its count and ⋯. */
+function ListRow({
+ name,
+ count,
+ current,
+ everyone = false,
+ menuOpen = false,
+ dropping = false,
+ onOpen,
+ onMenu,
+ onDragOver,
+ onDragLeave,
+ onDrop,
+}: {
+ name: string;
+ count: number;
+ current: boolean;
+ everyone?: boolean;
+ menuOpen?: boolean;
+ dropping?: boolean;
+ onOpen: () => void;
+ onMenu?: (at: MenuAt) => void;
+ onDragOver?: React.DragEventHandler;
+ onDragLeave?: React.DragEventHandler;
+ onDrop?: React.DragEventHandler;
+}) {
+ const Glyph = everyone ? UsersRound : UserRound;
+ return (
+ <div
+ className={`notes-folder-row${menuOpen ? " is-menu" : ""}${dropping ? " is-drop" : ""}`}
+ onContextMenu={(e) => {
+ e.preventDefault();
+ onMenu?.({ x: e.clientX, y: e.clientY, alignRight: false });
+ }}
+ onDragOver={onDragOver}
+ onDragLeave={onDragLeave}
+ onDrop={onDrop}
+ >
+ <button className="notes-folder" aria-current={current} onClick={onOpen}>
+ <Glyph className="contacts-list-glyph" size={16} strokeWidth={2} aria-hidden="true" />
+ <span className="notes-folder-name">{name}</span>
+ <span className="notes-folder-count">{count || ""}</span>
+ </button>
+ {onMenu && (
+ <button
+ className="notes-folder-more"
+ aria-label={`Actions for ${name}`}
+ aria-haspopup="menu"
+ onClick={(e) => {
+ const r = e.currentTarget.getBoundingClientRect();
+ onMenu({ x: r.right, y: r.bottom + 4, alignRight: true });
+ }}
+ >
+ <span aria-hidden="true">•••</span>
+ </button>
+ )}
+ </div>
+ );
+}
+
+/** A list's name being typed, in place: Return keeps it, Escape leaves it as it was. */
+function NameField({ initial, label, onDone, onCancel }: {
+ initial: string;
+ label: string;
+ onDone: (name: string) => void;
+ onCancel: () => void;
+}) {
+ const settled = useRef(false);
+ return (
+ <input
+ className="notes-folder notes-folder-rename"
+ defaultValue={initial}
+ aria-label={label}
+ autoFocus
+ onFocus={(e) => e.currentTarget.select()}
+ onBlur={(e) => {
+ if (settled.current) return;
+ settled.current = true;
+ onDone(e.currentTarget.value);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") e.currentTarget.blur();
+ if (e.key === "Escape") {
+ settled.current = true;
+ onCancel();
+ }
+ }}
+ />
+ );
+}
+
/** The year Apple writes for a birthday given without one. */
const NO_YEAR = "1604";
diff --git a/src/styles/app.css b/src/styles/app.css
index 70d54ae..26ec183 100644
--- a/src/styles/app.css
+++ b/src/styles/app.css
@@ -781,10 +781,34 @@
.contacts {
display: grid;
- grid-template-columns: minmax(230px, 300px) minmax(0, 1fr);
+ grid-template-columns: 190px minmax(230px, 300px) minmax(0, 1fr);
height: 100%;
min-height: 0;
}
+/* The lists, as Contacts' sidebar has them — the same rows as Notes' folders. */
+.contacts-lists {
+ display: flex;
+ flex-direction: column;
+ gap: 1px;
+ min-height: 0;
+ overflow-y: auto;
+ padding: 2px 12px 12px 0;
+ margin-right: 14px;
+ border-right: 1px solid var(--separator);
+}
+.contacts-list-glyph { flex: none; color: var(--text-2); }
+.contacts-lists .notes-folder-row.is-drop .notes-folder {
+ background: var(--gold-tint);
+ box-shadow: inset 0 0 0 2px var(--gold);
+}
+.contacts-list-picker { display: none; margin-bottom: 8px; }
+.contacts-list-picker .picker { width: 100%; }
+/* The lists fold into a picker above the people first. */
+@media (max-width: 1000px) {
+ .contacts { grid-template-columns: minmax(230px, 300px) minmax(0, 1fr); }
+ .contacts-lists { display: none; }
+ .contacts-list-picker { display: block; }
+}
/* One column at a time in a narrow window: the list, or the person picked from it. */
@media (max-width: 720px) {
.contacts { grid-template-columns: minmax(0, 1fr); }