Native iCloud apps for Windows and Linux, built in Rust. Notes, Reminders, Calendar, Contacts, Drive and Photos, offline and in sync with your iPhone.
Rust apple-notesapple-reminderscloudkitcrdtdesktop-appicloudicloud-calendaricloud-driveicloud-notesicloud-photosiphonelinuxlinux-desktoplocal-firstoffline-firstprivacyrusttauritauri-appwindows
Photos load, sidebar folds cleanly, rows and menus stop flickering
Yashwanth Kamireddi5366d99e7cd8
diff --git a/.uiverify/menus.mjs b/.uiverify/menus.mjsindex 54b2896..002b45f 100644--- a/.uiverify/menus.mjs+++ b/.uiverify/menus.mjs@@ -1,7 +1,6 @@// Every kind of menu, where menus went wrong: near the window's edges, inside a popover, in a// small window. Each must open whole and on screen, in one draw (no flicker), take the keys,-// and go on Escape or a click elsewhere; a pop-up's menu lies over its button with the-// current choice on it; a submenu opens beside its line and flips left when the right is full.+// and go on Escape or a click elsewhere; a pop-up's menu drops from its button; a submenu opens beside its line and flips left when the right is full.import { engine } from "./engine.mjs";import { SERVICES, installStub, openScreen } from "./stub.mjs";const b = await engine.launch();@@ -86,9 +85,11 @@ for (const size of [{ width: 1280, height: 800 }, { width: 760, height: 520 }])await page.waitForTimeout(100);where = await onScreen(page, ".picker-menu");ok(where.ok, `${label} a pop-up's menu inside a popover is whole and on screen ${where.why ?? ""}`);- const chosen = await page.locator(".picker-menu [aria-selected=true]").boundingBox();- ok(chosen && Math.abs(chosen.y + chosen.height / 2 - (pb.y + pb.height / 2)) < 14 || where.ok && (await page.evaluate(() => document.querySelector(".picker-menu").getBoundingClientRect().bottom >= innerHeight - 9)),- `${label} its current choice lies over the button (or the menu is held at the window's edge)`);+ // Dropped from the button, never laid over it: laid over, a menu in a form covered the+ // rows around it. Below, or above where there is no room below.+ const mb = await page.locator(".picker-menu").boundingBox();+ ok(mb && (mb.y >= pb.y + pb.height - 1 || mb.y + mb.height <= pb.y + 1),+ `${label} its menu drops from the button and leaves it in sight [button ${Math.round(pb.y)}–${Math.round(pb.y + pb.height)}, menu ${Math.round(mb?.y)}–${Math.round(mb?.y + mb?.height)}]`);ok((await page.evaluate(() => window.__menus)) === 1, `${label} drawn once, no flicker`);await page.keyboard.press("Escape");ok((await page.locator(".picker-menu").count()) === 0, `${label} Escape closes a pop-up's menu`);diff --git a/.uiverify/pending-writes.mjs b/.uiverify/pending-writes.mjsnew file mode 100644index 0000000..8b571bc--- /dev/null+++ b/.uiverify/pending-writes.mjs@@ -0,0 +1,46 @@+// A change on its way to Apple stays drawn when a refresh lands mid-way — Apple pushes the+// change straight back, and the refresh read the library from before it: a note moved to+// another folder came back in the old one for a moment, then went again.+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(() => {+ window.__noteFolders = [+ { guid: "f1", title: "Notes", sortOrder: 0 },+ { guid: "f2", title: "Recently Deleted", sortOrder: 1 },+ { guid: "f3", title: "Work", sortOrder: 2 },+ ];+});+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, notesFixture: true });+const page = await ctx.newPage();+await page.goto("http://localhost:4173", { waitUntil: "networkidle" });+await openScreen(page, "Notes");+await page.waitForTimeout(400);+let failures = 0;+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };++await page.locator(".notes-folder", { hasText: /^Notes/ }).first().click();+await page.waitForTimeout(300);+await page.locator(".note-row", { hasText: "Curtains" }).first().click();+await page.waitForTimeout(300);+await page.evaluate(() => { window.__slowMove = 900; });+await page.getByRole("button", { name: "Folder for Curtains" }).click();+await page.evaluate(() => {+ window.__back = 0; window.__gone = false; window.__watching = true;+ const tick = () => {+ const there = [...document.querySelectorAll(".note-row")].some((r) => r.textContent.includes("Curtains"));+ if (!there) window.__gone = true;+ else if (window.__gone) window.__back++;+ if (window.__watching) requestAnimationFrame(tick);+ };+ requestAnimationFrame(tick);+ // A refresh finishing while the move is out, as Apple's push makes happen.+ setTimeout(() => window.__emit?.("quince://synced", { services: [], asOf: Math.floor(Date.now() / 1000), tookMs: 1 }), 350);+});+await page.getByRole("option", { name: "Work" }).click();+await page.waitForTimeout(800);+const r = await page.evaluate(() => { window.__watching = false; return { gone: window.__gone, back: window.__back }; });+ok(r.gone && r.back === 0, `a moved note leaves at once and does not come back while the move is out [${JSON.stringify(r)}]`);+await b.close();+process.exitCode = failures ? 1 : 0;diff --git a/.uiverify/reminders-list-info.mjs b/.uiverify/reminders-list-info.mjsindex b80922a..e05bcb4 100644--- a/.uiverify/reminders-list-info.mjs+++ b/.uiverify/reminders-list-info.mjs@@ -11,8 +11,20 @@ await openScreen(page, "Reminders");await page.waitForTimeout(300);let failures = 0;const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };+// The name never runs under the ⋯ that appears over it.await page.locator(".rx-list", { hasText: "Daily" }).hover();-await page.getByRole("button", { name: "Show List Info for Daily" }).click();+const clash = await page.evaluate(() => {+ const row = [...document.querySelectorAll(".rx-list-row")].find((r) => r.textContent.includes("Daily"));+ const name = row.querySelector(".rx-list-name").getBoundingClientRect();+ const more = row.querySelector(".rx-list-more").getBoundingClientRect();+ return name.right - parseFloat(getComputedStyle(row.querySelector(".rx-list-name")).paddingRight) > more.left;+});+ok(!clash, "a pointed-at list's name stops short of its ⋯");+await page.locator(".rx-list", { hasText: "Daily" }).hover();+// One ⋯ on the row, not three buttons over its name.+ok((await page.locator(".rx-list-row", { hasText: "Daily" }).getByRole("button").count()) === 2, "a list row has its name and one ⋯, nothing more");+await page.getByRole("button", { name: "Actions for Daily" }).click();+await page.getByRole("menuitem", { name: "Show List Info" }).click();await page.waitForTimeout(200);ok((await page.getByRole("radio").count()) === 12, "Apple's twelve colours are offered");await page.getByRole("radio", { name: "purple" }).click();diff --git a/.uiverify/row-hover.mjs b/.uiverify/row-hover.mjsnew file mode 100644index 0000000..2f491b6--- /dev/null+++ b/.uiverify/row-hover.mjs@@ -0,0 +1,33 @@+// A sidebar row's ⋯: moving from the row onto it keeps the row lit the whole way, and the+// name beside it does not move — in Reminders' lists, Notes' folders and Contacts' lists.+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, remindersFixture: true, notesFixture: true, contactsFixture: true });+const page = await ctx.newPage();+await page.goto("http://localhost:4173", { waitUntil: "networkidle" });+let failures = 0;+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };+for (const [screen, rowSel, hitSel, nameSel, moreSel] of [+ ["Reminders", ".rx-list-row", ".rx-list", ".rx-list-name", ".rx-list-more"],+ ["Notes", ".notes-folder-row", ".notes-folder", ".notes-folder-name", ".notes-folder-more"],+ ["Contacts", ".contacts-lists .notes-folder-row", ".notes-folder", ".notes-folder-name", ".notes-folder-more"],+]) {+ await openScreen(page, screen);+ await page.waitForTimeout(400);+ const row = page.locator(rowSel).filter({ has: page.locator(moreSel) }).first();+ if (!(await row.count())) { ok(false, `${screen}: a row with a ⋯`); continue; }+ const lit = () => row.locator(hitSel).evaluate((el) => getComputedStyle(el).backgroundColor);+ const nameBox = () => row.locator(nameSel).evaluate((el) => { const r = el.getBoundingClientRect(); return `${Math.round(r.width)}`; });+ await row.locator(hitSel).hover({ position: { x: 30, y: 10 } });+ await page.waitForTimeout(200);+ const onRow = await lit();+ const nameOnRow = await nameBox();+ await row.locator(moreSel).hover();+ await page.waitForTimeout(200);+ ok((await lit()) === onRow && onRow !== "rgba(0, 0, 0, 0)", `${screen}: the row stays lit with the pointer on its ⋯ [${onRow} → ${await lit()}]`);+ ok((await nameBox()) === nameOnRow, `${screen}: the name does not move when the ⋯ is pointed at`);+}+await b.close();+process.exitCode = failures ? 1 : 0;diff --git a/.uiverify/settings.mjs b/.uiverify/settings.mjsindex f12a44a..98ab26f 100644--- a/.uiverify/settings.mjs+++ b/.uiverify/settings.mjs@@ -14,7 +14,7 @@ let failures = 0;const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };const card = page.locator(".sidebar-account");-ok((await card.innerText()).includes("Asha Rao"), "the sidebar names who is signed in");+ok((await card.innerText()).includes("Asha") && !(await card.innerText()).includes("…"), "the sidebar names who is signed in, whole");await card.click();await page.waitForSelector(".settings");ok(await page.getByRole("heading", { name: "Settings" }).isVisible(), "the account opens Settings");@@ -64,5 +64,23 @@ await page.evaluate(() => {await page.getByRole("button", { name: "Fold Sidebar to Icons" }).click();await page.waitForTimeout(400);ok(await page.evaluate(() => window.__slid), "folding slides the content on the compositor");+// The account's picture is the photo on the person's own card, where it has one.+// (A plain browser cannot load quince:// — the picture falls back to initials, as it should —+// so what is checked is the picture asked for.)+await ctx.addInitScript(() => {+ window.__mePhoto = "me-card";+ window.__imgs = [];+ new MutationObserver((m) => {+ for (const r of m) for (const n of r.addedNodes) {+ if (n.nodeType !== 1) continue;+ for (const img of [n, ...n.querySelectorAll?.("img") ?? []]) if (img.tagName === "IMG") window.__imgs.push(img.getAttribute("src"));+ }+ }).observe(document, { childList: true, subtree: true });+});+await page.reload({ waitUntil: "networkidle" });+await page.waitForTimeout(300);+const asked = await page.evaluate(() => window.__imgs);+ok(asked.some((s) => s?.includes("me-card")), `the account shows the photo on the person's own card [${asked.join(", ")}]`);+ok((await page.locator(".sidebar-account .account-avatar").innerText()).trim() === "AR", "and its initials hold the place where the photo cannot be had");await b.close();process.exitCode = failures ? 1 : 0;diff --git a/.uiverify/sidebar-fold.mjs b/.uiverify/sidebar-fold.mjsnew file mode 100644index 0000000..f048b4f--- /dev/null+++ b/.uiverify/sidebar-fold.mjs@@ -0,0 +1,30 @@+// Folding the sidebar and opening it again: the content travels one way from where it was+// to where it goes, every frame — never drawn at the destination first and then thrown+// back, which was the whole window glitching.+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, calendarFixture: true });+const page = await ctx.newPage();+await page.goto("http://localhost:4173", { waitUntil: "networkidle" });+await openScreen(page, "Calendar");+await page.waitForTimeout(500);+let failures = 0;+for (const name of ["Fold Sidebar to Icons", "Show Sidebar Names"]) {+ await page.evaluate(() => {+ window.__xs = [];+ const h1 = document.querySelector(".cx-title");+ const tick = () => { window.__xs.push(Math.round(h1.getBoundingClientRect().left)); if (window.__xs.length < 30) requestAnimationFrame(tick); };+ requestAnimationFrame(tick);+ });+ await page.getByRole("button", { name }).click();+ await page.waitForTimeout(700);+ const xs = await page.evaluate(() => window.__xs);+ const dir = Math.sign(xs[xs.length - 1] - xs[0]);+ const back = xs.slice(1).filter((x, i) => Math.sign(x - xs[i]) === -dir && Math.abs(x - xs[i]) > 2).length;+ console.log(`${back ? "FAIL" : "PASS"} ${name}: the content moves one way [${xs.join(" ")}]`);+ if (back) failures++;+}+await b.close();+process.exitCode = failures ? 1 : 0;diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjsindex 0f26edc..8c83edc 100644--- a/.uiverify/stub.mjs+++ b/.uiverify/stub.mjs@@ -132,6 +132,8 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note];window.__TAURI_INTERNALS__ = {transformCallback: (cb) => cb,+ // As Tauri builds it on Linux (tauri/scripts/core.js): the whole path escaped.+ convertFileSrc: (path, protocol = "asset") => `${protocol}://localhost/${encodeURIComponent(path)}`,invoke: async (cmd, args) => {switch (cmd) {case "auth_status":@@ -238,7 +240,10 @@ export function installStub({ screen, services, twoFactor, calendarFixture, noteif (args.runs && kept === args.body) (window.__savedRuns ??= {})[args.guid] = args.runs;return kept;}- case "note_delete": case "note_move": return null;+ case "note_delete": return null;+ case "note_move":+ if (window.__slowMove) await new Promise((r) => setTimeout(r, window.__slowMove));+ return null;case "note_pin": {const n = noteList.find((x) => x.guid === args?.guid);if (n) n.pinned = args.pinned;@@ -285,7 +290,7 @@ export function installStub({ screen, services, twoFactor, calendarFixture, notecase "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 };- case "account_info": return { name: "Asha Rao", email: "[email protected]" };+ case "account_info": return { name: "Asha Rao", email: "[email protected]", photoContact: window.__mePhoto ?? null };case "settings_get": return { reminderAlerts: true, eventAlerts: true, ...(window.__settings ?? {}) };case "settings_set":if (window.__settingsFail) throw "Couldn't save that setting.";@@ -307,6 +312,14 @@ export function installStub({ screen, services, twoFactor, calendarFixture, notesize: 1500000, childCount: null, createdAt: 1786000000, modifiedAt: 1786000000, etag: "t2",expiresAt: Math.floor(Date.now() / 1000) + 2 * 86400 - 60, restorePath: "Wallpaper.jpg" },]).slice();+ case "drive_trash_out": {+ // One request for all of them, as Recover All / Delete All send it.+ (window.__trashBatches ??= []).push({ recover: args.recover, ids: args.items.map((i) => i.drivewsid) });+ const ids = new Set(args.items.map((i) => i.drivewsid));+ window.__trash = (window.__trash ?? []).filter((i) => !ids.has(i.drivewsid));+ for (const i of args.items) (window.__trashCalls ??= []).push([args.recover ? "drive_put_back" : "drive_delete_forever", i.drivewsid]);+ return [];+ }case "drive_put_back": case "drive_delete_forever":window.__trash = (window.__trash ?? []).filter((i) => i.drivewsid !== args.item.drivewsid);(window.__trashCalls ??= []).push([cmd, args.item.drivewsid]);@@ -340,8 +353,13 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note};// The event plugin is how a finished refresh reaches the screens. Nothing emits in// a plain browser, so listening is a no-op that hands back an unsubscribe id.- case "plugin:event|listen":+ case "plugin:event|listen": {+ // Kept, so a test can play a finished refresh in: `window.__emit(event, payload)`.+ const all = (window.__listeners ??= {});+ (all[args.event] ??= []).push(args.handler);+ window.__emit ??= (event, payload) => (window.__listeners[event] ?? []).forEach((h) => typeof h === "function" && h({ event, payload, id: 0 }));return 0;+ }case "plugin:event|unlisten":return null;default: throw new Error(`unstubbed command: ${cmd}`);diff --git a/check.sh b/check.shindex b935352..f44f3ba 100755--- a/check.sh+++ b/check.sh@@ -69,6 +69,11 @@ step "drive recents" node .uiverify/drive-recents.mjsstep "drive gone folder" node .uiverify/drive-gone.mjsstep "settings" node .uiverify/settings.mjsstep "calendar day steps" node .uiverify/calendar-daystep.mjs+step "sidebar fold" node .uiverify/sidebar-fold.mjs+step "pending writes" node .uiverify/pending-writes.mjs+step "row hover" node .uiverify/row-hover.mjs+step "webkit: row hover" env ENGINE=webkit node .uiverify/row-hover.mjs+step "webkit: fold" env ENGINE=webkit node .uiverify/sidebar-fold.mjsstep "reminder colours" node .uiverify/calendar-reminder-colour.mjsstep "calendar dblclick" node .uiverify/calendar-dblclick.mjsstep "menus" node .uiverify/menus.mjsdiff --git a/crates/quince-auth/src/lib.rs b/crates/quince-auth/src/lib.rsindex b946031..173964c 100644--- a/crates/quince-auth/src/lib.rs+++ b/crates/quince-auth/src/lib.rs@@ -962,6 +962,19 @@ impl Client {if let Some(email) = text("/dsInfo/primaryEmail").or_else(|| text("/dsInfo/appleId")) {self.session.account_email = Some(email);}+ if let Some(allowed) = data+ .pointer("/dsInfo/isWebAccessAllowed")+ .and_then(Value::as_bool)+ {+ self.session.web_access_allowed = Some(allowed);+ }+ if let Some(on) = data+ .get("iCDPEnabled")+ .or_else(|| data.pointer("/dsInfo/iCDPEnabled"))+ .and_then(Value::as_bool)+ {+ self.session.data_protection = Some(on);+ }}/// Query parameters every iCloud service endpoint expects alongside the session cookies.diff --git a/crates/quince-auth/src/session.rs b/crates/quince-auth/src/session.rsindex 47b40fe..d3c3ad9 100644--- a/crates/quince-auth/src/session.rs+++ b/crates/quince-auth/src/session.rs@@ -65,6 +65,14 @@ pub struct Session {pub account_name: Option<String>,#[serde(default)]pub account_email: Option<String>,+ /// Whether iCloud's data may be reached from the web at all (`dsInfo.isWebAccessAllowed`).+ /// Off on an account with Advanced Data Protection until the person turns on "Access+ /// iCloud Data on the Web" — and then nothing here can be read, whatever else is right.+ #[serde(default)]+ pub web_access_allowed: Option<bool>,+ /// Advanced Data Protection, which Apple calls iCloud Data Protection (`iCDPEnabled`).+ #[serde(default)]+ pub data_protection: Option<bool>,/// Failed sign-ins in a row. Drives the local backoff.#[serde(default)]diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex 13ad86f..b0efa50 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -164,6 +164,22 @@ async fn cloudkit_context(}/// Undo percent-encoding in a path segment. Enough for the ids this scheme carries.+/// The contact a `quince://` request asks for the photo of.+///+/// WebKitGTK reads `quince://photo/<id>` with "photo" as the host, while Tauri's own helper+/// builds `quince://localhost/photo%2F<id>` — the whole path escaped, slash and all. The path+/// is decoded before it is read: matched undecoded, no request ever found its photo, and every+/// contact showed initials with nothing to say why.+fn photo_guid(host: Option<&str>, path: &str) -> Option<String> {+ let path = percent_decode(path.trim_start_matches('/'));+ let guid = if host == Some("photo") {+ path+ } else {+ path.strip_prefix("photo/")?.to_string()+ };+ (!guid.is_empty()).then_some(guid)+}+fn percent_decode(text: &str) -> String {let bytes = text.as_bytes();let mut out = Vec::with_capacity(bytes.len());@@ -310,15 +326,36 @@ async fn auth_sign_out(auth: State<'_, Auth>) -> UiResult<()> {struct AccountInfo {name: Option<String>,email: Option<String>,+ /// `false` when the account keeps its data from the web: nothing can be read until+ /// the person turns on "Access iCloud Data on the Web".+ web_access_allowed: Option<bool>,+ /// Advanced Data Protection.+ data_protection: Option<bool>,+ /// The person's own card, when it has a photo: theirs to show as the account's picture,+ /// served like any contact's.+ photo_contact: Option<String>,}#[tauri::command]-async fn account_info(auth: State<'_, Auth>) -> UiResult<AccountInfo> {+async fn account_info(auth: State<'_, Auth>, data: State<'_, Data>) -> UiResult<AccountInfo> {+ // The picture is the person's own card's — the card Contacts marks as theirs.+ let photo_contact = {+ let library = data.0.lock().await;+ library+ .state(quince_icloud::contacts::ME_KEY)+ .ok()+ .flatten()+ .filter(|guid| !guid.is_empty())+ .filter(|guid| library.contact_photo_source(guid).ok().flatten().is_some())+ };let client = auth.client.lock().await;let s = client.session();Ok(AccountInfo {name: s.account_name.clone(),email: s.account_email.clone().or_else(|| s.apple_id.clone()),+ web_access_allowed: s.web_access_allowed,+ data_protection: s.data_protection,+ photo_contact,})}@@ -2515,6 +2552,35 @@ async fn drive_delete_forever(.map_err(|e| e.to_string())}+/// Recover or delete for good every one of these, in one request, as Recover All and+/// Delete All do on icloud.com. Answers what could not be done, each with why — the rest are+/// done and gone from Recently Deleted.+#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+struct TrashRefusal {+ drivewsid: String,+ reason: String,+}++#[tauri::command]+async fn drive_trash_out(+ items: Vec<quince_core::drive::DriveItem>,+ recover: bool,+ auth: State<'_, Auth>,+) -> UiResult<Vec<TrashRefusal>> {+ let (http, root, params) = drive_context(&auth).await?;+ let failed = if recover {+ quince_icloud::drive::put_back_many(&http, &root, params, &items).await+ } else {+ quince_icloud::drive::delete_forever_many(&http, &root, params, &items).await+ }+ .map_err(|e| e.to_string())?;+ Ok(failed+ .into_iter()+ .map(|(drivewsid, reason)| TrashRefusal { drivewsid, reason })+ .collect())+}+/// Move an item into a different folder, refreshing both the old and new location.#[tauri::command]async fn drive_move(@@ -2569,6 +2635,7 @@ async fn sync_all(keep_signed_in(&app, &client).await;let result = refresh::all(&client, &data.0).await;alerts::changed();+ warm_contact_photos(app.clone());// Screens read the library, not the network, so they only need to be told to look again.app.emit(SYNCED, &result).ok();Ok(result)@@ -2595,6 +2662,7 @@ fn spawn_auto_sync(app: tauri::AppHandle, client: Arc<Mutex<Client>>) {let data = app.state::<Data>();let result = refresh::all(&client, &data.0).await;alerts::changed();+ warm_contact_photos(app.clone());app.emit(SYNCED, &result).ok();}});@@ -2636,7 +2704,9 @@ fn photo_path(dir: &std::path::Path, guid: &str, signature: &str) -> PathBuf {.map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }).collect();// No extension: the format is Apple's to choose, and is read back from the bytes.- dir.join("photos").join(format!("{guid_safe}-{safe}"))+ // "faces": the folder before held pictures cut with the crop read upside down, and is+ // never read again.+ dir.join("faces").join(format!("{guid_safe}-{safe}"))}/// Serve a contact's picture to the interface.@@ -2708,6 +2778,39 @@ async fn contact_photo(})}+/// Fetch, in the background, every contact photo not yet on disk, so a face is already here+/// when its row is drawn rather than fetched from Apple as it scrolls into view. Three at a+/// time; one that fails is simply tried again after the next sync.+pub fn warm_contact_photos(app: tauri::AppHandle) {+ tauri::async_runtime::spawn(async move {+ let wanted: Vec<String> = {+ let data = app.state::<Data>();+ let library = data.0.lock().await;+ let dir = state_dir(&app);+ library+ .contacts(None)+ .unwrap_or_default()+ .into_iter()+ .filter(|c| c.photo_url.is_some())+ .filter(|c| match &c.photo_signature {+ Some(sig) => !photo_path(&dir, &c.guid, sig).exists(),+ None => false,+ })+ .map(|c| c.guid)+ .collect()+ };+ use futures_util::StreamExt;+ futures_util::stream::iter(wanted)+ .for_each_concurrent(3, |guid| {+ let app = app.clone();+ async move {+ let _ = contact_photo(&app, &guid).await;+ }+ })+ .await;+ });+}+/// Where this installation's writer id is kept.const WRITER_KEY: &str = "documents.writer";@@ -2844,12 +2947,9 @@ fn main() {// own helper produces `quince://localhost/photo/<id>`. Accept either, rather than// depending on which one the caller happened to build.let uri = request.uri();- let mut path = uri.path().trim_start_matches('/').to_string();- if uri.host() == Some("photo") {- path = format!("photo/{path}");- }+ let wanted = photo_guid(uri.host(), uri.path());tauri::async_runtime::spawn(async move {- let Some(guid) = path.strip_prefix("photo/") else {+ let Some(guid) = wanted else {responder.respond(tauri::http::Response::builder().status(404)@@ -2858,9 +2958,6 @@ fn main() {);return;};- // Percent-encoding: a contact id is a plain UUID, but the scheme should not- // assume what a future caller puts here.- let guid = percent_decode(guid);match contact_photo(&app, &guid).await {Ok(Photo { bytes, durable }) => responder.respond(tauri::http::Response::builder()@@ -3002,6 +3099,7 @@ fn main() {drive_thumbnails,drive_put_back,drive_delete_forever,+ drive_trash_out,drive_move,drive_item,reminder_set_done,@@ -3047,6 +3145,22 @@ mod tests {#[test]fn a_percent_encoded_id_comes_back_as_itself() {assert_eq!(percent_decode("a%2Fb"), "a/b");+ // What convertFileSrc("photo/<id>", "quince") builds, and what WebKitGTK reads.+ let id = "9C2B1E7A-0F4D-4E25-8A61-3C1D2E4F5A6B";+ assert_eq!(+ photo_guid(Some("localhost"), &format!("/photo%2F{id}")).as_deref(),+ Some(id)+ );+ assert_eq!(+ photo_guid(Some("localhost"), &format!("/photo/{id}")).as_deref(),+ Some(id)+ );+ assert_eq!(+ photo_guid(Some("photo"), &format!("/{id}")).as_deref(),+ Some(id)+ );+ assert_eq!(photo_guid(Some("localhost"), "/other%2Fx"), None);+ assert_eq!(photo_guid(Some("localhost"), "/photo%2F"), None);assert_eq!(percent_decode("plain-uuid"), "plain-uuid");assert_eq!(percent_decode("%zz"), "%zz", "malformed stays as it was");}diff --git a/src-tauri/src/push.rs b/src-tauri/src/push.rsindex 3e278aa..bcd4166 100644--- a/src-tauri/src/push.rs+++ b/src-tauri/src/push.rs@@ -187,6 +187,9 @@ async fn refresher(let data = app.state::<Data>();refresh::some(&client, &data.0, &services).await;alerts::changed();+ if services.contains(&"contacts") {+ crate::warm_contact_photos(app.clone());+ }// Every service's freshness, not only the ones refreshed: the window shows the whole.app.emit(SYNCED, refresh::status(&data.0).await).ok();}diff --git a/src/components/Account.tsx b/src/components/Account.tsxindex bb1e814..20f7cca 100644--- a/src/components/Account.tsx+++ b/src/components/Account.tsx@@ -1,5 +1,6 @@import { useEffect, useState } from "react";-import { api } from "../lib/ipc";+import { Face } from "./Face";+import { api, contactPhotoSrc, type AccountInfo } from "../lib/ipc";import { freshness, useSync } from "../lib/sync";/** "Asha Rao" → "AR"; an address → its first letter. */@@ -10,22 +11,37 @@ export function initialsOf(name: string): string {return (words[0][0]! + words[words.length - 1][0]!).toUpperCase();}+/**+ * The account's picture: the photo on the person's own card, as Apple shows it; their+ * initials on Apple's grey disc where there is none, or until it has loaded.+ */+export function AccountAvatar({ account, large }: { account: AccountInfo | null; large?: boolean }) {+ const initials = initialsOf(account?.name ?? account?.email ?? "");+ return (+ <span className={`account-avatar${large ? " is-large" : ""}`} aria-hidden="true">+ <Face src={account?.photoContact ? contactPhotoSrc(account.photoContact) : null} initials={initials} />+ </span>+ );+}+/*** The account at the foot of the sidebar — who is signed in and how fresh their iCloud is —* and the way into Settings, as System Settings puts the account at the head of its list.*/export function AccountCard({ current, onOpen }: { current: boolean; onOpen: () => void }) {- const [account, setAccount] = useState<{ name: string | null; email: string | null } | null>(null);+ const [account, setAccount] = useState<AccountInfo | null>(null);const { report, syncing, error } = useSync();useEffect(() => {api.accountInfo().then(setAccount, () => {});}, []);const failed = error || report?.services.some((s) => s.outcome === "failed");const status = syncing ? "Syncing…" : failed ? "Some things didn't update" : freshness(report?.asOf ?? null);- const name = account?.name ?? account?.email ?? "Settings";+ // The first name, as the menu bar greets someone: a full name did not fit the sidebar and+ // ended in "…". Settings shows it whole.+ const name = account?.name?.split(/\s+/)[0] ?? account?.email ?? "Settings";return (<button className="sidebar-account" aria-current={current} onClick={onOpen} title="Settings">- <span className="account-avatar" aria-hidden="true">{initialsOf(name)}</span>+ <AccountAvatar account={account} /><span className="sidebar-account-text"><span className="sidebar-account-name">{name}</span><span className={`sidebar-account-status${failed ? " is-trouble" : ""}`}>diff --git a/src/components/Face.tsx b/src/components/Face.tsxnew file mode 100644index 0000000..54fb8fe--- /dev/null+++ b/src/components/Face.tsx@@ -0,0 +1,37 @@+import { useLayoutEffect, useRef, useState } from "react";++/**+ * A person's picture over their initials, as Contacts draws one.+ *+ * The initials hold the place until the picture is decoded, and the picture then fades in+ * over them — never initials swapped for a picture in one jump, which read as a flicker.+ * A picture already to hand (the backend keeps each on disk, the window keeps it in memory)+ * is drawn at once with no fade: there is nothing to wait for, so nothing should move. One+ * that cannot be had leaves the initials, never a broken frame.+ */+export function Face({ src, initials }: { src: string | null; initials: string }) {+ const img = useRef<HTMLImageElement | null>(null);+ const [state, setState] = useState<"loading" | "ready" | "instant" | "failed">("loading");+ // Reset for a different picture; decided before paint whether it is already there.+ useLayoutEffect(() => {+ const el = img.current;+ setState(el && el.complete && el.naturalWidth > 0 ? "instant" : "loading");+ }, [src]);+ return (+ <>+ {state !== "ready" && state !== "instant" && <span className="face-initials">{initials}</span>}+ {src && state !== "failed" && (+ <img+ ref={img}+ className={`face-photo is-${state}`}+ src={src}+ alt=""+ decoding="async"+ draggable={false}+ onLoad={() => setState((s) => (s === "instant" ? s : "ready"))}+ onError={() => setState("failed")}+ />+ )}+ </>+ );+}diff --git a/src/components/Picker.tsx b/src/components/Picker.tsxindex 9a32ee5..5655a58 100644--- a/src/components/Picker.tsx+++ b/src/components/Picker.tsx@@ -22,6 +22,7 @@ export function Picker({label,disabled = false,className = "",+ pullDown = true,}: {value: string;options: PickerOption[];@@ -30,6 +31,10 @@ export function Picker({label: string;disabled?: boolean;className?: string;+ /** Dropped below the button (the default), as a pull-down is, rather than laid over it+ * with the choice on the button as a Mac pop-up is. Laid over, a menu in a form covered+ * the rows around it, and one in a toolbar climbed over the window's top edge. */+ pullDown?: boolean;}) {const [open, setOpenState] = useState(false);/** Whether the menu is open as of the last key, ahead of the render that shows it: two@@ -71,6 +76,18 @@ export function Picker({const maxHeight = window.innerHeight - pad * 2;const height = Math.min(list.scrollHeight, maxHeight);const width = Math.max(b.width, list.scrollWidth);+ if (pullDown) {+ // Below the button, its left edge with the button's; above it only where there is not+ // room below.+ const below = window.innerHeight - pad - (b.bottom + 4);+ const fitsBelow = below >= Math.min(height, 160);+ const room = fitsBelow ? below : b.top - 4 - pad;+ const h = Math.min(height, room);+ const top = fitsBelow ? b.bottom + 4 : b.top - 4 - h;+ const left = Math.max(pad, Math.min(b.left, window.innerWidth - pad - width));+ setPlace({ left, top, width, maxHeight: room });+ return;+ }// The chosen row's label over the button's label.const rowTop = chosen ? chosen.offsetTop : 0;let top = b.top - rowTop + (b.height - (chosen?.offsetHeight ?? b.height)) / 2;@@ -104,9 +121,20 @@ export function Picker({// value is where someone is navigating away from./** Where the pointer was when it was last seen over the menu; none since it opened. */const pointer = useRef<{ x: number; y: number } | null>(null);- const openMenu = () => {+ /** Whether a row is lit. On opening only the ✓ shows what is chosen, as a Mac menu opens:+ * lit as well, the current row read as two marks for one thing. The pointer moving or a+ * key lights a row. */+ const [lit, setLitState] = useState(false);+ const litNow = useRef(false);+ const setLit = (to: boolean) => {+ litNow.current = to;+ setLitState(to);+ };+ const openMenu = (byKey = false) => {if (disabled) return;pointer.current = null;+ // Opened from the keyboard, the current row is lit straight away, as on the Mac.+ setLit(byKey);setActive(Math.max(0, options.findIndex((o) => o.value === value)));setOpen(true);};@@ -159,6 +187,11 @@ export function Picker({const move = (to: (at: number) => number) => {e.preventDefault();byKeyboard.current = true;+ // The first key lights the row it starts from; the next ones move.+ if (!litNow.current) {+ setLit(true);+ return;+ }setActive((at) => Math.max(0, Math.min(to(at), options.length - 1)));};if (e.key === "ArrowDown") move((at) => at + 1);@@ -186,14 +219,14 @@ export function Picker({aria-expanded={open}aria-label={label}disabled={disabled}- onClick={() => (open ? close(false) : openMenu())}+ onClick={() => (open ? close(false) : openMenu(false))}onKeyDown={(e) => {// Open already, with focus not yet moved in: a key pressed that quickly is the// menu's. Opening it again put the highlight back and the key was lost.if (isOpen.current) return onListKey(e);if (e.key === "ArrowDown" || e.key === "ArrowUp") {e.preventDefault();- openMenu();+ openMenu(true);}}}>@@ -226,7 +259,7 @@ export function Picker({role="option"aria-selected={option.value === value}tabIndex={index === active ? 0 : -1}- className={index === active ? "is-active" : undefined}+ className={lit && index === active ? "is-active" : undefined}onKeyDown={onListKey}onClick={() => choose(index)}// The pointer highlights a row only once it moves. The menu opens over the@@ -239,6 +272,7 @@ export function Picker({pointer.current = { x: e.clientX, y: e.clientY };if (first) return;byKeyboard.current = false;+ setLit(true);setActive(index);}}>diff --git a/src/lib/ipc.ts b/src/lib/ipc.tsindex 46b58af..8387596 100644--- a/src/lib/ipc.ts+++ b/src/lib/ipc.ts@@ -210,12 +210,15 @@ export const api = {driveDuplicate: (drivewsid: string) => invoke<void>("drive_duplicate", { drivewsid }),storageInfo: () => invoke<{ usedBytes: number; totalBytes: number }>("storage_info"),/** Who is signed in, as Apple names them. */- accountInfo: () => invoke<{ name: string | null; email: string | null }>("account_info"),+ accountInfo: () => invoke<AccountInfo>("account_info"),/** Settings' switches, as the backend obeys them. */settingsGet: () => invoke<{ reminderAlerts: boolean; eventAlerts: boolean }>("settings_get"),settingsSet: (key: "reminderAlerts" | "eventAlerts", on: boolean) => invoke<void>("settings_set", { key, on }),drivePutBack: (item: DriveItem) => invoke<void>("drive_put_back", { item }),driveDeleteForever: (item: DriveItem) => invoke<void>("drive_delete_forever", { item }),+ /** Recover, or delete for good, all of these in one request; what could not be, with why. */+ driveTrashOut: (items: DriveItem[], recover: boolean) =>+ invoke<{ drivewsid: string; reason: string }[]>("drive_trash_out", { items, recover }),driveMove: (drivewsid: string, destinationId: string) =>invoke<void>("drive_move", { drivewsid, destinationId }),};@@ -475,8 +478,22 @@ export type Contact = {* it does any image, so a list of a hundred people does not push a hundred pictures through* a message channel every time it scrolls.*/+/** Who is signed in. `photoContact` is their own card, when it has a picture. */+export type AccountInfo = {+ name: string | null;+ email: string | null;+ webAccessAllowed?: boolean | null;+ dataProtection?: boolean | null;+ photoContact?: string | null;+};++/** The picture of the contact with this id, served by the backend. */+export function contactPhotoSrc(guid: string): string {+ return convertFileSrc(`photo/${guid}`, "quince");+}+export function photoSrc(c: Contact): string | null {- return c.photoUrl ? convertFileSrc(`photo/${c.guid}`, "quince") : null;+ return c.photoUrl ? contactPhotoSrc(c.guid) : null;}export function displayName(c: Contact): string {diff --git a/src/lib/pending.ts b/src/lib/pending.tsnew file mode 100644index 0000000..307760a--- /dev/null+++ b/src/lib/pending.ts@@ -0,0 +1,24 @@+import { useCallback, useRef } from "react";++/**+ * Changes on their way to Apple, kept over every read of the library until they land.+ *+ * A change is drawn the moment it is made, then sent. While it is out, a refresh can finish+ * — Apple's push for that very change arrives within a second — and read the library from+ * before it was stored: a note moved to another folder came back in the old one for a+ * moment, then went again. Every read lays the changes still out over what it read, so what+ * is on screen only ever moves forward.+ */+export function usePending<T>() {+ const pending = useRef<((rows: T[]) => T[])[]>([]);+ /** Hold a change over reads; the returned function lets it go once it has landed. */+ const hold = useCallback((predict: (rows: T[]) => T[]) => {+ pending.current.push(predict);+ return () => {+ pending.current = pending.current.filter((p) => p !== predict);+ };+ }, []);+ /** What was read, with every change still on its way laid over it. */+ const over = useCallback((rows: T[]) => pending.current.reduce((acc, p) => p(acc), rows), []);+ return { hold, over };+}diff --git a/src/screens/ContactsView.tsx b/src/screens/ContactsView.tsxindex dc69cd7..a1ca338 100644--- a/src/screens/ContactsView.tsx+++ b/src/screens/ContactsView.tsx@@ -1,4 +1,5 @@import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from "react";+import { Face } from "../components/Face";import { Notice } from "../components/Notice";import { ChevronLeft, Plus, UsersRound, UserRound } from "lucide-react";import {@@ -36,15 +37,9 @@ const KINDS = [* does the initials underneath are what shows, rather than a broken frame.*/function Avatar({ contact, large }: { contact: Contact; large?: boolean }) {- const [failed, setFailed] = useState(false);- const src = failed ? null : photoSrc(contact);return (<span className={`avatar${large ? " large" : ""}`} aria-hidden="true">- {src ? (- <img src={src} alt="" onError={() => setFailed(true)} />- ) : (- initials(contact)- )}+ <Face src={photoSrc(contact)} initials={initials(contact)} /></span>);}@@ -461,8 +456,8 @@ export function ContactsView() {<section className="contacts-list" aria-label="Contacts"><header className="cal-bar"><div className="cal-nav">+ {/* The count is the sidebar's, beside the list's name; said twice it was noise. */}<h1>{openList?.name ?? "Contacts"}</h1>- <span className="badge">{shown.length}</span></div><div className="cal-actions"><button className="quiet" disabled={busy} onClick={() => setDraft(blank())}>diff --git a/src/screens/DriveView.tsx b/src/screens/DriveView.tsxindex e880ecc..4580a2b 100644--- a/src/screens/DriveView.tsx+++ b/src/screens/DriveView.tsx@@ -98,21 +98,33 @@ function DriveTrash({ onClose }: { onClose: () => void }) {void read();}, [read]);- const out = async (gone: TrashItem[], run: (i: DriveItem) => Promise<void>) => {+ // Every item asked for goes in one request, as icloud.com's Recover All and Delete All+ // send them; one request each, all at once, Apple turned most away as busy. They leave the+ // list at once; whatever Apple did not do comes back, with the reason.+ const out = async (gone: TrashItem[], recover: boolean) => {const ids = new Set(gone.map((i) => i.drivewsid));setRows((r) => (r ?? []).filter((i) => !ids.has(i.drivewsid)));setError(null);- const failed = (await Promise.allSettled(gone.map(run))).find((r) => r.status === "rejected");- if (failed) {- setError(messageOf((failed as PromiseRejectedResult).reason));+ try {+ const refused = await api.driveTrashOut(gone, recover);+ if (refused.length > 0) {+ setError(+ refused.length === 1+ ? refused[0].reason+ : `${refused.length} of ${gone.length} items could not be ${recover ? "recovered" : "deleted"}: ${refused[0].reason}`,+ );+ await read();+ }+ } catch (e) {+ setError(messageOf(e));await read();}};- const recover = (items: TrashItem[]) => out(items, (i) => api.drivePutBack(i));+ const recover = (items: TrashItem[]) => out(items, true);const destroy = (items: TrashItem[]) => {const what = items.length === 1 ? `\u201c${driveName(items[0])}\u201d` : `these ${items.length} items`;if (!window.confirm(`Delete ${what} now? You can\u2019t undo this.`)) return;- void out(items, (i) => api.driveDeleteForever(i));+ void out(items, false);};return (@@ -901,6 +913,7 @@ export function DriveView() {Recently Deleted</button><Picker+ pullDownclassName="drive-view"label="View as"value={grid ? "grid" : "list"}@@ -908,6 +921,7 @@ export function DriveView() {options={[{ value: "grid", label: "Grid" }, { value: "list", label: "List" }]}/><Picker+ pullDownclassName="drive-sort"label="Sort by"value={sortBy}diff --git a/src/screens/Library.tsx b/src/screens/Library.tsxindex fb988eb..e5908f7 100644--- a/src/screens/Library.tsx+++ b/src/screens/Library.tsx@@ -1,4 +1,4 @@-import { lazy, Suspense, useEffect, useRef, useState } from "react";+import { lazy, Suspense, useEffect, useLayoutEffect, useRef, useState } from "react";import { listen } from "@tauri-apps/api/event";import { PanelLeft } from "lucide-react";import { api, messageOf, OPEN_REMINDER } from "../lib/ipc";@@ -63,28 +63,35 @@ export function Library({ onSignOut }: { onSignOut: () => void }) {}});const content = useRef<HTMLElement | null>(null);+ /** Where the content began before a fold, for it to slide from. */+ const slideFrom = useRef<number | null>(null);+ const contentLeft = () => {+ const el = content.current;+ return el ? el.getBoundingClientRect().left + parseFloat(getComputedStyle(el).paddingLeft) : 0;+ };/*** Folding the sidebar moves the content without laying it out on every frame. Animating* the content's padding made the whole screen — a calendar grid, a long list — lay itself* out sixty times a second, and that was the stutter. Instead it takes its new width at- * once and slides from where it was, which the compositor does alone.+ * once and slides from where it was, which the compositor does alone. Started in a layout+ * effect — after the new layout, before it is painted — so no frame ever shows the content+ * in its new place and then back in the old: started a frame later, that jump was the+ * whole window glitching.*/- const slideContent = (from: number) => {+ useLayoutEffect(() => {+ const from = slideFrom.current;+ slideFrom.current = null;const el = content.current;- if (!el || window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;- requestAnimationFrame(() => {- const to = el.getBoundingClientRect().left + parseFloat(getComputedStyle(el).paddingLeft);- const by = from - to;- if (Math.abs(by) < 1) return;- el.animate([{ transform: `translateX(${by}px)` }, { transform: "none" }], {- duration: 300,- easing: getComputedStyle(document.documentElement).getPropertyValue("--spring-quick").trim() || "ease-out",- });+ if (from === null || !el || window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;+ const by = from - contentLeft();+ if (Math.abs(by) < 1) return;+ el.animate([{ transform: `translateX(${by}px)` }, { transform: "none" }], {+ duration: 300,+ easing: getComputedStyle(document.documentElement).getPropertyValue("--spring-quick").trim() || "ease-out",});- };+ }, [rail]);const toggleRail = () => {- const el = content.current;- if (el) slideContent(el.getBoundingClientRect().left + parseFloat(getComputedStyle(el).paddingLeft));+ slideFrom.current = contentLeft();setRailState();};const setRailState = () =>diff --git a/src/screens/NotesView.tsx b/src/screens/NotesView.tsxindex 1ba67c2..0af73e2 100644--- a/src/screens/NotesView.tsx+++ b/src/screens/NotesView.tsx@@ -1,4 +1,5 @@import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from "react";+import { usePending } from "../lib/pending";import { Notice } from "../components/Notice";import { ChevronLeft, Folder, FolderOpen, FolderPlus, ListChecks, Pin, PinOff, SquarePen, Trash2 } from "lucide-react";import { editorDate, groupNotes, listDate, mergeEdits, splitTitle } from "./notes/model";@@ -70,6 +71,7 @@ export function NotesView() {per: new Map(),});+ const { hold, over } = usePending<Note>();const read = useCallback(async () => {api.noteCounts()@@ -83,9 +85,9 @@ export function NotesView() {searching ? api.notesSearch(query) : api.notesIn(folder === ALL ? null : folder),]);setFolders(Array.isArray(found) ? found : []);- setNotes(Array.isArray(list) ? list : []);+ setNotes(over(Array.isArray(list) ? list : []));setLoaded(true);- }, [folder, query, searching]);+ }, [folder, query, searching, over]);// Reads the library and nothing else. `revision` ticks when a refresh finishes, whether// someone pressed for it or the timer came round, and that is the screen's whole@@ -117,19 +119,24 @@ export function NotesView() {setBusy(true);setError(null);if (predict) setNotes((rows) => predict(rows));+ // Kept over any refresh until Apple has it; let go before the read that confirms it.+ const release = predict ? hold(predict) : () => {};try {await run();+ release();await read();return true;} catch (e) {+ release();setError(messageOf(e));read().catch(() => {});return false;} finally {+ release();setBusy(false);}},- [read]+ [read, hold]);/** Mirrors `composing` for effects that must not re-run when it changes. */@@ -838,6 +845,7 @@ export function NotesView() {</>)}{!inTrash && <Picker+ pullDownlabel={`Folder for ${open.title}`}value={open.folderGuid ?? ALL}disabled={busy}diff --git a/src/screens/RemindersView.tsx b/src/screens/RemindersView.tsxindex 8f1e171..33e1051 100644--- a/src/screens/RemindersView.tsx+++ b/src/screens/RemindersView.tsx@@ -1,4 +1,5 @@import { Fragment, useCallback, useEffect, useMemo, useState } from "react";+import { usePending } from "../lib/pending";import { Notice } from "../components/Notice";import { Portal } from "../components/Portal";import { TimeField } from "../components/TimeField";@@ -16,6 +17,7 @@ import {} from "../lib/ipc";import { useSync } from "../lib/sync";import { Picker } from "../components/Picker";+import { RowMenu } from "../components/RowMenu";import { Glyph, emblemGlyph, type GlyphName } from "../components/Glyph";import { dateText, timeText } from "../lib/when";@@ -177,6 +179,8 @@ type Selection =export function RemindersView() {const [lists, setLists] = useState<ReminderList[]>([]);+ /** A list's menu, from its ⋯ or a right-click. */+ const [listMenu, setListMenu] = useState<{ list: ReminderList; at: { x: number; y: number; alignRight: boolean } } | null>(null);/** The list whose Show List Info sheet is open. */const [infoFor, setInfoFor] = useState<ReminderList | null>(null);const [groups, setGroups] = useState<ReminderGroup[]>([]);@@ -262,6 +266,7 @@ export function RemindersView() {*/const [detail, setDetail] = useState(false);+ const { hold, over } = usePending<Reminder>();const readItems = useCallback(async (): Promise<Reminder[]> => {// Search reaches every list, as Apple's does, whatever is open in the sidebar.const found = searching@@ -269,10 +274,10 @@ export function RemindersView() {: selection.type === "smart"? await api.remindersSmart(selection.kind, endOfToday()): await api.remindersIn(selection.guid, showDone);- const fresh = (Array.isArray(found) ? found : []).map(asShown);+ const fresh = over((Array.isArray(found) ? found : []).map(asShown));setItems(fresh);return fresh;- }, [selection, showDone, query, searching]);+ }, [selection, showDone, query, searching, over]);// Both reads come from the library. `revision` ticks when the shared refresh finishes —// pressed, or on the timer — so a reminder ticked on the phone appears here without this@@ -319,14 +324,19 @@ export function RemindersView() {setBusy((was) => new Set(was).add(reminder.guid));setError(null);if (predict) setItems((rows) => predict(rows));+ // Kept over any refresh until Apple has it; let go before the read that confirms it.+ const release = predict ? hold(predict) : () => {};try {await run();+ release();return await readItems();} catch (e) {+ release();setError(messageOf(e));readItems().catch(() => {});return null;} finally {+ release();setBusy((was) => {const next = new Set(was);next.delete(reminder.guid);@@ -334,7 +344,7 @@ export function RemindersView() {});}},- [readItems],+ [readItems, hold],);/**@@ -806,7 +816,7 @@ export function RemindersView() {const inGroup = (guid: string) => lists.filter((l) => !l.pinned && l.groupGuid === guid);const listRow = (list: ReminderList, nested: boolean) => (- <div className={`rx-list-row${nested ? " nested" : ""}`} key={list.guid}>+ <div className={`rx-list-row${nested ? " nested" : ""}${listMenu?.list.guid === list.guid ? " is-menu" : ""}`} key={list.guid}>{renaming === list.guid ? (<inputclassName="rx-rename"@@ -839,6 +849,10 @@ export function RemindersView() {setDetail(true);}}onDoubleClick={() => setRenaming(list.guid)}+ onContextMenu={(e) => {+ e.preventDefault();+ setListMenu({ list, at: { x: e.clientX, y: e.clientY, alignRight: false } });+ }}><span className="rx-badge" style={{ background: colourOf(list) }}><Glyph name={emblemGlyph(list.emblem)} />@@ -846,37 +860,19 @@ export function RemindersView() {<span className="rx-list-name">{list.title}</span><span className="rx-list-count">{countOf(list.guid)}</span></button>- <span className="rx-list-actions">- <button- className="rx-icon-button"- aria-label={`Show List Info for ${list.title}`}- title="Show List Info"- onClick={() => setInfoFor(list)}- >- ⓘ- </button>- <button- className="rx-icon-button"- aria-label={`Rename ${list.title}`}- title="Rename"- onClick={() => setRenaming(list.guid)}- >- ✎- </button>- <button- className="rx-icon-button danger"- aria-label={`Delete ${list.title}`}- title="Delete"- onClick={() => {- // Deleting a list takes its reminders, so ask before doing it.- if (window.confirm(`Delete "${list.title}" and everything in it?`)) {- void listWrite(() => api.reminderListDelete(list.guid));- }- }}- >- ×- </button>- </span>+ {/* One ⋯ over where the count sits, as Notes' and Contacts' rows have: three+ buttons there covered the list's own name. Right-click opens the same menu. */}+ <button+ className="notes-folder-more rx-list-more"+ aria-label={`Actions for ${list.title}`}+ aria-haspopup="menu"+ onClick={(e) => {+ const r = e.currentTarget.getBoundingClientRect();+ setListMenu({ list, at: { x: r.right, y: r.bottom + 4, alignRight: true } });+ }}+ >+ <span aria-hidden="true">•••</span>+ </button></>)}</div>@@ -1345,6 +1341,28 @@ export function RemindersView() {</p>)}</section>+ {listMenu && (+ <RowMenu+ at={listMenu.at}+ onClose={() => setListMenu(null)}+ entries={[+ { label: "Show List Info", run: () => setInfoFor(listMenu.list) },+ { label: "Rename List", run: () => setRenaming(listMenu.list.guid) },+ null,+ {+ label: "Delete List…",+ danger: true,+ run: () => {+ const list = listMenu.list;+ // Deleting a list takes its reminders, so ask before doing it.+ if (window.confirm(`Delete "${list.title}" and everything in it?`)) {+ void listWrite(() => api.reminderListDelete(list.guid));+ }+ },+ },+ ]}+ />+ )}{infoFor && (<ListInfolist={infoFor}diff --git a/src/screens/SettingsView.tsx b/src/screens/SettingsView.tsxindex c3744fc..85f153b 100644--- a/src/screens/SettingsView.tsx+++ b/src/screens/SettingsView.tsx@@ -1,10 +1,10 @@import { useEffect, useState } from "react";import { getVersion } from "@tauri-apps/api/app";-import { api, messageOf } from "../lib/ipc";+import { api, messageOf, type AccountInfo } from "../lib/ipc";import { freshness, useSync } from "../lib/sync";import { setTheme, storedTheme, type Theme } from "../lib/theme";import { AppIcon } from "../components/AppIcon";-import { initialsOf } from "../components/Account";+import { AccountAvatar } from "../components/Account";/** The app each service's freshness belongs to, for its icon. */const ICON: Record<string, string> = {@@ -27,7 +27,7 @@ function size(bytes: number): string {* from Apple or from this computer's library.*/export function SettingsView({ onSignOut }: { onSignOut: () => void }) {- const [account, setAccount] = useState<{ name: string | null; email: string | null } | null>(null);+ const [account, setAccount] = useState<AccountInfo | null>(null);const [storage, setStorage] = useState<{ usedBytes: number; totalBytes: number } | null>(null);const [alerts, setAlerts] = useState<{ reminderAlerts: boolean; eventAlerts: boolean } | null>(null);const [theme, chooseTheme] = useState<Theme>(storedTheme);@@ -63,7 +63,7 @@ export function SettingsView({ onSignOut }: { onSignOut: () => void }) {{error && <p className="settings-error" role="alert">{error}</p>}<section className="settings-group settings-account" aria-label="Account">- <span className="account-avatar is-large" aria-hidden="true">{initialsOf(account?.name ?? account?.email ?? "")}</span>+ <AccountAvatar account={account} large /><div className="settings-account-text"><strong>{account?.name ?? "Your Apple Account"}</strong><span>{account?.email ?? ""}</span>@@ -74,7 +74,7 @@ export function SettingsView({ onSignOut }: { onSignOut: () => void }) {<button className="quiet danger" onClick={onSignOut}>Sign Out</button></span>) : (- <button className="quiet" onClick={() => setConfirming(true)}>Sign Out…</button>+ <button className="quiet" onClick={() => setConfirming(true)}>Sign Out</button>)}</section>{confirming && (diff --git a/src/screens/calendar/CalendarView.tsx b/src/screens/calendar/CalendarView.tsxindex 3278298..cea9d04 100644--- a/src/screens/calendar/CalendarView.tsx+++ b/src/screens/calendar/CalendarView.tsx@@ -1,4 +1,5 @@import { Notice } from "../../components/Notice";+import { usePending } from "../../lib/pending";import { inMenu, Portal } from "../../components/Portal";import { TimeField } from "../../components/TimeField";import { Search } from "lucide-react";@@ -313,6 +314,7 @@ export function CalendarView() {// eslint-disable-next-line react-hooks/exhaustive-depsconst range = useMemo(() => rawRange, [rangeKey]);+ const { hold, over } = usePending<CalendarEvent>();const read = useCallback(async () => {const [found, cals, reminders, lists] = await Promise.all([api.calendarEvents(range.from, range.to),@@ -321,7 +323,7 @@ export function CalendarView() {api.reminderLists().catch(() => []),]);setListColours(new Map((Array.isArray(lists) ? lists : []).map((l) => [l.guid, l.colour && /^#[0-9a-f]{6}$/i.test(l.colour) ? l.colour : ""])));- setEvents(Array.isArray(found) ? found : []);+ setEvents(over(Array.isArray(found) ? found : []));setCalendars(Array.isArray(cals) ? cals : []);// What is done is not on the schedule any more; Calendar hides completed reminders.// An all-day reminder's date is Apple's: midnight UTC on its day. Read as an instant it@@ -333,7 +335,7 @@ export function CalendarView() {};setDue(Array.isArray(reminders) ? reminders.filter((r) => !r.completedAt).map(onItsDay) : []);setLoaded(true);- }, [range]);+ }, [range, over]);useEffect(() => {let cancelled = false;@@ -404,19 +406,24 @@ export function CalendarView() {setBusy(true);setError(null);if (predict) setEvents((rows) => predict(rows));+ // Kept over any refresh until Apple has it; let go before the read that confirms it.+ const release = predict ? hold(predict) : () => {};try {await run();+ release();await read();return true;} catch (e) {+ release();setError(messageOf(e));read().catch(() => {});return false;} finally {+ release();setBusy(false);}},- [read]+ [read, hold]);/**diff --git a/src/styles/app.css b/src/styles/app.cssindex b5bffbf..512b96a 100644--- a/src/styles/app.css+++ b/src/styles/app.css@@ -1954,6 +1954,17 @@box-shadow: inset 0 0.5px 0 rgba(255, 255, 255, 0.35);}.account-avatar.is-large { width: 56px; height: 56px; font-size: 21px; }+.account-avatar { overflow: hidden; position: relative; }++/* A face over its initials (components/Face): the photo fades in once decoded, or is simply+ there when it was already to hand. */+.avatar { position: relative; overflow: hidden; }+.face-photo { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; display: block; }+.face-photo.is-loading { opacity: 0; }+.face-photo.is-ready { opacity: 1; animation: face-in 180ms ease-out; }+.face-photo.is-instant { opacity: 1; }+@keyframes face-in { from { opacity: 0; } to { opacity: 1; } }+@media (prefers-reduced-motion: reduce) { .face-photo.is-ready { animation: none; } }@media (min-width: 901px) {.is-rail .sidebar-foot { display: flex; }.is-rail .sidebar-account { justify-content: center; padding-inline: 0; }diff --git a/src/styles/notes.css b/src/styles/notes.cssindex 501c3c2..ed058ff 100644--- a/src/styles/notes.css+++ b/src/styles/notes.css@@ -42,13 +42,16 @@text-align: left;cursor: default;}+/* On the row, not the button alone — the ⋯ over the row took the hover off the button and+ the highlight blinked (see .rx-list-row). */+.notes-folder-row:hover .notes-folder, .notes-folder-row.is-menu .notes-folder,.notes-folder:hover { background: color-mix(in srgb, var(--text) 6%, transparent); }.notes-folder[aria-current="true"] { background: color-mix(in srgb, var(--text) 12%, transparent); }.notes-folder:focus-visible { outline: 3px solid var(--accent-ring); outline-offset: -1px; }/* Apple's folders are drawn in the accent, which in Notes is its yellow — here, quince gold. */.notes-folder-glyph { flex: none; color: var(--accent); }.notes-folder-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }-.notes-folder-count { color: var(--text-3); font-variant-numeric: tabular-nums; }+.notes-folder-count { min-width: 26px; text-align: right; color: var(--text-3); font-variant-numeric: tabular-nums; }/* ---- the list ------------------------------------------------------------------- */diff --git a/src/styles/reminders.css b/src/styles/reminders.cssindex 597c66a..b0e0ea8 100644--- a/src/styles/reminders.css+++ b/src/styles/reminders.css@@ -179,7 +179,10 @@text-align: left;cursor: default;}-.rx-list:hover,+/* The highlight follows the row, not the list's button alone: the ⋯ sits over the row+ beside the button, and moving onto it took the hover off the button — the highlight+ blinked out and back. Held while the row's menu is open too. */+.rx-list-row:hover .rx-list, .rx-list-row.is-menu .rx-list,.rx-group-row:hover { background: color-mix(in srgb, var(--text) 6%, transparent); }.rx-list[aria-current="true"] { background: color-mix(in srgb, var(--text) 12%, transparent); }.rx-list:focus-visible,@@ -211,7 +214,8 @@.rx-group-row .rx-list-name { font-weight: 600; }.rx-list-count {- min-width: 18px;+ /* Wide enough for the ⋯ that takes its place, so nothing beside it moves when it does. */+ min-width: 26px;color: var(--text-3);font-size: var(--t-13);font-variant-numeric: tabular-nums;@@ -222,19 +226,14 @@.rx-chevron svg { width: 12px; height: 12px; }.rx-group-row[aria-expanded="true"] .rx-chevron { transform: rotate(90deg); }-/* Rename and delete wait until a list is pointed at, over where its count sits. */-.rx-list-actions {- position: absolute;- right: 4px;- display: flex;- gap: 2px;- opacity: 0;- pointer-events: none;-}-.rx-list-row:hover .rx-list-actions,-.rx-list-row:focus-within .rx-list-actions { opacity: 1; pointer-events: auto; }+/* The list's ⋯ waits until it is pointed at, over where its count sits — the same control+ Notes' and Contacts' rows have (.notes-folder-more). */+.rx-list-more { right: 8px; }+.rx-list-row:hover .rx-list-more, .rx-list-row:focus-within .rx-list-more { opacity: 1; }.rx-list-row:hover .rx-list-count,.rx-list-row:focus-within .rx-list-count { visibility: hidden; }+.rx-list-row.is-menu .rx-list-more { opacity: 1; }+.rx-list-row.is-menu .rx-list-count { visibility: hidden; }.rx-rename {flex: 1;