Skip to content

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

Reminders shows the sections inside a list

Yashwanth Kamireddi491791480811
diff --git a/.uiverify/assert.mjs b/.uiverify/assert.mjs
index 851c290..86eab38 100644
--- a/.uiverify/assert.mjs
+++ b/.uiverify/assert.mjs
@@ -369,6 +369,56 @@ let failures = 0;
await page.close();
}
+// ── A list shows its own sections ─────────────────────────────────────────────────────
+// Inside a real list, reminders outside any section come first with no heading, then each
+// section under its own heading — how Apple shows it, and how the phone showed "🌅".
+{
+ const page = await ctx.newPage();
+ await page.addInitScript(() => {
+ const r = (guid, title, sectionGuid) => ({ guid, listGuid: "L", title, notes: null, dueAt: null,
+ completedAt: null, priority: 0, flagged: false, parentGuid: null, recurFrequency: null,
+ recurInterval: null, sectionGuid, etag: null });
+ window.__TAURI_INTERNALS__ = {
+ transformCallback: (cb) => cb,
+ invoke: async (cmd) => {
+ if (cmd === "auth_status") return { hasStoredSession: true, signedIn: true };
+ if (cmd === "auth_resume") return true;
+ if (cmd === "account_services") return ["reminders"];
+ if (cmd === "reminder_lists") return [{ guid: "L", title: "Life Goals", colour: "#1badf8", ctag: null, sortOrder: 0, enabled: true }];
+ if (cmd === "reminder_counts") return { today: 0, scheduled: 0, flagged: 0, all: 3, lists: [["L", 3]] };
+ if (cmd === "reminder_sections") return [{ guid: "S", listGuid: "L", title: "Morning Habits", createdAt: 1 }];
+ if (cmd === "reminders_in" || cmd === "reminders_smart")
+ return [r("A", "Loose one", null), r("B", "In the section", "S"), r("C", "In a deleted section", "GONE")];
+ if (cmd === "sync_all" || cmd === "sync_status") return { services: [], asOf: 1, tookMs: 0 };
+ if (cmd === "plugin:event|listen") return 0;
+ return [];
+ },
+ };
+ });
+ await page.goto("http://localhost:4173", { waitUntil: "networkidle" });
+ await page.getByRole("button", { name: "Reminders", exact: true }).click();
+ await page.waitForTimeout(300);
+ await page.locator(".rem-list", { hasText: "Life Goals" }).click();
+ await page.waitForTimeout(400);
+
+ const layout = await page.evaluate(() => {
+ const out = [];
+ for (const el of document.querySelectorAll(".rem-section, .rem-list-items li")) {
+ out.push(el.matches(".rem-section") ? `#${el.textContent.trim()}` : (el.querySelector("input")?.value ?? ""));
+ }
+ return out;
+ });
+ const want = ["Loose one", "In a deleted section", "#Morning Habits", "In the section"];
+ const right = JSON.stringify(layout) === JSON.stringify(want);
+ console.log(
+ right
+ ? "PASS a list shows its sections, loose reminders first"
+ : `FAIL sections laid out as ${JSON.stringify(layout)}`
+ );
+ if (!right) failures++;
+ await page.close();
+}
+
// ── Coming back to the window brings it up to date ────────────────────────────────────
// That is the moment somebody looks for a change they just made on their phone, and between
// background passes the window could be five minutes stale right then. It must refresh on
diff --git a/crates/quince-core/src/reminders.rs b/crates/quince-core/src/reminders.rs
index 3e3677e..a822b39 100644
--- a/crates/quince-core/src/reminders.rs
+++ b/crates/quince-core/src/reminders.rs
@@ -4,6 +4,16 @@ use crate::{Library, Result};
use rusqlite::params;
use serde::{Deserialize, Serialize};
+/// A heading inside a reminders list.
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct ReminderSection {
+ pub guid: String,
+ pub list_guid: String,
+ pub title: String,
+ pub created_at: Option<i64>,
+}
+
/// The most reminders any one view hands to the window at once.
///
/// The plan rules out unbounded payloads crossing into the webview, and "All" on an account
@@ -60,6 +70,10 @@ pub struct Reminder {
/// morning wherever the person is, and that is not something a timestamp can say.
#[serde(default)]
pub timezone: Option<String>,
+ /// The section of its list this reminder sits in, if any. Set from the list's membership
+ /// file, never from the reminder — Apple does not record it on the reminder at all.
+ #[serde(default)]
+ pub section_guid: Option<String>,
}
/// What every entry in the sidebar is holding.
@@ -223,6 +237,91 @@ impl Library {
///
/// Apple's Calendar shows reminders alongside events, which is most of what fills a
/// month for someone who lives in Reminders rather than Calendar.
+ /// Store sections as Apple has them now, and drop the ones Apple says are gone.
+ pub fn put_reminder_sections(
+ &mut self,
+ sections: &[ReminderSection],
+ gone: &[String],
+ ) -> Result<()> {
+ let tx = self.conn.transaction()?;
+ {
+ let mut put = tx.prepare(
+ "INSERT INTO reminder_sections (guid, list_guid, title, created_at, updated_at)
+ VALUES (?1, ?2, ?3, ?4, ?5)
+ ON CONFLICT(guid) DO UPDATE SET
+ list_guid = excluded.list_guid, title = excluded.title,
+ created_at = excluded.created_at, updated_at = excluded.updated_at",
+ )?;
+ let stamp = now();
+ for section in sections {
+ put.execute(params![
+ section.guid,
+ section.list_guid,
+ section.title,
+ section.created_at,
+ stamp
+ ])?;
+ }
+ let mut drop = tx.prepare("DELETE FROM reminder_sections WHERE guid = ?1")?;
+ let mut loose =
+ tx.prepare("UPDATE reminders SET section_guid = NULL WHERE section_guid = ?1")?;
+ for guid in gone {
+ drop.execute(params![guid])?;
+ // A deleted section's reminders stay in the list; they just have no heading.
+ loose.execute(params![guid])?;
+ }
+ }
+ tx.commit()?;
+ Ok(())
+ }
+
+ /// Which section each reminder in a list sits in, as the list's membership file says.
+ ///
+ /// The file is the whole truth for that list, so a reminder it does not place is set
+ /// outside every section rather than left where it was. A placement naming a section
+ /// this library does not hold — one deleted since — is treated the same way, because
+ /// a heading nobody can see is not somewhere to put anything.
+ pub fn set_reminder_sections(
+ &mut self,
+ list_guid: &str,
+ placed: &[(String, String)],
+ ) -> Result<()> {
+ let tx = self.conn.transaction()?;
+ {
+ tx.execute(
+ "UPDATE reminders SET section_guid = NULL WHERE list_guid = ?1",
+ params![list_guid],
+ )?;
+ let mut set = tx.prepare(
+ "UPDATE reminders SET section_guid = ?2
+ WHERE guid = ?1 AND list_guid = ?3
+ AND EXISTS (SELECT 1 FROM reminder_sections WHERE guid = ?2)",
+ )?;
+ for (reminder, section) in placed {
+ set.execute(params![reminder, section, list_guid])?;
+ }
+ }
+ tx.commit()?;
+ Ok(())
+ }
+
+ /// A list's sections, in the order they were made.
+ pub fn reminder_sections(&self, list_guid: &str) -> Result<Vec<ReminderSection>> {
+ let mut stmt = self.conn.prepare(
+ "SELECT guid, list_guid, title, created_at FROM reminder_sections
+ WHERE list_guid = ?1 ORDER BY created_at, title",
+ )?;
+ let rows = stmt.query_map(params![list_guid], |row| {
+ Ok(ReminderSection {
+ guid: row.get(0)?,
+ list_guid: row.get(1)?,
+ title: row.get(2)?,
+ created_at: row.get(3)?,
+ })
+ })?;
+ Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
+ }
+
/// Apple's whole record for one reminder, for the write path that echoes it back.
///
/// Fetched on its own rather than carried on every listed reminder. It averages five
@@ -243,7 +342,7 @@ impl Library {
let mut stmt = self.conn.prepare(
"SELECT r.guid, r.list_guid, r.title, r.notes, r.due_at, r.completed_at,
r.priority, r.flagged, r.parent_guid, r.recur_frequency, r.recur_interval,
- r.etag, r.timezone
+ r.etag, r.timezone, r.section_guid
FROM reminders r
JOIN reminder_lists l ON l.guid = r.list_guid
WHERE l.enabled = 1 AND r.due_at IS NOT NULL
@@ -267,6 +366,7 @@ impl Library {
etag: row.get(11)?,
raw: None,
timezone: row.get(12)?,
+ section_guid: row.get(13)?,
})
})?;
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
@@ -342,7 +442,7 @@ impl Library {
let sql = format!(
"SELECT r.guid, r.list_guid, r.title, r.notes, r.due_at, r.completed_at,
r.priority, r.flagged, r.parent_guid, r.recur_frequency, r.recur_interval,
- r.etag, r.timezone
+ r.etag, r.timezone, r.section_guid
FROM reminders r
JOIN reminder_lists l ON l.guid = r.list_guid
WHERE l.enabled = 1 AND {clause}
@@ -366,6 +466,7 @@ impl Library {
etag: row.get(11)?,
raw: None,
timezone: row.get(12)?,
+ section_guid: row.get(13)?,
})
})?;
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
@@ -525,7 +626,7 @@ impl Library {
pub fn reminders_in(&self, list_guid: &str, include_done: bool) -> Result<Vec<Reminder>> {
let mut stmt = self.conn.prepare(
"SELECT guid, list_guid, title, notes, due_at, completed_at, priority, flagged,
- parent_guid, recur_frequency, recur_interval, etag, timezone
+ parent_guid, recur_frequency, recur_interval, etag, timezone, section_guid
FROM reminders
WHERE list_guid = ?1 AND (?2 = 1 OR completed_at IS NULL)
ORDER BY completed_at IS NOT NULL,
@@ -552,6 +653,7 @@ impl Library {
etag: row.get(11)?,
raw: None,
timezone: row.get(12)?,
+ section_guid: row.get(13)?,
})
},
)?;
@@ -590,6 +692,7 @@ mod tests {
etag: None,
raw: None,
timezone: None,
+ section_guid: None,
}
}
@@ -778,6 +881,7 @@ mod smart_tests {
etag: None,
raw: None,
timezone: None,
+ section_guid: None,
}
}
@@ -918,6 +1022,7 @@ mod count_tests {
etag: None,
raw: None,
timezone: None,
+ section_guid: None,
}
}
@@ -1015,6 +1120,7 @@ mod payload_tests {
etag: Some("e1".into()),
raw: Some(apples_record),
timezone: None,
+ section_guid: None,
};
let sent = serde_json::to_string(&reminder).unwrap();
@@ -1050,6 +1156,7 @@ mod payload_tests {
etag: Some(format!("e{i}")),
raw: Some("y".repeat(5_000)),
timezone: None,
+ section_guid: None,
})
.collect();
let bytes = serde_json::to_vec(&many).unwrap().len();
@@ -1080,6 +1187,7 @@ mod raw_column_tests {
etag: Some("e1".into()),
raw: Some("z".repeat(5_000)),
timezone: None,
+ section_guid: None,
}
}
@@ -1160,6 +1268,7 @@ mod bound_tests {
etag: None,
raw: None,
timezone: None,
+ section_guid: None,
})
.collect();
lib.put_reminders(&rows).unwrap();
@@ -1248,6 +1357,7 @@ mod recurrence_daylight_tests {
etag: None,
raw: None,
timezone: Some(zone.into()),
+ section_guid: None,
}
}
@@ -1306,3 +1416,134 @@ mod recurrence_daylight_tests {
assert!((next - 1_789_000_000 - 86_400).abs() <= 3_600);
}
}
+
+#[cfg(test)]
+mod section_tests {
+ use super::*;
+
+ fn reminder(guid: &str, list: &str) -> Reminder {
+ Reminder {
+ guid: guid.into(),
+ list_guid: list.into(),
+ title: guid.into(),
+ notes: None,
+ due_at: None,
+ completed_at: None,
+ priority: 0,
+ flagged: false,
+ parent_guid: None,
+ recur_frequency: None,
+ recur_interval: None,
+ etag: None,
+ raw: None,
+ timezone: None,
+ section_guid: None,
+ }
+ }
+
+ fn library() -> Library {
+ let mut lib = Library::in_memory().unwrap();
+ lib.put_reminder_lists(&[ReminderList {
+ guid: "List/L".into(),
+ title: "Life Goals".into(),
+ colour: None,
+ ctag: None,
+ sort_order: 0,
+ enabled: true,
+ }])
+ .unwrap();
+ lib.put_reminders(&[
+ reminder("Reminder/A", "List/L"),
+ reminder("Reminder/B", "List/L"),
+ reminder("Reminder/C", "List/L"),
+ ])
+ .unwrap();
+ lib.put_reminder_sections(
+ &[ReminderSection {
+ guid: "ListSection/S".into(),
+ list_guid: "List/L".into(),
+ title: "🌅".into(),
+ created_at: Some(1),
+ }],
+ &[],
+ )
+ .unwrap();
+ lib
+ }
+
+ fn section_of(lib: &Library, guid: &str) -> Option<String> {
+ lib.reminders_in("List/L", true)
+ .unwrap()
+ .into_iter()
+ .find(|r| r.guid == guid)
+ .and_then(|r| r.section_guid)
+ }
+
+ /// The membership file is the whole truth for its list: placed reminders go in, and one
+ /// it no longer places comes back out.
+ #[test]
+ fn the_membership_file_decides_and_is_the_whole_truth() {
+ let mut lib = library();
+ lib.set_reminder_sections(
+ "List/L",
+ &[
+ ("Reminder/A".into(), "ListSection/S".into()),
+ ("Reminder/B".into(), "ListSection/S".into()),
+ ],
+ )
+ .unwrap();
+ assert_eq!(
+ section_of(&lib, "Reminder/A").as_deref(),
+ Some("ListSection/S")
+ );
+ assert_eq!(section_of(&lib, "Reminder/C"), None);
+
+ lib.set_reminder_sections("List/L", &[("Reminder/A".into(), "ListSection/S".into())])
+ .unwrap();
+ assert_eq!(
+ section_of(&lib, "Reminder/B"),
+ None,
+ "moved out on the phone, out here"
+ );
+ }
+
+ /// A sync rewrites reminders wholesale and knows nothing about sections; it must not
+ /// knock them out of the ones they sit in.
+ #[test]
+ fn storing_reminders_again_keeps_their_sections() {
+ let mut lib = library();
+ lib.set_reminder_sections("List/L", &[("Reminder/A".into(), "ListSection/S".into())])
+ .unwrap();
+ lib.put_reminders(&[reminder("Reminder/A", "List/L")])
+ .unwrap();
+ assert_eq!(
+ section_of(&lib, "Reminder/A").as_deref(),
+ Some("ListSection/S")
+ );
+ }
+
+ /// A placement naming a section deleted since is a heading nobody can see.
+ #[test]
+ fn a_placement_in_a_section_that_is_gone_places_nothing() {
+ let mut lib = library();
+ lib.set_reminder_sections(
+ "List/L",
+ &[("Reminder/A".into(), "ListSection/GONE".into())],
+ )
+ .unwrap();
+ assert_eq!(section_of(&lib, "Reminder/A"), None);
+ }
+
+ /// Deleting a section leaves its reminders in the list, without a heading.
+ #[test]
+ fn deleting_a_section_keeps_its_reminders() {
+ let mut lib = library();
+ lib.set_reminder_sections("List/L", &[("Reminder/A".into(), "ListSection/S".into())])
+ .unwrap();
+ lib.put_reminder_sections(&[], &["ListSection/S".into()])
+ .unwrap();
+ assert!(lib.reminder_sections("List/L").unwrap().is_empty());
+ assert_eq!(section_of(&lib, "Reminder/A"), None);
+ assert_eq!(lib.reminders_in("List/L", true).unwrap().len(), 3);
+ }
+}
diff --git a/crates/quince-core/src/schema.rs b/crates/quince-core/src/schema.rs
index c37ee98..2a961e9 100644
--- a/crates/quince-core/src/schema.rs
+++ b/crates/quince-core/src/schema.rs
@@ -278,4 +278,20 @@ pub const MIGRATIONS: &[&str] = &[
value TEXT NOT NULL
);
"#,
+ // 19 — sections inside a reminders list.
+ //
+ // A section is its own record, but which reminder sits in which one is not on the
+ // reminder: it is a file hung off the list, a JSON array of { memberID, groupID } where
+ // groupID is the section. A reminder with no groupID sits outside every section.
+ r#"
+ CREATE TABLE reminder_sections (
+ guid TEXT PRIMARY KEY,
+ list_guid TEXT NOT NULL,
+ title TEXT NOT NULL,
+ created_at INTEGER,
+ updated_at INTEGER NOT NULL
+ ) STRICT;
+ CREATE INDEX reminder_sections_by_list ON reminder_sections (list_guid, created_at);
+ ALTER TABLE reminders ADD COLUMN section_guid TEXT;
+ "#,
];
diff --git a/crates/quince-icloud/src/reminders.rs b/crates/quince-icloud/src/reminders.rs
index 63d5213..6410744 100644
--- a/crates/quince-icloud/src/reminders.rs
+++ b/crates/quince-icloud/src/reminders.rs
@@ -58,6 +58,7 @@ fn reminder_from(v: &Value) -> Option<Reminder> {
// reconstructing one from parsed columns would drop fields we do not model.
raw: serde_json::to_string(v).ok(),
timezone: None,
+ section_guid: None,
})
}
@@ -450,6 +451,7 @@ fn reminder_from_record(record: &Value) -> Option<Reminder> {
// nine in the morning wherever the person is. A repeating reminder stepped without it
// moves an hour on each of the two days a year a clock changes.
timezone: field::string(record, "TimeZone"),
+ section_guid: None,
})
}
@@ -598,6 +600,72 @@ pub struct RemindersFetch {
records: Vec<Value>,
token: Option<String>,
incremental: bool,
+ /// Which reminder sits in which section, per list, from each changed list's membership
+ /// file. Only lists that came back in this walk are here; the rest are unchanged.
+ memberships: std::collections::HashMap<String, Vec<(String, String)>>,
+}
+
+/// The placements in a list's membership file, as record names.
+///
+/// The file is JSON, a `memberships` array of `{ memberID, groupID }` where the member is a
+/// reminder and the group a section, both as bare ids. A reminder with no groupID sits
+/// outside every section and is not a placement. Anything unreadable places nothing, which
+/// leaves the reminders in the list without headings rather than losing them.
+#[must_use]
+pub fn memberships_from(bytes: &[u8]) -> Vec<(String, String)> {
+ let Ok(file) = serde_json::from_slice::<Value>(bytes) else {
+ return Vec::new();
+ };
+ file.get("memberships")
+ .and_then(Value::as_array)
+ .map(|entries| {
+ entries
+ .iter()
+ .filter_map(|m| {
+ let member = m.get("memberID")?.as_str()?;
+ let group = m.get("groupID")?.as_str()?;
+ Some((format!("Reminder/{member}"), format!("ListSection/{group}")))
+ })
+ .collect()
+ })
+ .unwrap_or_default()
+}
+
+/// Fetch the membership file for every list that came back in a walk.
+///
+/// A file that will not download is skipped rather than failing the sync: the reminders are
+/// still right, and their sections simply stay as they were until the next pass.
+async fn fetch_memberships(
+ http: &reqwest::Client,
+ records: &[Value],
+) -> std::collections::HashMap<String, Vec<(String, String)>> {
+ let mut out = std::collections::HashMap::new();
+ for record in records {
+ if field::record_type(record).as_deref() != Some("List") || field::flag(record, "Deleted") {
+ continue;
+ }
+ let Some(name) = field::record_name(record) else {
+ continue;
+ };
+ let Some(url) = record
+ .pointer("/fields/MembershipsOfRemindersInSectionsAsData/value/downloadURL")
+ .and_then(Value::as_str)
+ else {
+ continue;
+ };
+ // The URL is a template; Apple fills the file name in with whatever it is given.
+ let Ok(response) = http.get(url.replace("${f}", "memberships")).send().await else {
+ continue;
+ };
+ if !response.status().is_success() {
+ continue;
+ }
+ let Ok(bytes) = response.bytes().await else {
+ continue;
+ };
+ out.insert(name, memberships_from(&bytes));
+ }
+ out
}
/// Ask Apple what changed. Touches no local state.
@@ -609,7 +677,9 @@ pub async fn fetch_cloudkit(
) -> Result<RemindersFetch> {
let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);
let walk = client.all_records(ZONE, since).await?;
+ let memberships = fetch_memberships(http, &walk.records).await;
Ok(RemindersFetch {
+ memberships,
records: walk.records,
token: walk.token,
// A walk that stopped at its page cap saw only part of the zone, so it cannot be
@@ -627,7 +697,10 @@ pub fn apply_cloudkit(
records,
token,
incremental,
+ memberships,
} = fetched;
+ let mut sections: Vec<quince_core::reminders::ReminderSection> = Vec::new();
+ let mut gone_sections: Vec<String> = Vec::new();
let mut lists: Vec<ReminderList> = Vec::new();
let mut reminders: Vec<Reminder> = Vec::new();
@@ -655,6 +728,7 @@ pub fn apply_cloudkit(
// says which record is gone, and a name only ever belongs to one thing.
if removed {
gone_reminders.push(name.clone());
+ gone_sections.push(name.clone());
gone_lists.push(name);
}
continue;
@@ -685,6 +759,21 @@ pub fn apply_cloudkit(
lists.push(list);
}
}
+ // A heading inside a list. Which reminders sit under it is not on this record —
+ // it is in the list's membership file, fetched alongside the walk.
+ "ListSection" => {
+ if removed {
+ gone_sections.push(name);
+ } else if let Some(list_guid) = field::reference(record, "List") {
+ sections.push(quince_core::reminders::ReminderSection {
+ guid: name,
+ list_guid,
+ title: field::string(record, "DisplayName")
+ .unwrap_or_else(|| "Section".into()),
+ created_at: field::timestamp_seconds(record, "CreationDate"),
+ });
+ }
+ }
"RecurrenceRule" => {
if !removed {
if let Some(target) = field::reference(record, "Reminder") {
@@ -747,6 +836,12 @@ pub fn apply_cloudkit(
if !gone_reminders.is_empty() || !gone_lists.is_empty() {
library.forget_reminders(&gone_reminders, &gone_lists)?;
}
+ // Sections before memberships: a placement is only honoured for a section this library
+ // holds, so the section has to be there first.
+ library.put_reminder_sections(&sections, &gone_sections)?;
+ for (list, placed) in &memberships {
+ library.set_reminder_sections(list, placed)?;
+ }
// A full pass saw everything Apple has, so anything else here is gone. An incremental
// pass saw only changes, where absence means unchanged — pruning there would empty the
// library on the first refresh.
@@ -1708,6 +1803,7 @@ mod write_tests {
etag: Some("tag-3".into()),
raw: None,
timezone: None,
+ section_guid: None,
};
delete_cloudkit(&reqwest::Client::new(), &server.uri(), vec![], &reminder)
.await
@@ -1787,6 +1883,7 @@ mod edit_tests {
etag: Some("tag-1".into()),
raw: None,
timezone: None,
+ section_guid: None,
}
}
@@ -2270,6 +2367,7 @@ mod recurring_tick_tests {
etag: Some("tag".into()),
raw: None,
timezone: None,
+ section_guid: None,
}
}
@@ -2468,6 +2566,7 @@ mod priority_and_move_tests {
etag: Some("tag".into()),
raw: None,
timezone: None,
+ section_guid: None,
}
}
@@ -2647,6 +2746,7 @@ mod tombstone_tests {
etag: None,
raw: None,
timezone: None,
+ section_guid: None,
}])
.unwrap();
library
@@ -2656,6 +2756,7 @@ mod tombstone_tests {
apply_cloudkit(
library,
RemindersFetch {
+ memberships: std::collections::HashMap::new(),
records,
token: Some("t".into()),
incremental: true,
@@ -2715,6 +2816,7 @@ mod tombstone_tests {
apply_cloudkit(
&mut library,
RemindersFetch {
+ memberships: std::collections::HashMap::new(),
records: vec![json!({
"recordName": "List/a",
"recordType": "List",
@@ -2780,6 +2882,7 @@ mod recurrence_write_tests {
etag: Some("tag".into()),
raw: None,
timezone: None,
+ section_guid: None,
}
}
@@ -3102,6 +3205,7 @@ mod other_accounts_tests {
let stored = apply_cloudkit(
&mut lib,
RemindersFetch {
+ memberships: std::collections::HashMap::new(),
records: Vec::new(),
token: Some("t1".into()),
incremental: false,
@@ -3352,3 +3456,40 @@ mod alarm_tests {
assert!(date_components(1_757_000_000, "").is_ok());
}
}
+
+#[cfg(test)]
+mod membership_tests {
+ use super::*;
+
+ /// The shape Apple's membership file actually has, taken from a real list: some entries
+ /// name a section in groupID, some carry no groupID and sit outside every section.
+ #[test]
+ fn placements_are_read_and_the_unplaced_are_left_out() {
+ let file = br#"{"minimumSupportedVersion":20230430,"memberships":[
+ {"memberID":"6B06F5A6","modifiedOn":775500357.6},
+ {"memberID":"D21F787F","modifiedOn":775501474.6,"groupID":"5D09C4F4"},
+ {"groupID":"5D09C4F4","modifiedOn":775501474.6,"memberID":"D2CE1947"}
+ ]}"#;
+ assert_eq!(
+ memberships_from(file),
+ vec![
+ (
+ "Reminder/D21F787F".to_string(),
+ "ListSection/5D09C4F4".to_string()
+ ),
+ (
+ "Reminder/D2CE1947".to_string(),
+ "ListSection/5D09C4F4".to_string()
+ ),
+ ]
+ );
+ }
+
+ #[test]
+ fn a_file_that_cannot_be_read_places_nothing() {
+ assert!(memberships_from(b"").is_empty());
+ assert!(memberships_from(b"not json").is_empty());
+ assert!(memberships_from(br#"{"memberships":"wrong"}"#).is_empty());
+ assert!(memberships_from(br#"{"other":[]}"#).is_empty());
+ }
+}
diff --git a/probe/examples/at_scale.rs b/probe/examples/at_scale.rs
index a6fec97..a96f371 100644
--- a/probe/examples/at_scale.rs
+++ b/probe/examples/at_scale.rs
@@ -53,6 +53,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
// What Apple actually stores per reminder on a real account: about five KB.
raw: Some("z".repeat(5_000)),
timezone: None,
+ section_guid: None,
})
.collect();
let t = Instant::now();
diff --git a/probe/examples/sections.rs b/probe/examples/sections.rs
new file mode 100644
index 0000000..4baa107
--- /dev/null
+++ b/probe/examples/sections.rs
@@ -0,0 +1,42 @@
+//! Throwaway: sync reminders the way the app does and show what landed in each section.
+use anyhow::{anyhow, Result};
+
+#[tokio::main]
+async fn main() -> Result<()> {
+ let dir = std::path::PathBuf::from(std::env::var("HOME")?).join(".local/share/quince-probe");
+ let mut client = quince_auth::Client::new(&dir)?;
+ if !client.resume().await? {
+ return Err(anyhow!("no session"));
+ }
+ let root = client
+ .session()
+ .service_url("ckdatabasews")
+ .ok_or_else(|| anyhow!("no ck"))?;
+ let http = client.http().clone();
+ let store = std::env::temp_dir().join(format!("quince-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&store)?;
+ let mut lib = quince_core::Library::open(&store)?;
+ quince_icloud::reminders::sync_cloudkit(&http, &root, client.service_params(), &mut lib, None)
+ .await?;
+ for list in lib.reminder_lists()? {
+ let sections = lib.reminder_sections(&list.guid)?;
+ if sections.is_empty() {
+ continue;
+ }
+ let items = lib.reminders_in(&list.guid, false)?;
+ println!("{}:", list.title);
+ for s in &sections {
+ let under: Vec<_> = items
+ .iter()
+ .filter(|r| r.section_guid.as_deref() == Some(s.guid.as_str()))
+ .map(|r| r.title.clone())
+ .collect();
+ println!(" [{}] {} reminder(s): {:?}", s.title, under.len(), under);
+ }
+ println!(
+ " (outside any section) {}",
+ items.iter().filter(|r| r.section_guid.is_none()).count()
+ );
+ }
+ Ok(())
+}
diff --git a/probe/src/main.rs b/probe/src/main.rs
index 98c4c0b..8e2c2ee 100644
--- a/probe/src/main.rs
+++ b/probe/src/main.rs
@@ -1369,6 +1369,7 @@ async fn main() -> Result<()> {
etag: None,
raw: None,
timezone: None,
+ section_guid: None,
};
// Subtasks: nest one reminder under another, read it back, free it.
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 590fcca..80b7477 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -376,6 +376,18 @@ async fn reminder_counts(
library.reminder_counts(until).map_err(|e| e.to_string())
}
+/// The headings inside one reminders list, in the order they were made.
+#[tauri::command]
+async fn reminder_sections(
+ list_guid: String,
+ data: State<'_, Data>,
+) -> UiResult<Vec<quince_core::reminders::ReminderSection>> {
+ let library = data.0.lock().await;
+ library
+ .reminder_sections(&list_guid)
+ .map_err(|e| e.to_string())
+}
+
#[tauri::command]
async fn reminder_lists(data: State<'_, Data>) -> UiResult<Vec<ReminderList>> {
let library = data.0.lock().await;
@@ -1406,6 +1418,7 @@ fn main() {
event_delete,
calendar_list,
reminder_lists,
+ reminder_sections,
reminder_counts,
reminders_in,
reminders_due_between,
diff --git a/src/lib/ipc.ts b/src/lib/ipc.ts
index fdbb3f2..d358fd3 100644
--- a/src/lib/ipc.ts
+++ b/src/lib/ipc.ts
@@ -62,6 +62,9 @@ export const api = {
reminderCounts: (until: number) => invoke<ReminderCounts>("reminder_counts", { until }),
reminderLists: () => invoke<ReminderList[]>("reminder_lists"),
+ /** The headings inside one list, in the order they were made. */
+ reminderSections: (listGuid: string) =>
+ invoke<ReminderSection[]>("reminder_sections", { listGuid }),
remindersIn: (listGuid: string, includeDone: boolean) =>
invoke<Reminder[]>("reminders_in", { listGuid, includeDone }),
remindersDueBetween: (from: number, to: number) =>
@@ -195,6 +198,14 @@ export type ReminderList = {
enabled: boolean;
};
+/** A heading inside a reminders list. */
+export type ReminderSection = {
+ guid: string;
+ listGuid: string;
+ title: string;
+ createdAt: number | null;
+};
+
export type SmartList = "today" | "scheduled" | "flagged" | "all";
/** What every entry in the Reminders sidebar is holding. */
@@ -249,6 +260,8 @@ export type Reminder = {
/** Apple's repeat frequency: 0 daily, 1 weekly, 2 monthly, 3 yearly. null if it never repeats. */
recurFrequency: number | null;
recurInterval: number | null;
+ /** The section of its list this sits in, if any. */
+ sectionGuid?: string | null;
etag: string | null;
};
diff --git a/src/screens/RemindersView.tsx b/src/screens/RemindersView.tsx
index 7d4d573..2549822 100644
--- a/src/screens/RemindersView.tsx
+++ b/src/screens/RemindersView.tsx
@@ -5,6 +5,7 @@ import {
messageOf,
type Reminder,
type ReminderList,
+ type ReminderSection,
type ReminderCounts,
type SmartList,
} from "../lib/ipc";
@@ -159,6 +160,8 @@ export function RemindersView() {
const { revision } = useSync();
/** What each sidebar entry is holding. Apple puts a number on every one. */
const [counts, setCounts] = useState<ReminderCounts | null>(null);
+ /** The headings inside the list that is open, when a real list is open. */
+ const [listSections, setListSections] = useState<ReminderSection[]>([]);
/** A repeating reminder that was just ticked forward, and where it landed. */
const [moved, setMoved] = useState<{ guid: string; text: string } | null>(
null,
@@ -177,6 +180,23 @@ export function RemindersView() {
setLoaded(true);
}, []);
+ useEffect(() => {
+ if (selection.type !== "list") return setListSections([]);
+ let cancelled = false;
+ api
+ .reminderSections(selection.guid)
+ .then((found) => {
+ if (!cancelled) setListSections(Array.isArray(found) ? found : []);
+ })
+ .catch(() => {
+ // Without sections the list still shows every reminder, just without headings.
+ if (!cancelled) setListSections([]);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [selection, revision]);
+
const readItems = useCallback(async (): Promise<Reminder[]> => {
const found =
selection.type === "smart"
@@ -460,8 +480,26 @@ export function RemindersView() {
(selection as { kind: SmartList }).kind !== "flagged";
const sections = useMemo(() => {
- if (inList)
- return [{ key: "all", heading: null, colour: null, dated: false, rows: threaded }];
+ if (inList) {
+ // Inside a real list the grouping is the list's own sections, which is how Apple shows
+ // it: reminders outside any section first with no heading, then each section in the
+ // order it was made. A reminder placed in a section that is not here — one deleted
+ // since — falls back to the loose ones rather than vanishing.
+ const known = new Set(listSections.map((s) => s.guid));
+ const loose = threaded.filter(
+ (row) => !row.reminder.sectionGuid || !known.has(row.reminder.sectionGuid)
+ );
+ return [
+ { key: "loose", heading: null, colour: null, dated: false, rows: loose },
+ ...listSections.map((section) => ({
+ key: section.guid,
+ heading: section.title,
+ colour: null,
+ dated: false,
+ rows: threaded.filter((row) => row.reminder.sectionGuid === section.guid),
+ })),
+ ];
+ }
const kind = (selection as { kind: SmartList }).kind;
const now = new Date();
@@ -553,7 +591,7 @@ export function RemindersView() {
dated: false,
rows,
}));
- }, [threaded, inList, selection, lists]);
+ }, [threaded, inList, selection, lists, listSections]);
return (
<div className="rem">