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
Reminders and Calendar speed pass
Yashwanth Kamireddi3c89b43ba725
diff --git a/.uiverify/calendar-optimistic.mjs b/.uiverify/calendar-optimistic.mjsnew file mode 100644index 0000000..981a8c2--- /dev/null+++ b/.uiverify/calendar-optimistic.mjs@@ -0,0 +1,101 @@+// Delete and Ctrl+D change the grid at once, while the event's alerts and repeat are still on+// their way from Apple — held here for 2 s, as a slow network holds them. Undo and the copy+// still carry the alerts once they come. And no button or picker says "…".+import { engine, engineName } from "./engine.mjs";+import { SERVICES, installStub, openScreen } from "./stub.mjs";++const BASE = process.env.BASE ?? "http://localhost:4173";+const b = await engine.launch();+const ctx = await b.newContext({ viewport: { width: 1300, height: 850 } });+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, calendarFixture: true });+await ctx.addInitScript(() => {+ const wrap = () => {+ const t = window.__TAURI_INTERNALS__;+ if (!t || t.__slow) return;+ const inner = t.invoke;+ t.invoke = async (cmd, args) => {+ if (cmd === "event_alerts" || cmd === "event_repeat") await new Promise((r) => setTimeout(r, 2000));+ return inner(cmd, args);+ };+ t.__slow = true;+ };+ wrap(); document.addEventListener("DOMContentLoaded", wrap);+});+const page = await ctx.newPage();+page.on("pageerror", (e) => { console.log(`FAIL page error: ${e.message}`); failures++; });+let failures = 0;+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };+await page.goto(BASE, { waitUntil: "networkidle" });+await openScreen(page, "Calendar");+await page.keyboard.press("Control+2");+await page.waitForTimeout(400);+const saves = () => page.evaluate(() => window.__eventSaves ?? []);++// Ctrl+D on Dentist (whose alert, 15 minutes, the stub keeps at Apple): the copy is drawn at+// once, and made with the alert once it comes.+const dentist = page.locator(".cx-block", { hasText: "Dentist" });+await dentist.first().click();+await page.waitForTimeout(200);+await page.keyboard.press("Escape");+const before = await dentist.count();+// Watched frame by frame until the copy is made: never two of it (the stand-in and the copy).+// (The stub keeps no saved event, so the copy goes again on the read after; that is the stub.)+const watch = (text, until) => page.evaluate(([text, until]) => {+ window.__most = 0; window.__least = Infinity;+ const look = () => {+ if ((window[until] ?? []).length) return;+ const n = [...document.querySelectorAll(".cx-block")].filter((el) => el.textContent.includes(text)).length;+ window.__most = Math.max(window.__most, n); window.__least = Math.min(window.__least, n);+ requestAnimationFrame(look);+ };+ requestAnimationFrame(look);+}, [text, until]);+await watch("Dentist", "__eventSaves");+const t0 = Date.now();+await page.keyboard.press("Control+d");+await page.waitForFunction((n) => document.querySelectorAll(".cx-block").length > 0 &&+ [...document.querySelectorAll(".cx-block")].filter((el) => el.textContent.includes("Dentist")).length > n, before, { timeout: 1500 }).catch(() => {});+const drawn = Date.now() - t0;+ok((await dentist.count()) === before + 1 && drawn < 500, `${engineName}: Ctrl+D draws the copy at once (${drawn} ms), before its alerts come`);+ok((await saves()).length === 0, "the copy is not made before its alerts are known");+await page.waitForTimeout(2600);+const s = await saves();+ok(s.length === 1 && s[0].guid === null && JSON.stringify(s[0].alerts) === "[15]",+ `the copy is made with the event's alerts ${JSON.stringify(s[0]?.alerts)}`);+ok(await page.evaluate(() => window.__most) === before + 1, "one copy on the grid until it is made, never the stand-in and the copy both");++// Delete: gone from the grid at once; Undo makes it again with its alert.+const review = page.locator(".cx-block", { hasText: "Design review" });+await review.first().click();+await page.waitForTimeout(250);+await page.evaluate(() => document.activeElement?.blur());+await page.keyboard.press("Delete");+const t1 = Date.now();+await page.getByRole("alertdialog").getByRole("button", { name: "Delete" }).click();+await watch("Design review", "__eventDeletes");+await page.waitForFunction(() => ![...document.querySelectorAll(".cx-block")].some((el) => el.textContent.includes("Design review")), null, { timeout: 1500 }).catch(() => {});+const gone = Date.now() - t1;+ok((await review.count()) === 0 && gone < 500, `${engineName}: a deleted event leaves the grid at once (${gone} ms), before its alerts are read`);+const deletes = () => page.evaluate(() => (window.__eventDeletes ?? []).length);+await page.waitForTimeout(2300);+ok((await deletes()) === 1, "the deletion is queued once the alerts are in hand");+ok(await page.evaluate(() => window.__most) === 0, "and it stays off the grid while its alerts are read");+await page.getByRole("button", { name: "Undo" }).click();+await page.waitForTimeout(400);+const again = (await saves()).at(-1);+ok(again?.title === "Design review" && again?.guid === null, `Undo makes it again ${JSON.stringify(again?.title)}`);++// No label ends in "…": Subscribe says Subscribe; a loading picker says Loading.+const labels = await page.evaluate(() => [...document.querySelectorAll("button, [role=combobox], select, option")]+ .map((el) => (el.getAttribute("aria-label") ?? el.textContent ?? "").trim()).filter((t) => t.endsWith("…")));+ok(labels.length === 0, `no button or picker ends in "…" ${JSON.stringify(labels)}`);+// Opened while its alerts are still coming, an event's Alert picker says Loading, disabled.+await page.locator(".cx-block", { hasText: "Dentist" }).first().click();+await page.waitForTimeout(300);+const alert = page.getByRole("button", { name: "Alert", exact: true }).first();+const alertText = (await alert.textContent().catch(() => "")) ?? "";+ok(/Loading/.test(alertText) && !alertText.includes("…") && await alert.isDisabled(), `the Alert picker says Loading, disabled, while it loads [${alertText.trim()}]`);+await page.keyboard.press("Escape");++await b.close();+process.exitCode = failures ? 1 : 0;diff --git a/.uiverify/reminders-perf.mjs b/.uiverify/reminders-perf.mjsnew file mode 100644index 0000000..d0fce0c--- /dev/null+++ b/.uiverify/reminders-perf.mjs@@ -0,0 +1,144 @@+// What Reminders and Calendar ask the backend for, and how long a key takes, measured against+// the stub: a search keystroke, another service's outbox tick, a reminders tick's tag sweep,+// and a key typed into New Reminder with a thousand rows on screen. Prints the numbers; fails+// where the screen asks for more than it needs.+//+// BASE=http://localhost:4173 ENGINE=webkit node .uiverify/reminders-perf.mjs+import { engine, engineName } from "./engine.mjs";+import { SERVICES, installStub, openScreen } from "./stub.mjs";++const b = await engine.launch();+let failures = 0;+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };+const ctx = await b.newContext({ viewport: { width: 1280, height: 800 } });+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, remindersFixture: true, calendarFixture: true });+await ctx.addInitScript(() => {+ // Every command the window sends, counted by name.+ const wrap = () => {+ const t = window.__TAURI_INTERNALS__;+ if (!t || t.__counted) return;+ const inner = t.invoke;+ window.__calls = {};+ t.invoke = (cmd, args) => {+ window.__calls[cmd] = (window.__calls[cmd] ?? 0) + 1;+ return inner(cmd, args);+ };+ t.__counted = true;+ };+ wrap(); document.addEventListener("DOMContentLoaded", wrap);+ // A thousand rows, as a busy list holds them: one invented reminder each.+ const now = Math.floor(Date.now() / 1000);+ window.__extraReminders = Array.from({ length: 1000 }, (_, i) => ({+ guid: `bulk-${i}`, listGuid: "l1", title: `Errand number ${i + 1}`, notes: null,+ dueAt: now + (i + 1) * 3600, completedAt: null, priority: 0, flagged: false, parentGuid: null, etag: null,+ }));+});+const page = await ctx.newPage();+page.on("pageerror", (e) => { console.log(`FAIL page error: ${e.message}`); failures++; });+await page.goto(process.env.BASE ?? "http://localhost:4173", { waitUntil: "networkidle" });+// Calendar first, so it stays mounted behind Reminders as it does once visited.+await openScreen(page, "Calendar");+await page.waitForTimeout(500);+await openScreen(page, "Reminders");+await page.locator(".rx-list", { hasText: "Daily" }).first().click();+await page.waitForFunction(() => document.querySelectorAll(".rx-rows .rx-row").length >= 1000, null, { timeout: 15000 });+await page.waitForTimeout(500);++const reset = () => page.evaluate(() => { window.__calls = {}; });+const calls = () => page.evaluate(() => ({ ...window.__calls }));+const sum = (c, names) => names.reduce((n, k) => n + (c[k] ?? 0), 0);++// 1. Another service's change landing: neither Reminders nor Calendar reads anything again.+await reset();+await page.evaluate(() => window.__emit("quince://outbox-changed", { services: ["notes"] }));+await page.waitForTimeout(600);+let c = await calls();+const notesTick = sum(c, ["reminders_in", "reminder_marks", "reminder_tags", "reminders_tagged", "reminder_extras", "calendar_events", "calendar_list", "reminders_due_between"]);+console.log(`${engineName}: a Notes outbox tick → ${notesTick} Reminders/Calendar reads ${JSON.stringify(c)}`);+ok(notesTick === 0, "a Notes change landing reads nothing in Reminders or Calendar");++// 2. A reminders change landing: the tag and smart-list sweep is one call, not one per tag.+await reset();+await page.evaluate(() => window.__emit("quince://outbox-changed", { services: ["reminders"] }));+await page.waitForTimeout(600);+c = await calls();+const sweep = sum(c, ["reminders_tagged", "reminders_in_smart_list", "reminder_extras"]);+console.log(`${engineName}: a Reminders outbox tick → tag/smart sweep ${sweep} calls, reminders_in ${c.reminders_in ?? 0}, marks ${c.reminder_marks ?? 0}`);+ok(sweep <= 1, "the tags and smart-list counts are read in one call");+ok((c.reminders_in ?? 0) >= 1, "a reminders change landing still reads the list again");++// 3. Searching: one search per pause, not one per key, and no listeners torn down per key.+await reset();+const search = page.getByLabel("Search reminders").first();+await search.click();+for (const ch of "errand") {+ await page.keyboard.type(ch);+ await page.waitForTimeout(30);+}+await page.waitForTimeout(500);+c = await calls();+console.log(`${engineName}: typing "errand" → reminders_search ${c.reminders_search ?? 0}, marks ${c.reminder_marks ?? 0}, listen ${c["plugin:event|listen"] ?? 0}, unlisten ${c["plugin:event|unlisten"] ?? 0}`);+ok((c.reminders_search ?? 0) <= 2, "a word typed quickly is searched once or twice, not per key");+ok((c["plugin:event|listen"] ?? 0) === 0, "typing a search sets up no event listeners again");+ok(await page.locator(".rx-rows .rx-row").count() >= 1000, "the results are shown");+await search.fill("");+await page.waitForTimeout(400);++// 4. A key typed into New Reminder with 1,000 rows: time from the key to the screen settled.+const field = page.getByPlaceholder(/New Reminder/i).first();+await field.click();+const times = await page.evaluate(async () => {+ const input = document.querySelector(".rx-add input");+ const set = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value").set;+ const out = [];+ let text = "";+ for (const ch of "Buy oat milk") {+ text += ch;+ const t0 = performance.now();+ set.call(input, text);+ input.dispatchEvent(new Event("input", { bubbles: true }));+ await new Promise((r) => setTimeout(r, 0));+ out.push(performance.now() - t0);+ await new Promise((r) => setTimeout(r, 30));+ }+ return out;+});+const mean = times.reduce((a, x) => a + x, 0) / times.length;+console.log(`${engineName}: a key in New Reminder with 1,000 rows → mean ${mean.toFixed(1)} ms, worst ${Math.max(...times).toFixed(1)} ms`);+ok(mean < 16, "a key typed with 1,000 rows on screen settles within a frame");+await field.fill("");++// 5. Dragging over rows marks where it lands without drawing the list again.+const marked = await page.evaluate(async ([a, z]) => {+ const rowsNow = [...document.querySelectorAll(".rx-rows .rx-row")];+ const from = rowsNow[a], to = rowsNow[z];+ const dt = new DataTransfer();+ from.dispatchEvent(new DragEvent("dragstart", { bubbles: true, dataTransfer: dt }));+ await new Promise((r) => setTimeout(r, 50));+ to.dispatchEvent(new DragEvent("dragover", { bubbles: true, cancelable: true, dataTransfer: dt }));+ await new Promise((r) => setTimeout(r, 50));+ const on = to.classList.contains("is-drop-before");+ const only = document.querySelectorAll(".rx-row.is-drop-before").length;+ rowsNow[z + 1].dispatchEvent(new DragEvent("dragover", { bubbles: true, cancelable: true, dataTransfer: dt }));+ await new Promise((r) => setTimeout(r, 50));+ const moved = rowsNow[z + 1].classList.contains("is-drop-before") && !to.classList.contains("is-drop-before");+ from.dispatchEvent(new DragEvent("dragend", { bubbles: true, dataTransfer: dt }));+ await new Promise((r) => setTimeout(r, 50));+ const cleared = document.querySelectorAll(".rx-row.is-drop-before").length === 0;+ return { on, only, moved, cleared };+}, [2, 5]);+ok(marked.on && marked.only === 1, "dragging over a row marks it as where the reminder lands");+ok(marked.moved, "the mark follows the pointer to the next row");+ok(marked.cleared, "the mark goes when the drag ends");++// 6. Urgent read from Apple after the marks came back: merged into its row as it arrives.+const urgentRow = page.locator('.rx-row[data-guid="bulk-0"]');+await urgentRow.scrollIntoViewIfNeeded();+ok((await urgentRow.locator(".rx-urgent").count()) === 0, "a row shows no Urgent before it is known");+await page.evaluate(() => window.__emit("quince://reminder-urgent", [{ guid: "bulk-0", urgent: true }, { guid: "bulk-1", urgent: false }]));+await page.waitForTimeout(200);+ok((await urgentRow.locator(".rx-urgent").count()) === 1, "Urgent read later shows on its row");+ok((await page.locator('.rx-row[data-guid="bulk-1"] .rx-urgent').count()) === 0, "a row read as not Urgent stays without it");++await b.close();+process.exitCode = failures ? 1 : 0;diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjsindex 1c5107a..8b3c9d8 100644--- a/.uiverify/stub.mjs+++ b/.uiverify/stub.mjs@@ -330,7 +330,7 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note// Reminders' details (reminders_cmds.rs): tags, a link, early alerts, custom smart lists// and sections. A test sets __tagMap / __details / __smartLists / __sections to change them.case "reminder_sections": return (window.__sections ?? []).filter((s) => s.listGuid === args.listGuid);- case "reminder_tags": case "reminders_tagged": case "reminder_detail": {+ case "reminder_tags": case "reminders_tagged": case "reminder_detail": case "reminder_extras": {const tagMap = (window.__tagMap ??= !remindersFixture || remindersFixture === "lists" ? {} : { r1: ["home"], r2: ["errands", "home"], r3: ["fitness"] });const every = [...reminderItems, ...(window.__extraReminders ?? [])];if (cmd === "reminder_detail") {@@ -340,6 +340,14 @@ export function installStub({ screen, services, twoFactor, calendarFixture, noteconst open = (name) => every.filter((r) => !r.completedAt && (tagMap[r.guid] ?? []).some((t) => t.toLowerCase() === name.toLowerCase()));if (cmd === "reminders_tagged") return open(args.name);const names = [...new Set(Object.values(tagMap).flat())].sort((a, b) => a.localeCompare(b));+ // One read for the rows' tags and the custom smart lists' counts (reminder_extras).+ if (cmd === "reminder_extras") {+ const tagsByReminder = {};+ for (const name of names) for (const r of open(name)) (tagsByReminder[r.guid] ??= []).push(name);+ const lists = window.__smartLists ?? (!remindersFixture || remindersFixture === "lists" ? [] : [{ guid: "SL-1", kind: "custom" }]);+ const held = every.filter((r) => !r.completedAt && r.flagged).length;+ return { tagsByReminder, customCounts: Object.fromEntries(lists.filter((x) => x.kind === "custom").map((x) => [x.guid, held])) };+ }return names.map((name) => ({ name, open: open(name).length }));}case "reminder_smart_lists": return window.__smartLists ?? (!remindersFixture || remindersFixture === "lists" ? [] : [diff --git a/crates/quince-core/src/contacts.rs b/crates/quince-core/src/contacts.rsindex 394c8c5..c41d3c8 100644--- a/crates/quince-core/src/contacts.rs+++ b/crates/quince-core/src/contacts.rs@@ -745,6 +745,47 @@ impl Library {Ok(self.cards(search)?.into_iter().map(|c| c.contact).collect())}+ /// Everyone with a birthday, in the order [`Library::contacts`] gives them, with only their+ /// names and birthday filled in: what the Birthdays calendar draws. Calendar built every card+ /// whole for this — each method, detail and address — on every read of a month.+ pub fn contacts_with_birthdays(&self) -> Result<Vec<Contact>> {+ let mut stmt = self.conn.prepare(+ "SELECT guid, first_name, middle_name, last_name, company, is_company, birthday+ FROM contacts WHERE birthday IS NOT NULL",+ )?;+ let rows = stmt.query_map([], |row| {+ Ok(Contact {+ guid: row.get(0)?,+ first_name: row.get(1)?,+ middle_name: row.get(2)?,+ photo_url: None,+ photo_signature: None,+ photo_crop: None,+ last_name: row.get(3)?,+ company: row.get(4)?,+ is_company: row.get::<_, i64>(5)? != 0,+ birthday: row.get(6)?,+ notes: None,+ etag: None,+ methods: Vec::new(),+ })+ })?;+ let mut keyed: Vec<(String, Contact)> = rows+ .map(|c| c.map(|c| (c.sort_key(), c)))+ .collect::<rusqlite::Result<_>>()?;+ keyed.sort_by(|(a, _), (b, _)| crate::fold::natural(a, b));+ Ok(keyed.into_iter().map(|(_, c)| c).collect())+ }++ /// Whether anyone in the address book has a birthday: whether there is a Birthdays calendar.+ pub fn any_birthday(&self) -> Result<bool> {+ Ok(self.conn.query_row(+ "SELECT EXISTS (SELECT 1 FROM contacts WHERE birthday IS NOT NULL)",+ [],+ |r| r.get::<_, i64>(0),+ )? != 0)+ }+/// [`Library::contacts`], each card whole: with the rest of its name and work, which a/// search matches too — a nickname or a job title finds the person.pub fn cards(&self, search: Option<&str>) -> Result<Vec<Card>> {@@ -926,6 +967,41 @@ mod tests {}}+ /// Calendar's read: the people with a birthday, in the address book's order, with what+ /// a birthday's title is made from — and whether there are any at all.+ #[test]+ fn birthdays_are_read_without_building_every_card() {+ let mut lib = Library::in_memory().unwrap();+ assert!(!lib.any_birthday().unwrap());+ let mut alex = contact("1", Some("Alex"), Some("Rivera"));+ alex.birthday = Some("1990-04-12".into());+ let mut bea = contact("2", Some("Bea"), Some("Moreno"));+ bea.birthday = Some("1604-09-30".into());+ lib.put_contacts(&[alex, contact("3", Some("Cy"), Some("Lane")), bea])+ .unwrap();+ assert!(lib.any_birthday().unwrap());+ let born = lib.contacts_with_birthdays().unwrap();+ let whole: Vec<Contact> = lib+ .contacts(None)+ .unwrap()+ .into_iter()+ .filter(|c| c.birthday.is_some())+ .collect();+ let names = |cs: &[Contact]| -> Vec<String> {+ cs.iter()+ .map(|c| {+ format!(+ "{} {:?} {:?} {:?}",+ c.guid, c.first_name, c.last_name, c.birthday+ )+ })+ .collect()+ };+ assert_eq!(names(&born), names(&whole));+ assert_eq!(born.len(), 2);+ assert!(born.iter().all(|c| c.methods.is_empty()), "names only");+ }+#[test]fn search_ignores_case_accents_and_word_order() {let mut lib = Library::in_memory().unwrap();diff --git a/crates/quince-core/src/reminders.rs b/crates/quince-core/src/reminders.rsindex 23a06c2..3ae9b53 100644--- a/crates/quince-core/src/reminders.rs+++ b/crates/quince-core/src/reminders.rs@@ -2690,6 +2690,15 @@ fn date_holds(d: &DateFilter, r: &Reminder, now: i64) -> bool {}}+/// What the Reminders sidebar and rows show beside the lists: each reminder still to do with its+/// tags, and how many reminders each custom smart list holds, by the list's id.+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+pub struct ReminderExtras {+ pub tags_by_reminder: std::collections::HashMap<String, Vec<String>>,+ pub custom_counts: std::collections::HashMap<String, usize>,+}+/// What a custom smart list holds now, and which parts of its filter could not be read.#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]#[serde(rename_all = "camelCase")]@@ -3028,6 +3037,74 @@ impl Library {.collect())}+ /// Each reminder still to do with its tags, named as [`Library::reminder_tags`] names them+ /// and in that order, and how many reminders each custom smart list holds now — what the+ /// Reminders sidebar and rows show beside the lists, read in one go. The window used to ask+ /// for every tag's reminders whole, and every smart list's, only to build this.+ pub fn reminder_extras(&self, now: i64) -> Result<ReminderExtras> {+ // Tags as the sidebar lists them: one name per tag however it is capitalised.+ let tags = self.reminder_tags()?;+ let order: std::collections::HashMap<String, (usize, &str)> = tags+ .iter()+ .enumerate()+ .map(|(i, t)| (tag_key(&t.name), (i, t.name.as_str())))+ .collect();+ let mut stmt = self.conn.prepare(+ "SELECT h.reminder_guid, h.name FROM reminder_hashtags h+ JOIN reminders r ON r.guid = h.reminder_guid+ JOIN reminder_lists l ON l.guid = r.list_guid+ WHERE l.enabled = 1 AND r.completed_at IS NULL",+ )?;+ let mut placed: std::collections::HashMap<String, Vec<(usize, &str)>> =+ std::collections::HashMap::new();+ for row in stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))? {+ let (reminder, name) = row?;+ if let Some(&at) = order.get(&tag_key(&name)) {+ placed.entry(reminder).or_default().push(at);+ }+ }+ let tags_by_reminder = placed+ .into_iter()+ .map(|(reminder, mut names)| {+ names.sort_unstable();+ names.dedup();+ (+ reminder,+ names.into_iter().map(|(_, n)| n.to_string()).collect(),+ )+ })+ .collect();++ // Every custom list's rules over one read of what is still to do, rather than one+ // read of every open reminder per list.+ let custom: Vec<(String, Option<String>)> = self+ .reminder_smart_lists()?+ .into_iter()+ .filter(|s| s.kind == "custom")+ .map(|s| (s.guid, s.filter))+ .collect();+ let mut custom_counts = std::collections::HashMap::new();+ if !custom.is_empty() {+ let tagged = self.all_tags_by_reminder()?;+ let open = self.open_reminders()?;+ let none: Vec<String> = Vec::new();+ for (guid, filter) in custom {+ let count = filter.map_or(0, |filter| {+ let filter = SmartFilter::decode(&filter);+ open.iter()+ .filter(|r| filter.holds(r, tagged.get(&r.guid).unwrap_or(&none), now))+ .take(MOST_AT_ONCE)+ .count()+ });+ custom_counts.insert(guid, count);+ }+ }+ Ok(ReminderExtras {+ tags_by_reminder,+ custom_counts,+ })+ }+/// The account id Apple writes inside early alerts, from any reminder that has one: a new/// alert is written with the same.pub fn early_alert_account(&self) -> Result<Option<String>> {@@ -3211,6 +3288,35 @@ mod detail_tests {);}+ /// The sidebar's sweep in one read: the same tags per reminder and the same smart-list+ /// counts as asking for each tag's and each list's reminders one at a time.+ #[test]+ fn extras_match_the_tag_and_smart_list_reads() {+ let lib = library();+ let extras = lib.reminder_extras(0).unwrap();+ let tags = lib.reminder_tags().unwrap();+ let mut one_by_one: std::collections::HashMap<String, Vec<String>> = Default::default();+ for t in &tags {+ for r in lib.reminders_tagged(&t.name).unwrap() {+ one_by_one.entry(r.guid).or_default().push(t.name.clone());+ }+ }+ assert_eq!(extras.tags_by_reminder, one_by_one);+ assert!(+ !extras.tags_by_reminder.contains_key("Reminder/3"),+ "done ones carry no chips"+ );+ assert_eq!(+ extras.custom_counts.get("SmartList/S").copied(),+ Some(+ lib.reminders_in_smart_list("SmartList/S", 0)+ .unwrap()+ .reminders+ .len()+ )+ );+ }+/// An incremental pass lays itself over what is stored; a gone record goes; a reminder/// that comes back without its alert loses it.#[test]diff --git a/crates/quince-icloud/src/reminders.rs b/crates/quince-icloud/src/reminders.rsindex 39fe2f4..00a8817 100644--- a/crates/quince-icloud/src/reminders.rs+++ b/crates/quince-icloud/src/reminders.rs@@ -3982,6 +3982,53 @@ mod tombstone_tests {);}+ /// The re-read after a section write is a delta (main.rs `resync_reminders`), so the delta+ /// must carry what a list change moves: the new section and the list's placements from its+ /// membership file land, and nothing the walk left out is touched.+ #[test]+ fn an_incremental_pass_places_reminders_in_a_new_section() {+ let mut library = library_with("Reminder/1");+ library+ .put_reminders(&[Reminder {+ guid: "Reminder/2".into(),+ list_guid: "List/a".into(),+ title: "Untouched by the walk".into(),+ ..library.reminder("Reminder/1").unwrap().unwrap()+ }])+ .unwrap();+ let mut memberships = std::collections::HashMap::new();+ memberships.insert(+ "List/a".to_string(),+ vec![("Reminder/1".to_string(), "ListSection/s".to_string())],+ );+ apply_cloudkit(+ &mut library,+ RemindersFetch {+ memberships,+ records: vec![json!({+ "recordName": "ListSection/s",+ "recordType": "ListSection",+ "fields": {+ "List": { "value": { "recordName": "List/a" } },+ "DisplayName": { "type": "STRING", "value": "Groceries" }+ }+ })],+ token: Some("t2".into()),+ incremental: true,+ },+ )+ .unwrap();+ let sections = library.reminder_sections("List/a").unwrap();+ assert_eq!(sections.len(), 1);+ assert_eq!(sections[0].title, "Groceries");+ let placed = library.reminder("Reminder/1").unwrap().unwrap();+ assert_eq!(placed.section_guid.as_deref(), Some("ListSection/s"));+ let other = library.reminder("Reminder/2").unwrap().unwrap();+ assert_eq!(other.title, "Untouched by the walk");+ assert_eq!(other.section_guid, None);+ assert_eq!(library.reminders_in("List/a", true).unwrap().len(), 2);+ }+/// A name that matches nothing must not disturb what is there.#[test]fn a_tombstone_for_something_we_never_had_is_harmless() {diff --git a/crates/quince-icloud/src/reminders_more.rs b/crates/quince-icloud/src/reminders_more.rsindex eb6aad4..069e46f 100644--- a/crates/quince-icloud/src/reminders_more.rs+++ b/crates/quince-icloud/src/reminders_more.rs@@ -293,8 +293,67 @@ pub async fn urgent_cloudkit(Ok(urgent)}+/// Urgent files that could not be read lately, by checksum (or the reminder's name, for a record+/// without one), and when. A failure was never kept: offline, or with Apple out of reach, every+/// read of a list asked for the same forty files again and waited out each one's timeout.+static URGENT_FAILED: std::sync::Mutex<+ Option<std::collections::HashMap<String, std::time::Instant>>,+> = std::sync::Mutex::new(None);++/// How long a file that could not be read is left alone before it is asked for again.+pub const URGENT_RETRY: std::time::Duration = std::time::Duration::from_secs(10 * 60);++fn urgent_key(record: &Value, guid: &str) -> String {+ urgent_checksum(record).unwrap_or_else(|| guid.to_string())+}++/// Whether `key` failed within `retry` of `now`.+fn failed_within(+ failed: &std::collections::HashMap<String, std::time::Instant>,+ key: &str,+ now: std::time::Instant,+ retry: std::time::Duration,+) -> bool {+ failed+ .get(key)+ .is_some_and(|at| now.saturating_duration_since(*at) < retry)+}++fn note_urgent_failed(key: String, at: std::time::Instant) {+ if let Ok(mut failed) = URGENT_FAILED.lock() {+ let failed = failed.get_or_insert_with(Default::default);+ // Old failures go as new ones come, so the map never outgrows one list's worth.+ failed.retain(|_, when| at.saturating_duration_since(*when) < URGENT_RETRY);+ failed.insert(key, at);+ }+}++fn forget_urgent_failed(key: &str) {+ if let Ok(mut failed) = URGENT_FAILED.lock() {+ if let Some(failed) = failed.as_mut() {+ failed.remove(key);+ }+ }+}++/// Whether this reminder's Urgent file could not be read within the last [`URGENT_RETRY`]:+/// it is not asked for again until then, and its row shows Urgent off, as it does while unknown.+#[must_use]+pub fn urgent_failed_lately(guid: &str, raw: &str) -> bool {+ let Ok(record) = serde_json::from_str::<Value>(raw) else {+ return false;+ };+ let key = urgent_key(&record, guid);+ URGENT_FAILED.lock().is_ok_and(|failed| {+ failed.as_ref().is_some_and(|failed| {+ failed_within(failed, &key, std::time::Instant::now(), URGENT_RETRY)+ })+ })+}+/// Whether a reminder is Urgent, read from Apple: the file's link from the record as synced/// first (good for about an hour), and only if that has lapsed, a fresh lookup. Read only.+/// A file that cannot be read is not asked for again for [`URGENT_RETRY`].pub async fn urgent_for(http: &reqwest::Client,ckdatabasews_root: &str,@@ -303,6 +362,22 @@ pub async fn urgent_for(raw: &str,) -> Option<bool> {let record: Value = serde_json::from_str(raw).ok()?;+ let key = urgent_key(&record, guid);+ let urgent = urgent_read(http, ckdatabasews_root, params, guid, &record).await;+ match urgent {+ Some(_) => forget_urgent_failed(&key),+ None => note_urgent_failed(key, std::time::Instant::now()),+ }+ urgent+}++async fn urgent_read(+ http: &reqwest::Client,+ ckdatabasews_root: &str,+ params: Vec<(String, String)>,+ guid: &str,+ record: &Value,+) -> Option<bool> {let url = record.pointer("/fields/UrgentPresentationAlarmsAsData/value/downloadURL").and_then(Value::as_str)?;@@ -310,7 +385,7 @@ pub async fn urgent_for(if response.status().is_success() {if let Ok(bytes) = response.bytes().await {let urgent = urgent_from_file(&bytes);- if let (Some(on), Some(sum)) = (urgent, urgent_checksum(&record)) {+ if let (Some(on), Some(sum)) = (urgent, urgent_checksum(record)) {if let Ok(mut seen) = URGENT_SEEN.lock() {seen.get_or_insert_with(Default::default).insert(sum, on);}@@ -328,6 +403,44 @@ pub async fn urgent_for(#[cfg(test)]mod tests {use super::*;++ /// A file that could not be read is left alone for a while, then asked for again.+ #[test]+ fn a_failed_urgent_read_waits_before_it_is_tried_again() {+ let now = std::time::Instant::now();+ let mut failed = std::collections::HashMap::new();+ assert!(!failed_within(&failed, "sum", now, URGENT_RETRY));+ failed.insert("sum".to_string(), now);+ assert!(failed_within(&failed, "sum", now, URGENT_RETRY));+ assert!(failed_within(+ &failed,+ "sum",+ now + URGENT_RETRY / 2,+ URGENT_RETRY+ ));+ assert!(!failed_within(+ &failed,+ "sum",+ now + URGENT_RETRY,+ URGENT_RETRY+ ));+ assert!(!failed_within(&failed, "other", now, URGENT_RETRY));+ }++ /// Kept by the file's checksum, so a changed file (a new checksum) is read at once.+ #[test]+ fn a_failure_is_kept_by_checksum_and_forgotten_on_success() {+ let raw = r#"{"recordName":"Reminder/F1","fields":{+ "UrgentPresentationAlarmsChecksum":{"value":"sum-failed-test"},+ "UrgentPresentationAlarmsAsData":{"value":{}}}}"#;+ let changed = raw.replace("sum-failed-test", "sum-failed-test-2");+ assert!(!urgent_failed_lately("Reminder/F1", raw));+ note_urgent_failed("sum-failed-test".into(), std::time::Instant::now());+ assert!(urgent_failed_lately("Reminder/F1", raw));+ assert!(!urgent_failed_lately("Reminder/F1", &changed));+ forget_urgent_failed("sum-failed-test");+ assert!(!urgent_failed_lately("Reminder/F1", raw));+ }use serde_json::json;/// The founder's "Skykeep Test" as the phone wrote it, personal text replaced.diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex f7a67ff..2449bb2 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -123,15 +123,18 @@ type UiResult<T> = Result<T, String>;/// any network work so a slow sync cannot block the heartbeat or a sign-out./// Re-read reminders after a write, so what is on screen is what Apple stored.///-/// A list change moves records other than the one written, so this is a full pass rather-/// than a delta.+/// A delta from the stored sync token: a list change moves records other than the one written,+/// and the walk since the token brings those back too, with each changed list's sections. A+/// whole-zone pass here walked years of completed reminders and every list's membership file+/// after each tag, link, reorder or repeat, and the reminder's next edit queued behind it. A+/// token Apple refused starts the walk over from the beginning on its own.async fn resync_reminders(http: &reqwest::Client,root: &str,params: Vec<(String, String)>,data: &State<'_, Data>,) -> Result<(), String> {- refresh_reminders(http, root, params, data, true).await+ refresh_reminders(http, root, params, data, false).await}/// Ask Apple what changed in Reminders and store it — without holding the library while@@ -1844,7 +1847,11 @@ async fn calendar_events(library.events_between(from, to).map_err(|e| e.to_string())?,- library.contacts(None).map_err(|e| e.to_string())?,+ // Only who has a birthday, and their names: every card built whole was most of+ // the cost of reading a month.+ library+ .contacts_with_birthdays()+ .map_err(|e| e.to_string())?,)};// Birthdays and holidays, as a phone draws them: neither is an iCloud calendar.@@ -1877,7 +1884,9 @@ async fn calendar_search(let library = data.0.lock().await;(library.search_events(&query).map_err(|e| e.to_string())?,- library.contacts(None).map_err(|e| e.to_string())?,+ library+ .contacts_with_birthdays()+ .map_err(|e| e.to_string())?,)};if !words.is_empty() {@@ -2325,16 +2334,19 @@ async fn calendar_list(occasions: State<'_, Occasions>,feeds_state: State<'_, Feeds>,) -> UiResult<Vec<Calendar>> {- let library = data.0.lock().await;- let mut calendars = library.calendars().map_err(|e| e.to_string())?;- let any_birthdays = library- .contacts(None)- .map_err(|e| e.to_string())?- .iter()- .any(|c| c.birthday.is_some());- let feed = occasions.feed.lock().await;- let holidays =- (!feed.1.is_empty()).then(|| feed.0.clone().unwrap_or_else(|| "Holidays".into()));+ // The library is let go before the holiday feed and subscriptions are waited for: held+ // across them, every other screen's read queued behind those locks too.+ let (mut calendars, any_birthdays) = {+ let library = data.0.lock().await;+ (+ library.calendars().map_err(|e| e.to_string())?,+ library.any_birthday().map_err(|e| e.to_string())?,+ )+ };+ let holidays = {+ let feed = occasions.feed.lock().await;+ (!feed.1.is_empty()).then(|| feed.0.clone().unwrap_or_else(|| "Holidays".into()))+ };calendars.extend(quince_icloud::occasions::calendars(holidays.as_deref(),any_birthdays,@@ -5872,6 +5884,7 @@ fn main() {reminders_cmds::reminder_more,reminders_cmds::reminders_ending,reminders_cmds::reminder_marks,+ reminders_cmds::reminder_extras,reminders_cmds::reminder_tags,reminders_cmds::reminders_tagged,reminders_cmds::reminder_smart_lists,diff --git a/src-tauri/src/outbox.rs b/src-tauri/src/outbox.rsindex 1763f6d..1431d2a 100644--- a/src-tauri/src/outbox.rs+++ b/src-tauri/src/outbox.rs@@ -37,13 +37,9 @@ use tauri::{AppHandle, Emitter, Manager, State};use tokio::sync::{Mutex, Notify};static WAKE: Notify = Notify::const_new();-/// Set by every [`kick`] until the sender's next pass: a pass after one is never taken as idle,-/// so a change queued and sent between two looks is still announced as it lands.-static KICKED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);/// Something was queued: send it now.pub fn kick() {- KICKED.store(true, std::sync::atomic::Ordering::SeqCst);WAKE.notify_one();}@@ -1095,24 +1091,20 @@ pub fn start(app: AppHandle) {() = WAKE.notified() => {}() = tokio::time::sleep(wait) => {}}- // Nothing waiting is nothing to say. Told every thirty seconds regardless, each open- // Notes, Reminders and Contacts read its whole list (and the open note or card)- // again, twice, and drew it again — all day, with nothing changed.- let kicked = KICKED.swap(false, std::sync::atomic::Ordering::SeqCst);- let idle = !kicked && nothing_waiting(&app).await;- if !idle {- let _ = app.emit(CHANGED, ());- }let outcomes = [- drain_reminders(&app).await,- drain_notes(&app).await,- drain_contacts(&app).await,- drain_calendar(&app).await,+ (REMINDERS, drain_reminders(&app).await),+ (NOTES, drain_notes(&app).await),+ (CONTACTS, drain_contacts(&app).await),+ (CALENDAR, drain_calendar(&app).await),];- if !idle {- let _ = app.emit(CHANGED, ());+ // Said once, after the pass, and only to the services it touched. Told before and+ // after every pass with no service named, each kept-mounted screen read its whole+ // list again twice whatever had moved: a Notes save re-read Reminders and Calendar.+ // Nothing waiting is nothing to say, so an idle pass every thirty seconds is quiet.+ if let Some(changed) = changed(&outcomes) {+ let _ = app.emit(CHANGED, changed);}- wait = if outcomes.iter().any(|o| matches!(o, Outcome::Later)) {+ wait = if outcomes.iter().any(|(_, o)| matches!(o, Outcome::Later)) {// Apple out of reach: wait longer each time, up to two minutes.(wait * 2).clamp(Duration::from_secs(4), Duration::from_secs(120))} else {@@ -1125,7 +1117,28 @@ pub fn start(app: AppHandle) {/// Told to the window whenever what waits may have changed.pub const CHANGED: &str = "quince://outbox-changed";+/// What [`CHANGED`] carries after a pass: the services it sent for, or found waiting. A screen+/// reads its rows again only when its own service is named.+#[derive(Clone, Debug, PartialEq, Eq, Serialize)]+pub struct Changed {+ pub services: Vec<&'static str>,+}++/// What a pass over every service comes to for the window: the services that had anything+/// waiting, or `None` when none did — nothing was sent, so nothing on screen moved.+fn changed(outcomes: &[(&'static str, Outcome)]) -> Option<Changed> {+ let services: Vec<&'static str> = outcomes+ .iter()+ .filter(|(_, o)| !matches!(o, Outcome::Idle))+ .map(|(service, _)| *service)+ .collect();+ (!services.is_empty()).then_some(Changed { services })+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]enum Outcome {+ /// Nothing was waiting: the pass sent nothing and changed nothing.+ Idle,Clear,Later,}@@ -1229,14 +1242,6 @@ fn tell_refused(app: &AppHandle, service: &'static str, report: &Report) {}/// Whether anything waits for `service` — the answer when Apple can't be asked yet.-/// No change waiting for any service (refused ones are not sent, so they do not count): a pass-/// would send nothing and change nothing anyone is shown.-async fn nothing_waiting(app: &AppHandle) -> bool {- let data = app.state::<Data>();- let library = data.0.lock().await;- library.outbox_all_pending().is_ok_and(|p| p.is_empty())-}-async fn waiting(data: &Data, service: &str) -> Outcome {if data.0@@ -1256,7 +1261,7 @@ async fn drain_reminders(app: &AppHandle) -> Outcome {let auth = app.state::<Auth>();let data = app.state::<Data>();if waiting(&data, REMINDERS).await.is_clear() {- return Outcome::Clear;+ return Outcome::Idle;}let session = if crate::same_account(app).await {cloudkit_context(&auth).await@@ -1423,7 +1428,7 @@ async fn drain_notes(app: &AppHandle) -> Outcome {let auth = app.state::<Auth>();let data = app.state::<Data>();if waiting(&data, NOTES).await.is_clear() {- return Outcome::Clear;+ return Outcome::Idle;}let session = if crate::same_account(app).await {cloudkit_context(&auth).await@@ -1562,7 +1567,7 @@ async fn drain_contacts(app: &AppHandle) -> Outcome {let auth = app.state::<Auth>();let data = app.state::<Data>();if waiting(&data, CONTACTS).await.is_clear() {- return Outcome::Clear;+ return Outcome::Idle;}let session = if crate::same_account(app).await {crate::contacts_context(&auth).await@@ -1675,7 +1680,7 @@ async fn drain_calendar(app: &AppHandle) -> Outcome {let auth = app.state::<Auth>();let data = app.state::<Data>();if waiting(&data, CALENDAR).await.is_clear() {- return Outcome::Clear;+ return Outcome::Idle;}let session = if crate::same_account(app).await {crate::calendar_context(&auth).await@@ -2026,6 +2031,40 @@ pub async fn outbox_discard(id: i64, app: AppHandle, data: State<'_, Data>) -> R#[cfg(test)]mod tests {use super::*;++ /// A pass names only the services it sent for or found waiting, once; an idle pass says+ /// nothing at all.+ #[test]+ fn a_pass_tells_only_the_services_it_touched() {+ assert_eq!(+ changed(&[+ (REMINDERS, Outcome::Idle),+ (NOTES, Outcome::Clear),+ (CONTACTS, Outcome::Idle),+ (CALENDAR, Outcome::Later),+ ]),+ Some(Changed {+ services: vec![NOTES, CALENDAR]+ })+ );+ assert_eq!(+ changed(&[+ (REMINDERS, Outcome::Idle),+ (NOTES, Outcome::Idle),+ (CONTACTS, Outcome::Idle),+ (CALENDAR, Outcome::Idle),+ ]),+ None+ );+ // The window reads it as `{ services: [...] }`.+ assert_eq!(+ serde_json::to_string(&Changed {+ services: vec![REMINDERS]+ })+ .unwrap(),+ r#"{"services":["reminders"]}"#+ );+ }use quince_core::reminders::ReminderList;use std::sync::{Arc, Mutex as StdMutex};diff --git a/src-tauri/src/reminders_cmds.rs b/src-tauri/src/reminders_cmds.rsindex 2807328..afd1957 100644--- a/src-tauri/src/reminders_cmds.rs+++ b/src-tauri/src/reminders_cmds.rs@@ -4,8 +4,8 @@use crate::{Auth, Data, UiResult};use quince_core::reminders::{- Reminder, ReminderDetail, ReminderMarks, ReminderMore, ReminderSection, ReminderSmartList,- SmartListContents, TagCount,+ Reminder, ReminderDetail, ReminderExtras, ReminderMarks, ReminderMore, ReminderSection,+ ReminderSmartList, SmartListContents, TagCount,};use quince_icloud::reminders::{details, more};use tauri::State;@@ -85,20 +85,61 @@ pub async fn reminders_ending(data: State<'_, Data>) -> UiResult<Vec<String>> {Ok(out)}+/// Told to the window as Urgent is read from Apple for rows the library could not say: each+/// reminder's id and whether it is Urgent.+pub const URGENT_READ: &str = "quince://reminder-urgent";++/// One row's Urgent, read from Apple after its marks were answered.+#[derive(Clone, serde::Serialize)]+pub struct UrgentRead {+ guid: String,+ urgent: bool,+}++/// Reminders whose Urgent file is being read now: a second read of the list while the first is+/// still at Apple does not ask for the same files again.+static URGENT_ASKING: std::sync::Mutex<Option<std::collections::HashSet<String>>> =+ std::sync::Mutex::new(None);++/// Of `unread`, those not being read already, now taken as being read.+fn take_unasked(unread: Vec<(String, String)>) -> Vec<(String, String)> {+ let Ok(mut asking) = URGENT_ASKING.lock() else {+ return Vec::new();+ };+ let asking = asking.get_or_insert_with(Default::default);+ unread+ .into_iter()+ .filter(|(guid, _)| asking.insert(guid.clone()))+ .collect()+}++fn done_asking(guids: &[String]) {+ if let Ok(mut asking) = URGENT_ASKING.lock() {+ if let Some(asking) = asking.as_mut() {+ for guid in guids {+ asking.remove(guid);+ }+ }+ }+}+/// What each of these reminders' rows shows beside its date, as the phone's list does:/// Weekdays or Weekends, the Urgent alarm, a place, a person, a link. Only rows with any of-/// them come back. Urgent is read from Apple for rows not read yet — a few at a time, read-/// only — and is shown off until it is known.+/// them come back, from the library, at once. Urgent is shown off until it is known: for rows+/// not read yet it is read from Apple behind the answer — a few at a time, read only — and+/// told to the window as [`URGENT_READ`]. Waiting for those files held the whole answer, so a+/// list's place, person and link chips came seconds after its rows, and every row with one+/// grew by a line as they did; offline, each read waited out the timeouts.#[tauri::command]pub async fn reminder_marks(guids: Vec<String>,- auth: State<'_, Auth>,+ app: tauri::AppHandle,data: State<'_, Data>,) -> UiResult<Vec<ReminderMarks>> {- /// Urgent files read in one call at most; the rest are read on the next.+ /// Urgent files read for one call at most; the rest are read on the next.const MOST_UNREAD: usize = 40;let mut out = Vec::new();- let mut unread: Vec<(usize, String, String)> = Vec::new();+ let mut unread: Vec<(String, String)> = Vec::new();{let library = data.0.lock().await;for guid in guids.iter().take(2_000) {@@ -117,42 +158,27 @@ pub async fn reminder_marks(.map_err(|e| e.to_string())?.url;let urgent = more::urgent_known(raw.as_deref());- let marks = ReminderMarks {+ out.push(ReminderMarks {guid: guid.clone(),days_of_week: found.repeat.map(|r| r.days_of_week).unwrap_or_default(),urgent: urgent.unwrap_or(false),location: found.location,messaging,url,- };+ });if urgent.is_none() && unread.len() < MOST_UNREAD {if let Some(raw) = raw {- unread.push((out.len(), guid.clone(), raw));+ // One that failed lately is left until it is worth asking again.+ if !more::urgent_failed_lately(guid, &raw) {+ unread.push((guid.clone(), raw));+ }}}- out.push(marks);}}+ let unread = take_unasked(unread);if !unread.is_empty() {- if let Ok((http, root, params)) = crate::cloudkit_context(&auth).await {- use futures_util::StreamExt;- let read: Vec<(usize, Option<bool>)> = futures_util::stream::iter(unread)- .map(|(at, guid, raw)| {- let (http, root, params) = (http.clone(), root.clone(), params.clone());- async move {- (- at,- more::urgent_for(&http, &root, params, &guid, &raw).await,- )- }- })- .buffer_unordered(6)- .collect()- .await;- for (at, urgent) in read {- out[at].urgent = urgent.unwrap_or(false);- }- }+ tauri::async_runtime::spawn(read_urgent(app, unread));}out.retain(|m| {m.urgent@@ -164,6 +190,32 @@ pub async fn reminder_marks(Ok(out)}+/// Read these rows' Urgent files from Apple, six at a time, and tell the window what came back.+async fn read_urgent(app: tauri::AppHandle, unread: Vec<(String, String)>) {+ use futures_util::StreamExt;+ use tauri::{Emitter, Manager};+ let guids: Vec<String> = unread.iter().map(|(guid, _)| guid.clone()).collect();+ let auth = app.state::<Auth>();+ if let Ok((http, root, params)) = crate::cloudkit_context(&auth).await {+ let read: Vec<UrgentRead> = futures_util::stream::iter(unread)+ .map(|(guid, raw)| {+ let (http, root, params) = (http.clone(), root.clone(), params.clone());+ async move {+ let urgent = more::urgent_for(&http, &root, params, &guid, &raw).await;+ urgent.map(|urgent| UrgentRead { guid, urgent })+ }+ })+ .buffer_unordered(6)+ .filter_map(|found| async move { found })+ .collect()+ .await;+ if !read.is_empty() {+ let _ = app.emit(URGENT_READ, read);+ }+ }+ done_asking(&guids);+}+/// Every tag on the account, with how many reminders still to do carry each.#[tauri::command]pub async fn reminder_tags(data: State<'_, Data>) -> UiResult<Vec<TagCount>> {@@ -178,6 +230,14 @@ pub async fn reminders_tagged(name: String, data: State<'_, Data>) -> UiResult<Vlibrary.reminders_tagged(&name).map_err(|e| e.to_string())}+/// Each reminder still to do with its tags, and how many each custom smart list holds: the+/// sidebar's and the rows' tag chips in one read, rather than one per tag and per list.+#[tauri::command]+pub async fn reminder_extras(data: State<'_, Data>) -> UiResult<ReminderExtras> {+ let library = data.0.lock().await;+ library.reminder_extras(now()).map_err(|e| e.to_string())+}+/// The account's smart lists, built-in and custom.#[tauri::command]pub async fn reminder_smart_lists(data: State<'_, Data>) -> UiResult<Vec<ReminderSmartList>> {@@ -341,3 +401,28 @@ pub async fn reminder_section_move(.await;finish(done, &http, &root, params, &data).await}++#[cfg(test)]+mod tests {+ use super::*;++ /// A row whose Urgent file is on its way is not asked for again until that read is over.+ #[test]+ fn a_row_being_read_is_not_asked_for_twice() {+ let row = |g: &str| (g.to_string(), "{}".to_string());+ let first = take_unasked(vec![row("Reminder/U1"), row("Reminder/U2")]);+ assert_eq!(first.len(), 2);+ let again = take_unasked(vec![row("Reminder/U1"), row("Reminder/U3")]);+ assert_eq!(again, vec![row("Reminder/U3")]);+ done_asking(&["Reminder/U1".to_string()]);+ assert_eq!(+ take_unasked(vec![row("Reminder/U1")]),+ vec![row("Reminder/U1")]+ );+ done_asking(&[+ "Reminder/U1".to_string(),+ "Reminder/U2".to_string(),+ "Reminder/U3".to_string(),+ ]);+ }+}diff --git a/src/lib/ipc.ts b/src/lib/ipc.tsindex 4d56b1a..53c9e5e 100644--- a/src/lib/ipc.ts+++ b/src/lib/ipc.ts@@ -1108,6 +1108,13 @@ export type ReminderSmartList = {/** What a custom smart list holds now, and any part of its rules not read here. */export type SmartListContents = { reminders: Reminder[]; unknown: string[] };+/** Each reminder still to do with its tags, and how many each custom smart list holds, by id. */+export type ReminderExtras = { tagsByReminder: Record<string, string[]>; customCounts: Record<string, number> };++/** Told as Urgent is read from Apple for rows whose marks came back without it. */+export const REMINDER_URGENT = "quince://reminder-urgent";+export type UrgentRead = { guid: string; urgent: boolean };+export const remindersApi = {detail: (guid: string) => invoke<ReminderDetail>("reminder_detail", { guid }),more: (guid: string) => invoke<ReminderMore>("reminder_more", { guid }),@@ -1118,6 +1125,8 @@ export const remindersApi = {tags: () => invoke<TagCount[]>("reminder_tags"),tagged: (name: string) => invoke<Reminder[]>("reminders_tagged", { name }),smartLists: () => invoke<ReminderSmartList[]>("reminder_smart_lists"),+ /** Tags by reminder and smart-list counts, in one read. */+ extras: () => invoke<ReminderExtras>("reminder_extras"),inSmartList: (guid: string) => invoke<SmartListContents>("reminders_in_smart_list", { guid }),tagAdd: (guid: string, name: string) => invoke<void>("reminder_tag_add", { guid, name }),tagRemove: (guid: string, name: string) => invoke<void>("reminder_tag_remove", { guid, name }),diff --git a/src/lib/outbox.ts b/src/lib/outbox.tsindex caa6007..1188415 100644--- a/src/lib/outbox.ts+++ b/src/lib/outbox.ts@@ -38,8 +38,10 @@ export function changeWords(r: Pick<RefusedChange, "service" | "kind">): string* (shown as "Waiting to sync"), and the changes Apple turned down — kept, with what was typed,* until the person sends them again or lets them go.*- * The backend says when this moves (`quince://outbox-changed`): as it starts sending, as a- * change lands, as one is refused. `tick` counts those, for a view to read its rows again.+ * The backend says when this moves (`quince://outbox-changed`), once a pass of sending is over,+ * naming the services it sent for or found waiting. `tick` counts those that name this one, for+ * a view to read its rows again: a Notes save landing re-read Reminders and Calendar too, each+ * whole, twice. A word with no services named (a change resent or let go) is for every view.*/export function useOutbox(service: OutboxService) {wakeWhenOnline();@@ -56,14 +58,16 @@ export function useOutbox(service: OutboxService) {useEffect(() => {read();const offs = [- listen(CHANGED, () => {+ listen<{ services?: string[] } | null>(CHANGED, (e) => {+ const services = e.payload?.services;+ if (Array.isArray(services) && !services.includes(service)) return;read();setTick((n) => n + 1);}),listen(REFUSED, () => read()),];return () => offs.forEach((off) => void off.then((f) => f()).catch(() => {}));- }, [read]);+ }, [read, service]);const waiting = useMemo(() => new Set(status.waiting.filter((w) => w.service === service).map((w) => w.record)),diff --git a/src/screens/RemindersView.tsx b/src/screens/RemindersView.tsxindex cb0fc8a..83a6d95 100644--- a/src/screens/RemindersView.tsx+++ b/src/screens/RemindersView.tsx@@ -1,4 +1,4 @@-import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from "react";+import { Fragment, memo, useCallback, useEffect, useMemo, useRef, useState } from "react";import { fadeIn, fadeOut } from "../lib/fade";import { overlayOpen, useActiveRef } from "../lib/screen";import { useModalFocus } from "../lib/focus";@@ -32,6 +32,8 @@ import {type RepeatRule,type ReminderSmartList,type TagCount,+ REMINDER_URGENT,+ type UrgentRead,} from "../lib/ipc";import { Arriving } from "../components/EmptyState";import { useArriving, useSync } from "../lib/sync";@@ -310,6 +312,9 @@ type Selection =export function RemindersView() {const [lists, setLists] = useState<ReminderList[]>([]);+ /** Each list by its id: every row looks its own up, and a search through the array per row+ * was a thousand walks of it per draw. */+ const listById = useMemo(() => new Map(lists.map((l) => [l.guid, l])), [lists]);const focusedBeforePress = useRef<Element | null>(null);/** A reminder's menu, from a right-click on its row. */const [rowMenu, setRowMenu] = useState<{ reminder: Reminder; at: { x: number; y: number; alignRight: boolean } } | null>(null);@@ -441,26 +446,23 @@ export function RemindersView() {void readExtras().catch(() => {});}, []);- /** Tags with each one's reminders, and custom smart lists with what each holds. */+ /**+ * Tags with each one's reminders, and custom smart lists with what each holds. Three reads,+ * whatever the account holds: this asked for every tag's reminders and every smart list's+ * whole, one call each, only to know which tags each row carries and how many each list has.+ */const readExtras = async () => {- const [allTags, smart] = await Promise.all([+ const [allTags, smart, extras] = await Promise.all([remindersApi.tags().catch(() => [] as TagCount[]),remindersApi.smartLists().catch(() => [] as ReminderSmartList[]),+ remindersApi.extras().catch(() => null),]);const named = (Array.isArray(allTags) ? allTags : []).filter((t) => t.name);const custom = (Array.isArray(smart) ? smart : []).filter((x) => x.kind === "custom");- const [tagged, held] = await Promise.all([- Promise.all(named.map((t) => remindersApi.tagged(t.name).catch(() => [] as Reminder[]))),- Promise.all(custom.map((x) => remindersApi.inSmartList(x.guid).then((c) => c.reminders.length).catch(() => 0))),- ]);- const byReminder = new Map<string, string[]>();- named.forEach((t, i) => {- for (const r of tagged[i] ?? []) byReminder.set(r.guid, [...(byReminder.get(r.guid) ?? []), t.name]);- });setTags(named);- setTagsOf(byReminder);+ setTagsOf(new Map(Object.entries(extras?.tagsByReminder ?? {})));setCustomLists(custom);- setCustomCounts(new Map(custom.map((x, i) => [x.guid, held[i] ?? 0])));+ setCustomCounts(new Map(custom.map((x) => [x.guid, extras?.customCounts?.[x.guid] ?? 0])));};// A list's headings are read with its reminders (readItems), so they arrive together.@@ -468,6 +470,21 @@ export function RemindersView() {/** What is typed in the search field. While it holds anything, the pane is the results. */const [query, setQuery] = useState("");const searching = query.trim().length > 0;+ /**+ * What is searched for: the field once typing pauses for 120 ms, as Calendar's search waits.+ * Each key ran a search and the rows' marks again; a field emptied is taken at once.+ */+ const [settled, setSettled] = useState("");+ useEffect(() => {+ if (!query.trim()) {+ setSettled("");+ return undefined;+ }+ const timer = window.setTimeout(() => setSettled(query), 120);+ return () => window.clearTimeout(timer);+ }, [query]);+ const sought = searching ? settled : "";+ const seeking = sought.trim().length > 0;/*** In a narrow window one column shows at a time, as on iPhone: the lists, or the list that* was picked, with a way back. Searching shows the results under the search field.@@ -485,8 +502,8 @@ export function RemindersView() {// Search reaches every list, as Apple's does, whatever is open in the sidebar.let unknown: string[] = [];const [found, sections] = await Promise.all([- searching- ? api.remindersSearch(query)+ seeking+ ? api.remindersSearch(sought): sel.type === "smart"? api.remindersSmart(sel.kind, endOfToday()): sel.type === "tag"@@ -509,21 +526,30 @@ export function RemindersView() {setListSections(Array.isArray(sections) ? sections : []);setUnknownRules(unknown);return fresh;- }, [picked, showDone, query, searching, over]);+ }, [picked, showDone, sought, seeking, over]);// Changes go to Apple behind the window (the outbox): once a batch has landed the library// holds Apple's own version, and a change Apple refused has been put back — said here, why.+ // Through a ref, so the listeners are set up once: with `readItems` in their effect's deps,+ // every key typed into the search took both down and set them up again.+ const readItemsRef = useRef(readItems);+ readItemsRef.current = readItems;useEffect(() => {const offs = [- listen("quince://reminders-synced", () => void readItems().catch(() => {})),+ listen("quince://reminders-synced", () => void readItemsRef.current().catch(() => {})),// Said by the refused change's own notice (Unsent), which keeps what it held.listen<{ service: string; message: string }>("quince://outbox-refused", (e) => {if (e.payload.service !== "reminders") return;- void readItems().catch(() => {});+ void readItemsRef.current().catch(() => {});+ }),+ // Urgent read from Apple behind the marks' answer, merged in as it comes.+ listen<UrgentRead[]>(REMINDER_URGENT, (e) => {+ const read = Array.isArray(e.payload) ? e.payload : [];+ if (read.length) setMarks((was) => withUrgent(was, read));}),];return () => offs.forEach((off) => void off.then((f) => f()).catch(() => {}));- }, [readItems]);+ }, []);// 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@@ -844,7 +870,7 @@ export function RemindersView() {};}, [revision, outbox.tick, items.length, moreOf?.repeat?.endAt]);// The rows' marks, read again when the rows or Apple's copy change.- const markKey = items.map((r) => r.guid).join(",");+ const markKey = useMemo(() => items.map((r) => r.guid).join(","), [items]);useEffect(() => {const guids = items.filter((r) => !r.guid.startsWith(STAND_IN)).map((r) => r.guid);if (!guids.length) return;@@ -1057,9 +1083,17 @@ export function RemindersView() {return () => window.removeEventListener("keydown", onKey);}, []);- /** Drag and drop: what is being dragged, and the row it would land before. */+ /** Drag and drop: what is being dragged (state, for its own row's look; a ref, for the rows+ * it passes over), and the row it would land before — marked on that row's element. */const [dragging, setDragging] = useState<string | null>(null);- const [dropBefore, setDropBefore] = useState<string | null>(null);+ const draggingRef = useRef<string | null>(null);+ const dropRow = useRef<HTMLElement | null>(null);+ const markDrop = (row: HTMLElement | null) => {+ if (dropRow.current !== row) dropRow.current?.classList.remove("is-drop-before");+ // Added again on every dragover: a row drawn again mid-drag takes its class from React.+ row?.classList.add("is-drop-before");+ dropRow.current = row;+ };const canReorder = inList && !searching;/** Put a reminder before another in its list — at once, then to Apple; back if refused. */const reorder = (guid: string, before: string) => {@@ -1335,10 +1369,12 @@ export function RemindersView() {// All.const byList = new Map<string, typeof threaded>();for (const row of threaded) {- byList.set(row.reminder.listGuid, [...(byList.get(row.reminder.listGuid) ?? []), row]);+ const bucket = byList.get(row.reminder.listGuid);+ if (bucket) bucket.push(row);+ else byList.set(row.reminder.listGuid, [row]);}return [...byList.entries()].map(([guid, rows]) => {- const list = lists.find((l) => l.guid === guid);+ const list = listById.get(guid);return {key: guid,heading: list?.title ?? "Reminders",@@ -1371,7 +1407,7 @@ export function RemindersView() {const kind = smartKind;const now = new Date();- const listOf = (guid: string) => lists.find((l) => l.guid === guid);+ const listOf = (guid: string) => listById.get(guid);if (kind === "today") {// Apple's own buckets, each shown only when something is in it: empty "Morning" and@@ -1466,7 +1502,7 @@ export function RemindersView() {dated: false,rows,}));- }, [threaded, inList, selection, lists, listSections, searching]);+ }, [threaded, inList, selection, listById, listSections, searching]);const countOf = (guid: string) => counts?.lists.find(([g]) => g === guid)?.[1] ?? 0;const openList = inList ? (lists.find((l) => l.guid === listGuid) ?? null) : null;@@ -1635,6 +1671,24 @@ export function RemindersView() {</form>);+ const rowActions = useRef<RowActions>(null!);+ rowActions.current = {+ toggle, askRemove, rename, indent, outdent, flag, setNotes, setUrl, setDue, setEarly, setRepeat,+ tagAdd, tagRemove, setPriority, moveToList, moveToSection, openTag, setOpenGuid, reorder,+ openMenu: (reminder, at) => setRowMenu({ reminder, at }),+ dragging: () => draggingRef.current,+ startDrag: (guid) => {+ draggingRef.current = guid;+ setDragging(guid);+ },+ endDrag: () => {+ draggingRef.current = null;+ setDragging(null);+ markDrop(null);+ },+ markDrop,+ };+return (<divclassName={`rx${detail && !searching ? " is-detail" : ""}${searching ? " is-searching" : ""}`}@@ -1857,421 +1911,36 @@ export function RemindersView() {))}<ul className="rx-rows">{section.rows.map(({ reminder, depth }) => {- const due =- reminder.dueAt === null ? null : dueLabel(reminder.dueAt, section.dated, reminder.allDay);const isOpen = openGuid === reminder.guid;- const repeat = repeatLabel(reminder);- const justMoved = moved?.guid === reminder.guid ? moved.text : null;- const home = lists.find((l) => l.guid === reminder.listGuid);- const mark = priorityMark(reminder.priority);- const rowMarks = marks.get(reminder.guid);- // Kept in another zone, the phone adds that zone's clock: "8:30 PM (11:00 AM GMT-4)".- const elsewhere =- due && reminder.dueAt !== null && !reminder.allDay && reminder.timezone && reminder.timezone !== LOCAL_ZONE- ? zonedClock(reminder.timezone, reminder.dueAt)- : null;- const chips = rowMarks && (rowMarks.location || rowMarks.messaging || rowMarks.url) ? rowMarks : null;- const rowTags =- isOpen && detailOf?.guid === reminder.guid ? detailOf.tags : (tagsOf.get(reminder.guid) ?? []);return (- <li+ <ReminderRowkey={reminder.guid}- className={`rx-row${reminder.completedAt ? " is-done" : ""}${leaving.has(reminder.guid) ? " is-leaving" : ""}${- depth > 0 ? " is-subtask" : ""- }${isOpen ? " is-open" : ""}${dropBefore === reminder.guid ? " is-drop-before" : ""}${- dragging === reminder.guid ? " is-dragging" : ""- }`}- // Drag to reorder, in a list, as Reminders does — open ones among themselves.- draggable={canReorder && depth === 0 && !reminder.completedAt}- onDragStart={(e) => {- if (!canReorder) return;- e.dataTransfer.effectAllowed = "move";- e.dataTransfer.setData("text/plain", reminder.guid);- setDragging(reminder.guid);- }}- onDragEnd={() => { setDragging(null); setDropBefore(null); }}- // The row itself takes the keyboard, as on icloud.com and the Mac: arrows go- // from row to row, Space ticks it, Return edits its title, Delete deletes it- // once confirmed — a reminder deleted here cannot be brought back.- tabIndex={-1}- data-guid={reminder.guid}- // The list's colour for everything on the row drawn in it: the circle, the- // priority marks.- style={{ "--tick": colourOf(home) } as React.CSSProperties}- onKeyDown={(e) => {- if (e.target !== e.currentTarget) return;- const rows = [...document.querySelectorAll<HTMLElement>(".rx-rows .rx-row")];- const at = rows.indexOf(e.currentTarget);- const go = (i: number) => rows[Math.max(0, Math.min(rows.length - 1, i))]?.focus();- if (e.key === "ArrowDown" || e.key === "ArrowUp") {- e.preventDefault();- go(at + (e.key === "ArrowDown" ? 1 : -1));- } else if (e.key === "Home" || e.key === "End") {- e.preventDefault();- go(e.key === "Home" ? 0 : rows.length - 1);- } else if (e.key === " ") {- e.preventDefault();- void toggle(reminder);- } else if (e.key === "Enter") {- e.preventDefault();- const title = e.currentTarget.querySelector<HTMLInputElement>(".rx-title");- title?.focus();- title?.select();- } else if (e.key === "Delete" || e.key === "Backspace") {- e.preventDefault();- void askRemove(reminder);- }- }}- // Right-click, as on the Mac: what can be done to this reminder, in one menu.- onMouseDownCapture={() => {- // What had focus before this press: the press itself focuses a title it- // lands on, which is not the same as someone already typing in it.- focusedBeforePress.current = document.activeElement;- }}- onContextMenu={(e) => {- // Text being edited keeps its own menu; anywhere else on the row, the- // reminder's — its title included, until someone is typing in it.- const field = (e.target as HTMLElement).closest("input, textarea, [contenteditable=true]");- if (field && field === focusedBeforePress.current) return;- (document.activeElement as HTMLElement | null)?.blur?.();- e.preventDefault();- setRowMenu({ reminder, at: { x: e.clientX, y: e.clientY, alignRight: false } });- }}- onDragOver={(e) => {- if (!dragging || dragging === reminder.guid || depth > 0 || reminder.completedAt) return;- e.preventDefault();- e.dataTransfer.dropEffect = "move";- if (dropBefore !== reminder.guid) setDropBefore(reminder.guid);- }}- onDrop={(e) => {- e.preventDefault();- const moving = dragging;- setDragging(null);- setDropBefore(null);- if (moving && moving !== reminder.guid) void reorder(moving, reminder.guid);- }}- >- <button- className="rx-tick"- role="checkbox"- aria-checked={Boolean(reminder.completedAt) || settling.has(reminder.guid)}- aria-label={reminder.title}- style={{ "--tick": colourOf(home) } as React.CSSProperties}- // The fill fades in on the press itself, and only then (kept as state, it came- // in again every time Reminders came back into view): opacity alone, on a- // twenty-pixel circle, drawn by the page (lib/fade) — never the compositor.- onClick={(e) => {- const fill = e.currentTarget.querySelector<HTMLElement>(".rx-tick-fill");- const filling = !reminder.completedAt;- toggle(reminder);- if (filling) requestAnimationFrame(() => fadeIn(fill, { from: 0.25, duration: 140 }));- }}- >- <span className="rx-tick-fill" aria-hidden="true" />- </button>-- <div className="rx-text">- <div className="rx-title-row">- {mark && (- <span- className="rx-priority"- role="img"- aria-label={`${- PRIORITIES.find((p) => p.value === reminder.priority)?.label- } priority`}- >- {mark}- </span>- )}- <input- className="rx-title"- defaultValue={reminder.title}- key={`${reminder.guid}-${reminder.title}`}- aria-label={`Rename ${reminder.title}`}-- onBlur={(e) => void rename(reminder, e.target.value)}- onKeyDown={(e) => {- // As in Reminders on a Mac: Return finishes it and starts the next,- // Tab tucks it under the one above, Shift-Tab brings it back out.- if (e.key === "Enter") {- e.preventDefault();- e.currentTarget.blur();- window.setTimeout(() => document.querySelector<HTMLInputElement>(".rx-add input")?.focus(), 0);- } else if (e.key === "Escape") {- // Back to the row, which then takes the arrows and Space.- e.currentTarget.value = reminder.title;- e.currentTarget.closest<HTMLElement>(".rx-row")?.focus();- } else if (inList && (e.key === "Tab" || ((e.ctrlKey || e.metaKey) && (e.key === "]" || e.key === "[")))) {- // Tab and Shift-Tab, or Command-] and Command-[ as the Mac's menu has them.- e.preventDefault();- const typed = e.currentTarget.value;- const out = e.key === "[" || (e.key === "Tab" && e.shiftKey);- void rename(reminder, typed);- void (out ? (reminder.parentGuid ? outdent(reminder) : null) : (reminder.parentGuid ? null : indent(reminder)));- } else if ((e.key === "ArrowUp" || e.key === "ArrowDown") && !e.shiftKey && !e.altKey) {- // Up and Down walk the list, keeping where the caret was.- const all = [...document.querySelectorAll<HTMLInputElement>(".rx-row .rx-title")];- const next = all[all.indexOf(e.currentTarget) + (e.key === "ArrowDown" ? 1 : -1)];- if (next) {- e.preventDefault();- const caret = e.currentTarget.selectionStart ?? 0;- next.focus();- next.setSelectionRange(Math.min(caret, next.value.length), Math.min(caret, next.value.length));- }- }- }}- />- </div>- {reminder.notes && !isOpen && (- <span className="rx-notes">{reminder.notes}</span>- )}- <Waiting shown={outbox.waiting.has(reminder.guid)} />- {(due || repeat || justMoved || (showListName && home) || rowTags.length > 0 || rowMarks?.urgent) && (- <span className="rx-meta">- {justMoved ? (- <span className="rx-moved" role="status">- Moved to {justMoved}- </span>- ) : (- <>- {showListName && (- <span className="rx-from">{home?.title ?? "Reminders"}</span>- )}- {due && (- <span className={`rx-due${due.overdue ? " overdue" : ""}`}>- {elsewhere ? `${due.text} (${elsewhere})` : due.text}- </span>- )}- {repeat && (- <span className="rx-repeat" title={repeat}>- <span aria-hidden="true">↻</span> {repeatWord(reminder, rowMarks?.daysOfWeek)}- <span className="visually-hidden">{repeat}</span>- </span>- )}- {rowMarks?.urgent && (- <span className="rx-urgent" role="img" aria-label="Urgent" title="Urgent">- <AlarmClock aria-hidden="true" size={13} strokeWidth={2} />- </span>- )}- {rowTags.map((name) => (- <button- key={name}- type="button"- className="rx-tag"- tabIndex={-1}- aria-label={`Show reminders tagged ${name}`}- onClick={() => openTag(name)}- >- #{name}- </button>- ))}- </>- )}- </span>- )}- {chips && !justMoved && (- <span className="rx-chips">- {chips.location && (- <span className="rx-chip">- <MapPin aria-hidden="true" size={12} strokeWidth={2.2} className="rx-chip-place" />- {chips.location.proximity && <b>{chips.location.proximity === "arriving" ? "Arriving:" : "Leaving:"}</b>}- {chips.location.title ?? "A place"}- </span>- )}- {chips.messaging && (- <span className="rx-chip">- <MessageCircle aria-hidden="true" size={12} strokeWidth={2.2} />- <b>Messaging:</b>- {chips.messaging}- </span>- )}- {chips.url && (- <a className="rx-chip rx-chip-link" href={chips.url} target="_blank" rel="noreferrer" tabIndex={-1} title={chips.url}>- <Link2 aria-hidden="true" size={12} strokeWidth={2.2} />- {hostOf(chips.url)}- </a>- )}- </span>- )}-- {isOpen && (- <div className="rx-detail" role="group" aria-label={`Info for ${reminder.title}`}>- <label className="rx-field rx-field-notes">- <span>Notes</span>- <textarea- className="field"- defaultValue={reminder.notes ?? ""}- key={`n${reminder.guid}`}- rows={2}- placeholder="Add Note"- onBlur={(e) => void setNotes(reminder, e.target.value)}- />- </label>- <UrlField- reminder={reminder}- url={detailOf?.guid === reminder.guid ? detailOf.url : null}- onSave={(url) => void setUrl(reminder, url)}- />- <div className="rx-detail-rule" aria-hidden="true" />- <DueField reminder={reminder} onChange={(day, time) => void setDue(reminder, day, time)} />- {moreOf?.guid === reminder.guid && <ZoneAndUrgent reminder={reminder} more={moreOf} />}- <EarlyField- reminder={reminder}- alerts={detailOf?.guid === reminder.guid ? detailOf.earlyAlerts : []}- onChange={(alert) => void setEarly(reminder, alert)}- />- <RepeatField- reminder={reminder}- rule={moreOf?.guid === reminder.guid ? moreOf.repeat : null}- onChange={(repeat, endAt, days) => void setRepeat(reminder, repeat, endAt, days)}- />- <div className="rx-detail-rule" aria-hidden="true" />- <TagsField- reminder={reminder}- tags={rowTags}- onOpen={openTag}- onAdd={(name) => void tagAdd(reminder, name)}- onRemove={(name) => void tagRemove(reminder, name)}- />- <div className="rx-field">- <span>Subtasks</span>- <span className="rx-value">{items.filter((x) => x.parentGuid === reminder.guid).length}</span>- </div>- <div className="rx-field">- <span>Flag</span>- <label className="rx-switch">- <input- type="checkbox"- role="switch"- aria-label={`Flag for ${reminder.title}`}- checked={reminder.flagged}- onChange={() => void flag(reminder)}- />- <span className="switch" aria-hidden="true" />- </label>- </div>- <div className="rx-field">- <span>Priority</span>- <Picker- label={`Priority for ${reminder.title}`}- value={String(reminder.priority)}- onChange={(v) => void setPriority(reminder, Number(v))}- options={PRIORITIES.map((p) => ({- value: String(p.value),- label: p.label,- }))}- />- </div>- {moreOf?.guid === reminder.guid && <PlacesAndPeople more={moreOf} />}- {detailOf?.guid === reminder.guid && detailOf.images.length > 0 && (- <div className="rx-images" role="list" aria-label="Pictures">- {detailOf.images.map((id) => (- <img- key={id}- role="listitem"- className="rx-image"- src={reminderImageSrc(id)}- alt="Attached picture"- loading="lazy"- decoding="async"- draggable={false}- />- ))}- </div>- )}- {(detailOf?.guid === reminder.guid ? detailOf.otherAttachments - detailOf.images.length : 0) > 0 && (- <div className="rx-field">- <span>Attachments</span>- <span className="rx-value">- {detailOf!.otherAttachments - detailOf!.images.length === 1- ? "1 file"- : `${detailOf!.otherAttachments - detailOf!.images.length} files`}- </span>- </div>- )}- <div className="rx-detail-rule" aria-hidden="true" />- <div className="rx-field">- <span>List</span>- <Picker- label={`List for ${reminder.title}`}- value={reminder.listGuid}- onChange={(guid) => void moveToList(reminder, guid)}- options={lists.map((l) => ({ value: l.guid, label: l.title }))}- />- </div>- {inList && listSections.length > 0 && (- <div className="rx-field">- <span>Section</span>- {REMINDER_DETAIL_WRITES ? (- <Picker- label={`Section for ${reminder.title}`}- value={sectionOf(reminder) ?? ""}- onChange={(guid) => void moveToSection(reminder, guid || null)}- options={[- { value: "", label: "None" },- ...listSections.map((x) => ({ value: x.guid, label: x.title })),- ]}- />- ) : (- <span className="rx-value">- {listSections.find((x) => x.guid === sectionOf(reminder))?.title ?? "None"}- </span>- )}- </div>- )}- <div className="rx-detail-actions">- {depth > 0 ? (- <button- className="link"- onClick={() => void outdent(reminder)}- >- Move Out of Subtasks- </button>- ) : items.some((x) => x.parentGuid === reminder.guid) ? null : (- <button- className="link"- onClick={() => void indent(reminder)}- >- Make Subtask- </button>- )}- <button- className="link danger"- aria-label={`Delete ${reminder.title}`}-- onClick={() => void askRemove(reminder)}- >- Delete- </button>- </div>- </div>- )}- </div>-- <span className="rx-trailing">- <button- className="icon-button small rx-icon-button"- aria-label={- isOpen ? `Close details for ${reminder.title}` : `Details for ${reminder.title}`- }- aria-expanded={isOpen}- onClick={() => setOpenGuid(isOpen ? null : reminder.guid)}- >- <Glyph name="info" />- </button>- <button- className={`icon-button small is-glyph-state rx-icon-button rx-flag${reminder.flagged ? " on" : ""}`}- aria-label={- reminder.flagged ? `Unflag ${reminder.title}` : `Flag ${reminder.title}`- }- aria-pressed={reminder.flagged}-- onClick={() => flag(reminder)}- >- <Glyph name="flagged" />- </button>- </span>- </li>+ reminder={reminder}+ depth={depth}+ dated={section.dated}+ isOpen={isOpen}+ marks={marks.get(reminder.guid)}+ tags={isOpen && detailOf?.guid === reminder.guid ? detailOf.tags : (tagsOf.get(reminder.guid) ?? NO_TAGS)}+ home={listById.get(reminder.listGuid)}+ showListName={showListName}+ justMoved={moved?.guid === reminder.guid ? moved.text : null}+ waiting={outbox.waiting.has(reminder.guid)}+ leaving={leaving.has(reminder.guid)}+ settling={settling.has(reminder.guid)}+ isDragging={dragging === reminder.guid}+ canReorder={canReorder}+ inList={inList}+ act={rowActions}+ focused={focusedBeforePress}+ // What only the open row's details read: left out of every other row, so a+ // change to any of it draws one row again, not a thousand.+ detailOf={isOpen ? detailOf : null}+ moreOf={isOpen ? moreOf : null}+ lists={isOpen ? lists : NO_LISTS}+ sections={isOpen ? listSections : NO_SECTIONS}+ section={isOpen ? sectionOf(reminder) : null}+ subtasks={isOpen ? items.filter((x) => x.parentGuid === reminder.guid).length : 0}+ />);})}</ul>@@ -2411,6 +2080,500 @@ export function RemindersView() {);}+/** The actions a row takes, kept in one ref the list fills on every draw: the row reads them+ * when it acts, so handing them down never changes a row's props. */+type RowActions = {+ toggle: (r: Reminder) => void;+ askRemove: (r: Reminder) => Promise<void>;+ rename: (r: Reminder, title: string) => Promise<unknown>;+ indent: (r: Reminder) => Promise<unknown>;+ outdent: (r: Reminder) => Promise<unknown>;+ flag: (r: Reminder) => Promise<unknown>;+ setNotes: (r: Reminder, notes: string) => Promise<unknown> | undefined;+ setUrl: (r: Reminder, url: string | null) => Promise<unknown>;+ setDue: (r: Reminder, day: string, time: string | null) => Promise<unknown>;+ setEarly: (r: Reminder, alert: [number, number] | null) => Promise<unknown>;+ setRepeat: (r: Reminder, repeat: { frequency: number; interval: number } | null, endAt: number | null, days?: number[]) => Promise<unknown>;+ tagAdd: (r: Reminder, name: string) => Promise<unknown>;+ tagRemove: (r: Reminder, name: string) => Promise<unknown>;+ setPriority: (r: Reminder, priority: number) => Promise<unknown>;+ moveToList: (r: Reminder, listGuid: string) => Promise<unknown>;+ moveToSection: (r: Reminder, section: string | null) => Promise<unknown>;+ openTag: (name: string) => void;+ setOpenGuid: (guid: string | null) => void;+ openMenu: (r: Reminder, at: { x: number; y: number; alignRight: boolean }) => void;+ reorder: (guid: string, before: string) => Promise<unknown>;+ /** The reminder being dragged now, read at the moment it is asked. */+ dragging: () => string | null;+ startDrag: (guid: string) => void;+ endDrag: () => void;+ /** Mark the row a drop would land before, and only that one. */+ markDrop: (row: HTMLElement) => void;+};++/** Marks with Urgent read from Apple laid in: a row that had none gains them; the map is+ * replaced only when a row's Urgent changes, so nothing else is drawn again. */+function withUrgent(was: Map<string, ReminderMarks>, read: UrgentRead[]): Map<string, ReminderMarks> {+ let next: Map<string, ReminderMarks> | null = null;+ for (const { guid, urgent } of read) {+ const at = was.get(guid);+ if ((at?.urgent ?? false) === urgent) continue;+ next ??= new Map(was);+ next.set(guid, { ...(at ?? { guid, daysOfWeek: [], urgent: false, location: null, messaging: null, url: null }), urgent });+ }+ return next ?? was;+}++const NO_TAGS: string[] = [];+const NO_LISTS: ReminderList[] = [];+const NO_SECTIONS: ReminderSection[] = [];++type ReminderRowProps = {+ reminder: Reminder;+ depth: number;+ /** Under a heading that already says the day, so the row says only the time. */+ dated: boolean;+ isOpen: boolean;+ marks: ReminderMarks | undefined;+ tags: string[];+ home: ReminderList | undefined;+ showListName: boolean;+ justMoved: string | null;+ waiting: boolean;+ leaving: boolean;+ settling: boolean;+ isDragging: boolean;+ canReorder: boolean;+ inList: boolean;+ act: React.MutableRefObject<RowActions>;+ focused: React.MutableRefObject<Element | null>;+ detailOf: ReminderDetail | null;+ moreOf: ReminderMore | null;+ lists: ReminderList[];+ sections: ReminderSection[];+ section: string | null;+ subtasks: number;+};++/**+ * One reminder's row, drawn again only when something it shows changes. Inline, every row of+ * up to a thousand was rebuilt on each key typed into New Reminder or the search, each tick and+ * each row the pointer crossed while dragging.+ */+const ReminderRow = memo(function ReminderRow({+ reminder, depth, dated, isOpen, marks: rowMarks, tags: rowTags, home, showListName, justMoved, waiting,+ leaving, settling, isDragging, canReorder, inList, act, focused, detailOf, moreOf, lists, sections, section, subtasks,+}: ReminderRowProps) {+ const due = reminder.dueAt === null ? null : dueLabel(reminder.dueAt, dated, reminder.allDay);+ const repeat = repeatLabel(reminder);+ const mark = priorityMark(reminder.priority);+ // Kept in another zone, the phone adds that zone's clock: "8:30 PM (11:00 AM GMT-4)".+ const elsewhere =+ due && reminder.dueAt !== null && !reminder.allDay && reminder.timezone && reminder.timezone !== LOCAL_ZONE+ ? zonedClock(reminder.timezone, reminder.dueAt)+ : null;+ const chips = rowMarks && (rowMarks.location || rowMarks.messaging || rowMarks.url) ? rowMarks : null;+ return (+ <li+ className={`rx-row${reminder.completedAt ? " is-done" : ""}${leaving ? " is-leaving" : ""}${+ depth > 0 ? " is-subtask" : ""+ }${isOpen ? " is-open" : ""}${isDragging ? " is-dragging" : ""}`}+ // Drag to reorder, in a list, as Reminders does — open ones among themselves.+ draggable={canReorder && depth === 0 && !reminder.completedAt}+ onDragStart={(e) => {+ if (!canReorder) return;+ e.dataTransfer.effectAllowed = "move";+ e.dataTransfer.setData("text/plain", reminder.guid);+ act.current.startDrag(reminder.guid);+ }}+ onDragEnd={() => act.current.endDrag()}+ // The row itself takes the keyboard, as on icloud.com and the Mac: arrows go+ // from row to row, Space ticks it, Return edits its title, Delete deletes it+ // once confirmed — a reminder deleted here cannot be brought back.+ tabIndex={-1}+ data-guid={reminder.guid}+ // The list's colour for everything on the row drawn in it: the circle, the+ // priority marks.+ style={{ "--tick": colourOf(home) } as React.CSSProperties}+ onKeyDown={(e) => {+ if (e.target !== e.currentTarget) return;+ const rows = [...document.querySelectorAll<HTMLElement>(".rx-rows .rx-row")];+ const at = rows.indexOf(e.currentTarget);+ const go = (i: number) => rows[Math.max(0, Math.min(rows.length - 1, i))]?.focus();+ if (e.key === "ArrowDown" || e.key === "ArrowUp") {+ e.preventDefault();+ go(at + (e.key === "ArrowDown" ? 1 : -1));+ } else if (e.key === "Home" || e.key === "End") {+ e.preventDefault();+ go(e.key === "Home" ? 0 : rows.length - 1);+ } else if (e.key === " ") {+ e.preventDefault();+ act.current.toggle(reminder);+ } else if (e.key === "Enter") {+ e.preventDefault();+ const title = e.currentTarget.querySelector<HTMLInputElement>(".rx-title");+ title?.focus();+ title?.select();+ } else if (e.key === "Delete" || e.key === "Backspace") {+ e.preventDefault();+ void act.current.askRemove(reminder);+ }+ }}+ // Right-click, as on the Mac: what can be done to this reminder, in one menu.+ onMouseDownCapture={() => {+ // What had focus before this press: the press itself focuses a title it+ // lands on, which is not the same as someone already typing in it.+ focused.current = document.activeElement;+ }}+ onContextMenu={(e) => {+ // Text being edited keeps its own menu; anywhere else on the row, the+ // reminder's — its title included, until someone is typing in it.+ const field = (e.target as HTMLElement).closest("input, textarea, [contenteditable=true]");+ if (field && field === focused.current) return;+ (document.activeElement as HTMLElement | null)?.blur?.();+ e.preventDefault();+ act.current.openMenu(reminder, { x: e.clientX, y: e.clientY, alignRight: false });+ }}+ onDragOver={(e) => {+ const dragging = act.current.dragging();+ if (!dragging || dragging === reminder.guid || depth > 0 || reminder.completedAt) return;+ e.preventDefault();+ e.dataTransfer.dropEffect = "move";+ // Marked on the row itself, not in state: a state change here drew the whole list+ // again each time the pointer crossed into another row.+ act.current.markDrop(e.currentTarget);+ }}+ onDrop={(e) => {+ e.preventDefault();+ const moving = act.current.dragging();+ act.current.endDrag();+ if (moving && moving !== reminder.guid) void act.current.reorder(moving, reminder.guid);+ }}+ >+ <button+ className="rx-tick"+ role="checkbox"+ aria-checked={Boolean(reminder.completedAt) || settling}+ aria-label={reminder.title}+ style={{ "--tick": colourOf(home) } as React.CSSProperties}+ // The fill fades in on the press itself, and only then (kept as state, it came+ // in again every time Reminders came back into view): opacity alone, on a+ // twenty-pixel circle, drawn by the page (lib/fade) — never the compositor.+ onClick={(e) => {+ const fill = e.currentTarget.querySelector<HTMLElement>(".rx-tick-fill");+ const filling = !reminder.completedAt;+ act.current.toggle(reminder);+ if (filling) requestAnimationFrame(() => fadeIn(fill, { from: 0.25, duration: 140 }));+ }}+ >+ <span className="rx-tick-fill" aria-hidden="true" />+ </button>++ <div className="rx-text">+ <div className="rx-title-row">+ {mark && (+ <span+ className="rx-priority"+ role="img"+ aria-label={`${+ PRIORITIES.find((p) => p.value === reminder.priority)?.label+ } priority`}+ >+ {mark}+ </span>+ )}+ <input+ className="rx-title"+ defaultValue={reminder.title}+ key={`${reminder.guid}-${reminder.title}`}+ aria-label={`Rename ${reminder.title}`}++ onBlur={(e) => void act.current.rename(reminder, e.target.value)}+ onKeyDown={(e) => {+ // As in Reminders on a Mac: Return finishes it and starts the next,+ // Tab tucks it under the one above, Shift-Tab brings it back out.+ if (e.key === "Enter") {+ e.preventDefault();+ e.currentTarget.blur();+ window.setTimeout(() => document.querySelector<HTMLInputElement>(".rx-add input")?.focus(), 0);+ } else if (e.key === "Escape") {+ // Back to the row, which then takes the arrows and Space.+ e.currentTarget.value = reminder.title;+ e.currentTarget.closest<HTMLElement>(".rx-row")?.focus();+ } else if (inList && (e.key === "Tab" || ((e.ctrlKey || e.metaKey) && (e.key === "]" || e.key === "[")))) {+ // Tab and Shift-Tab, or Command-] and Command-[ as the Mac's menu has them.+ e.preventDefault();+ const typed = e.currentTarget.value;+ const out = e.key === "[" || (e.key === "Tab" && e.shiftKey);+ void act.current.rename(reminder, typed);+ void (out ? (reminder.parentGuid ? act.current.outdent(reminder) : null) : (reminder.parentGuid ? null : act.current.indent(reminder)));+ } else if ((e.key === "ArrowUp" || e.key === "ArrowDown") && !e.shiftKey && !e.altKey) {+ // Up and Down walk the list, keeping where the caret was.+ const all = [...document.querySelectorAll<HTMLInputElement>(".rx-row .rx-title")];+ const next = all[all.indexOf(e.currentTarget) + (e.key === "ArrowDown" ? 1 : -1)];+ if (next) {+ e.preventDefault();+ const caret = e.currentTarget.selectionStart ?? 0;+ next.focus();+ next.setSelectionRange(Math.min(caret, next.value.length), Math.min(caret, next.value.length));+ }+ }+ }}+ />+ </div>+ {reminder.notes && !isOpen && (+ <span className="rx-notes">{reminder.notes}</span>+ )}+ <Waiting shown={waiting} />+ {(due || repeat || justMoved || (showListName && home) || rowTags.length > 0 || rowMarks?.urgent) && (+ <span className="rx-meta">+ {justMoved ? (+ <span className="rx-moved" role="status">+ Moved to {justMoved}+ </span>+ ) : (+ <>+ {showListName && (+ <span className="rx-from">{home?.title ?? "Reminders"}</span>+ )}+ {due && (+ <span className={`rx-due${due.overdue ? " overdue" : ""}`}>+ {elsewhere ? `${due.text} (${elsewhere})` : due.text}+ </span>+ )}+ {repeat && (+ <span className="rx-repeat" title={repeat}>+ <span aria-hidden="true">↻</span> {repeatWord(reminder, rowMarks?.daysOfWeek)}+ <span className="visually-hidden">{repeat}</span>+ </span>+ )}+ {rowMarks?.urgent && (+ <span className="rx-urgent" role="img" aria-label="Urgent" title="Urgent">+ <AlarmClock aria-hidden="true" size={13} strokeWidth={2} />+ </span>+ )}+ {rowTags.map((name) => (+ <button+ key={name}+ type="button"+ className="rx-tag"+ tabIndex={-1}+ aria-label={`Show reminders tagged ${name}`}+ onClick={() => act.current.openTag(name)}+ >+ #{name}+ </button>+ ))}+ </>+ )}+ </span>+ )}+ {chips && !justMoved && (+ <span className="rx-chips">+ {chips.location && (+ <span className="rx-chip">+ <MapPin aria-hidden="true" size={12} strokeWidth={2.2} className="rx-chip-place" />+ {chips.location.proximity && <b>{chips.location.proximity === "arriving" ? "Arriving:" : "Leaving:"}</b>}+ {chips.location.title ?? "A place"}+ </span>+ )}+ {chips.messaging && (+ <span className="rx-chip">+ <MessageCircle aria-hidden="true" size={12} strokeWidth={2.2} />+ <b>Messaging:</b>+ {chips.messaging}+ </span>+ )}+ {chips.url && (+ <a className="rx-chip rx-chip-link" href={chips.url} target="_blank" rel="noreferrer" tabIndex={-1} title={chips.url}>+ <Link2 aria-hidden="true" size={12} strokeWidth={2.2} />+ {hostOf(chips.url)}+ </a>+ )}+ </span>+ )}++ {isOpen && (+ <div className="rx-detail" role="group" aria-label={`Info for ${reminder.title}`}>+ <label className="rx-field rx-field-notes">+ <span>Notes</span>+ <textarea+ className="field"+ defaultValue={reminder.notes ?? ""}+ key={`n${reminder.guid}`}+ rows={2}+ placeholder="Add Note"+ onBlur={(e) => void act.current.setNotes(reminder, e.target.value)}+ />+ </label>+ <UrlField+ reminder={reminder}+ url={detailOf?.guid === reminder.guid ? detailOf.url : null}+ onSave={(url) => void act.current.setUrl(reminder, url)}+ />+ <div className="rx-detail-rule" aria-hidden="true" />+ <DueField reminder={reminder} onChange={(day, time) => void act.current.setDue(reminder, day, time)} />+ {moreOf?.guid === reminder.guid && <ZoneAndUrgent reminder={reminder} more={moreOf} />}+ <EarlyField+ reminder={reminder}+ alerts={detailOf?.guid === reminder.guid ? detailOf.earlyAlerts : []}+ onChange={(alert) => void act.current.setEarly(reminder, alert)}+ />+ <RepeatField+ reminder={reminder}+ rule={moreOf?.guid === reminder.guid ? moreOf.repeat : null}+ onChange={(repeat, endAt, days) => void act.current.setRepeat(reminder, repeat, endAt, days)}+ />+ <div className="rx-detail-rule" aria-hidden="true" />+ <TagsField+ reminder={reminder}+ tags={rowTags}+ onOpen={(name) => act.current.openTag(name)}+ onAdd={(name) => void act.current.tagAdd(reminder, name)}+ onRemove={(name) => void act.current.tagRemove(reminder, name)}+ />+ <div className="rx-field">+ <span>Subtasks</span>+ <span className="rx-value">{subtasks}</span>+ </div>+ <div className="rx-field">+ <span>Flag</span>+ <label className="rx-switch">+ <input+ type="checkbox"+ role="switch"+ aria-label={`Flag for ${reminder.title}`}+ checked={reminder.flagged}+ onChange={() => void act.current.flag(reminder)}+ />+ <span className="switch" aria-hidden="true" />+ </label>+ </div>+ <div className="rx-field">+ <span>Priority</span>+ <Picker+ label={`Priority for ${reminder.title}`}+ value={String(reminder.priority)}+ onChange={(v) => void act.current.setPriority(reminder, Number(v))}+ options={PRIORITIES.map((p) => ({+ value: String(p.value),+ label: p.label,+ }))}+ />+ </div>+ {moreOf?.guid === reminder.guid && <PlacesAndPeople more={moreOf} />}+ {detailOf?.guid === reminder.guid && detailOf.images.length > 0 && (+ <div className="rx-images" role="list" aria-label="Pictures">+ {detailOf.images.map((id) => (+ <img+ key={id}+ role="listitem"+ className="rx-image"+ src={reminderImageSrc(id)}+ alt="Attached picture"+ loading="lazy"+ decoding="async"+ draggable={false}+ />+ ))}+ </div>+ )}+ {(detailOf?.guid === reminder.guid ? detailOf.otherAttachments - detailOf.images.length : 0) > 0 && (+ <div className="rx-field">+ <span>Attachments</span>+ <span className="rx-value">+ {detailOf!.otherAttachments - detailOf!.images.length === 1+ ? "1 file"+ : `${detailOf!.otherAttachments - detailOf!.images.length} files`}+ </span>+ </div>+ )}+ <div className="rx-detail-rule" aria-hidden="true" />+ <div className="rx-field">+ <span>List</span>+ <Picker+ label={`List for ${reminder.title}`}+ value={reminder.listGuid}+ onChange={(guid) => void act.current.moveToList(reminder, guid)}+ options={lists.map((l) => ({ value: l.guid, label: l.title }))}+ />+ </div>+ {inList && sections.length > 0 && (+ <div className="rx-field">+ <span>Section</span>+ {REMINDER_DETAIL_WRITES ? (+ <Picker+ label={`Section for ${reminder.title}`}+ value={section ?? ""}+ onChange={(guid) => void act.current.moveToSection(reminder, guid || null)}+ options={[+ { value: "", label: "None" },+ ...sections.map((x) => ({ value: x.guid, label: x.title })),+ ]}+ />+ ) : (+ <span className="rx-value">+ {sections.find((x) => x.guid === section)?.title ?? "None"}+ </span>+ )}+ </div>+ )}+ <div className="rx-detail-actions">+ {depth > 0 ? (+ <button+ className="link"+ onClick={() => void act.current.outdent(reminder)}+ >+ Move Out of Subtasks+ </button>+ ) : subtasks > 0 ? null : (+ <button+ className="link"+ onClick={() => void act.current.indent(reminder)}+ >+ Make Subtask+ </button>+ )}+ <button+ className="link danger"+ aria-label={`Delete ${reminder.title}`}++ onClick={() => void act.current.askRemove(reminder)}+ >+ Delete+ </button>+ </div>+ </div>+ )}+ </div>++ <span className="rx-trailing">+ <button+ className="icon-button small rx-icon-button"+ aria-label={+ isOpen ? `Close details for ${reminder.title}` : `Details for ${reminder.title}`+ }+ aria-expanded={isOpen}+ onClick={() => act.current.setOpenGuid(isOpen ? null : reminder.guid)}+ >+ <Glyph name="info" />+ </button>+ <button+ className={`icon-button small is-glyph-state rx-icon-button rx-flag${reminder.flagged ? " on" : ""}`}+ aria-label={+ reminder.flagged ? `Unflag ${reminder.title}` : `Flag ${reminder.title}`+ }+ aria-pressed={reminder.flagged}++ onClick={() => void act.current.flag(reminder)}+ >+ <Glyph name="flagged" />+ </button>+ </span>+ </li>+ );+});+/** Apple's twelve list colours, in its picker's order, keyed as CloudKit names them. */const LIST_COLOURS = [{ key: "red", hex: "#FF3B30" }, { key: "orange", hex: "#FF9500" }, { key: "yellow", hex: "#FFCC00" },diff --git a/src/screens/calendar/CalendarView.tsx b/src/screens/calendar/CalendarView.tsxindex 813e327..d5478b3 100644--- a/src/screens/calendar/CalendarView.tsx+++ b/src/screens/calendar/CalendarView.tsx@@ -460,9 +460,9 @@ export function CalendarView() {const draftRef = useRef<Draft | null>(null);draftRef.current = draft;const [anchor, setAnchor] = useState<Anchor | null>(null);- /** The last event deleted, held so the deletion can be taken back. */- /** The last event deleted, with its alerts, held so the deletion can be taken back. */- const [undo, setUndo] = useState<(CalendarEvent & { alerts: number[] }) | null>(null);+ /** The last event deleted, with its alerts (read from Apple as it goes), held so the deletion+ * can be taken back. */+ const [undo, setUndo] = useState<(CalendarEvent & { alerts: Promise<number[]> }) | null>(null);const { revision } = useSync();// Changes kept here and not yet at Apple (the outbox): a saved event says so, and one Apple// turned down is shown with what it held.@@ -764,17 +764,25 @@ export function CalendarView() {const occurrence = guid.includes("__");const scope = occurrence ? await whichEvents("delete") : null;if (occurrence && !scope) return;- // Its alerts, for Undo to make it again with them: read before it is gone.- const alerts = occurrence- ? []+ // Its alerts, for Undo to make it again with them. Read from Apple alongside the deletion,+ // not before it: awaited first, the event stayed on the grid for a second or two online+ // and until the request gave up offline. The read starts first, so it finds the event in+ // the library, and the deletion is queued once it has its answer — the grid has changed+ // long before. Never on a timer: a deletion that reached Apple first left the read+ // nothing to find, and Undo made the event again without its alerts.+ const alerts: Promise<number[]> = occurrence+ ? Promise.resolve([]): draftRef.current?.guid === guid && draftRef.current.alerts- ? draftRef.current.alerts- : await api.eventAlerts(guid).catch(() => [] as number[]);+ ? Promise.resolve(draftRef.current.alerts)+ : api.eventAlerts(guid).catch(() => [] as number[]);setDraft(null);// All of a series leaves every one of its days; one, only itself.const series = guid.split("__")[0];if (await write(- () => api.eventDelete(guid, scope ?? undefined),+ async () => {+ await alerts;+ await api.eventDelete(guid, scope ?? undefined);+ },(rows) => rows.filter((e) =>scope === "all" ? e.guid.split("__")[0] !== series: scope === "future" ? !(e.guid.split("__")[0] === series && e.startsAt >= (gone?.startsAt ?? 0))@@ -791,7 +799,9 @@ export function CalendarView() {const gone = undo;setUndo(null);// Made again as it was, its alerts with it (its guests are not this app's to invite).- if (gone) await save({ ...draftOf(gone), guid: null, alerts: gone.alerts, alertsChanged: gone.alerts.length > 0 });+ if (!gone) return;+ const alerts = await gone.alerts;+ await save({ ...draftOf(gone), guid: null, alerts, alertsChanged: alerts.length > 0 });}, [undo, save]);const moveEvent = useCallback((e: CalendarEvent, startsAt: number, endsAt: number) => void save({ ...draftOf(e), startsAt, endsAt }),@@ -809,17 +819,30 @@ export function CalendarView() {/** Real events at Apple carry alerts and a repeat to read; birthdays and feeds do not. */const atApple = (guid: string) => !guid.startsWith("quince:") && !guid.startsWith("pending:");- /** ⌘D: a copy at the same time, its alerts and repeat with it, as Calendar duplicates. */+ /**+ * ⌘D: a copy at the same time, its alerts and repeat with it, as Calendar duplicates. The+ * copy is drawn at once; its alerts and repeat are read from Apple meanwhile, and it is made+ * with them once they come. Read first, the copy appeared a second or two after the key.+ */const duplicate = async (e: CalendarEvent) => {const into = homeFor(e);if (!into) return;const occurrence = e.guid.includes("__");- const [alerts, repeat] = atApple(e.guid)- ? await Promise.all([- api.eventAlerts(e.guid).catch(() => [] as number[]),- occurrence ? Promise.resolve(null) : api.eventRepeat(e.guid).catch(() => null),- ])- : [alertsFor(into, e.allDay), null];+ if (!atApple(e.guid)) {+ await save({ ...draftOf(e), guid: null, calendarGuid: into, alerts: alertsFor(into, e.allDay), alertsChanged: true, repeat: null, repeatChanged: false });+ return;+ }+ const copy: CalendarEvent = { ...e, guid: `pending:copy:${e.guid}:${Date.now()}`, calendarGuid: into, etag: null };+ const draw = (rows: CalendarEvent[]) => [...rows, copy];+ setEvents(draw);+ const release = hold(draw);+ const [alerts, repeat] = await Promise.all([+ api.eventAlerts(e.guid).catch(() => [] as number[]),+ occurrence ? Promise.resolve(null) : api.eventRepeat(e.guid).catch(() => null),+ ]);+ // The stand-in gives way to the copy as it is saved, in the same draw.+ release();+ setEvents((rows) => rows.filter((x) => x.guid !== copy.guid));await save({ ...draftOf(e), guid: null, calendarGuid: into, alerts, alertsChanged: true, repeat, repeatChanged: repeat !== null });};/** ⌘V: the copied event on the selected day, at its own time of day. */@@ -3093,7 +3116,7 @@ function EventPopover({// Any beyond the two shown (made on a Mac) are kept, never dropped by an edit here.set({ alerts: next, alertsChanged: true, alertsDefault: false });}}- options={alerts === undefined ? [{ value: "loading", label: "…" }] : options}+ options={alerts === undefined ? [{ value: "loading", label: "Loading" }] : options}/></div>);@@ -3108,7 +3131,7 @@ function EventPopover({onChange={(v) => set({ repeat: v === "never" ? null : { freq: v as EventRepeat["freq"], interval: 1, count: null }, repeatChanged: true })}options={draft.repeat === undefined- ? [{ value: "loading", label: "…" }]+ ? [{ value: "loading", label: "Loading" }]: [...REPEATS,...(repeatKey(draft.repeat) === "custom" ? [{ value: "custom", label: repeatText(draft.repeat) }] : []),@@ -3437,7 +3460,7 @@ function SubscribeForm({ onDone, onCancel }: {)}<div className="cx-subscribe-actions"><button type="button" className="quiet" onClick={onCancel}>Cancel</button>- <button type="submit" className="primary" disabled={!url.trim() || busy}>{busy ? "Subscribing…" : "Subscribe"}</button>+ <button type="submit" className="primary" disabled={!url.trim() || busy} aria-busy={busy}>Subscribe</button></div></form>);diff --git a/src/styles/reminders.css b/src/styles/reminders.cssindex 5b65aa7..d9e64a8 100644--- a/src/styles/reminders.css+++ b/src/styles/reminders.css@@ -220,12 +220,22 @@grid-template-columns: 20px minmax(0, 1fr) auto;column-gap: 10px;align-items: start;- padding: 8px 14px 8px 0;+ /* The 4px either side of the circle's edge, given back by the margin, leave room for its+ focus ring, which the containment below would otherwise clip. */+ margin-left: -4px;+ padding: 8px 14px 8px 4px;+ /* A row out of view is neither laid out nor painted, so a list of a thousand costs what the+ screenful on show costs. Not an animation and nothing for the compositor: the page draws+ it, as every row here is drawn. Each skipped row holds the height it last had, or a usual+ row's until it has been seen. Its pickers and menus open in a portal, so the containment+ this brings clips none of them. */+ content-visibility: auto;+ contain-intrinsic-size: auto 44px;}.rx-row::after {content: "";position: absolute;- left: 30px;+ left: 34px;right: 0;bottom: 0;height: var(--hairline);@@ -243,7 +253,7 @@background: color-mix(in srgb, var(--accent) 14%, transparent);border-radius: 8px;}-.rx-row.is-subtask { margin-left: 30px; }+.rx-row.is-subtask { margin-left: 26px; }/* The circle is a vector ring (::before) masked over its colour, as Notes' checklist circlesare: the 1.5px CSS border it replaces drew lopsided — heavy on one side, faint on the