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: editing, flagging, due dates and Apple's smart lists

Yashwanth Kamireddi85516c697dbf
diff --git a/.uiverify/a11y.mjs b/.uiverify/a11y.mjs
index 7b33aed..9f7aa4a 100644
--- a/.uiverify/a11y.mjs
+++ b/.uiverify/a11y.mjs
@@ -33,6 +33,8 @@ function installStub({ screen, services, twoFactor }) {
case "reminder_create": return null;
case "reminder_delete": return null;
case "reminder_set_done": return null;
+ case "reminder_edit": return null;
+ case "reminders_smart": return [];
case "note_folders": return [];
case "notes_in": return [];
case "notes_last_synced": return Math.floor(Date.now() / 1000);
diff --git a/.uiverify/assert.mjs b/.uiverify/assert.mjs
index f14e4ba..52f1781 100644
--- a/.uiverify/assert.mjs
+++ b/.uiverify/assert.mjs
@@ -21,6 +21,8 @@ await ctx.addInitScript(({ services }) => {
if (cmd === "reminder_create") return null;
if (cmd === "reminder_delete") return null;
if (cmd === "reminder_set_done") return null;
+ if (cmd === "reminder_edit") return null;
+ if (cmd === "reminders_smart") return [];
if (cmd === "note_folders") return [];
if (cmd === "notes_in") return [];
if (cmd === "notes_last_synced") return Math.floor(Date.now() / 1000);
diff --git a/.uiverify/keyboard.mjs b/.uiverify/keyboard.mjs
index c5f980d..a8bd83e 100644
--- a/.uiverify/keyboard.mjs
+++ b/.uiverify/keyboard.mjs
@@ -32,6 +32,8 @@ function installStub({ screen, services, twoFactor }) {
case "reminder_create": return null;
case "reminder_delete": return null;
case "reminder_set_done": return null;
+ case "reminder_edit": return null;
+ case "reminders_smart": return [];
case "note_folders": return [];
case "notes_in": return [];
case "notes_last_synced": return Math.floor(Date.now() / 1000);
diff --git a/.uiverify/shots.mjs b/.uiverify/shots.mjs
index f2f70ac..7cc8591 100644
--- a/.uiverify/shots.mjs
+++ b/.uiverify/shots.mjs
@@ -120,6 +120,8 @@ function installStub({ screen, services, twoFactor, calendarFixture, notesFixtur
case "reminder_create": return null;
case "reminder_delete": return null;
case "reminder_set_done": return null;
+ case "reminder_edit": return null;
+ case "reminders_smart": return [];
case "note_folders": return !notesFixture ? [] : noteFolders;
case "notes_in": return !notesFixture ? [] : noteList;
case "notes_last_synced": return Math.floor(Date.now() / 1000);
diff --git a/crates/quince-core/src/reminders.rs b/crates/quince-core/src/reminders.rs
index 1ebc1de..6c859c6 100644
--- a/crates/quince-core/src/reminders.rs
+++ b/crates/quince-core/src/reminders.rs
@@ -26,6 +26,8 @@ pub struct Reminder {
/// `None` while outstanding.
pub completed_at: Option<i64>,
pub priority: i64,
+ #[serde(default)]
+ pub flagged: bool,
pub etag: Option<String>,
/// Apple's original JSON for this reminder, kept verbatim so a write can echo every
/// field back rather than only the ones we model.
@@ -33,6 +35,16 @@ pub struct Reminder {
pub raw: Option<String>,
}
+/// Apple's built-in views over every list.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum SmartList {
+ Today,
+ Scheduled,
+ Flagged,
+ All,
+}
+
impl Reminder {
#[must_use]
pub fn is_done(&self) -> bool {
@@ -109,7 +121,7 @@ impl Library {
pub fn reminders_due_between(&self, from: i64, to: i64) -> Result<Vec<Reminder>> {
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.etag, r.raw
+ r.priority, r.flagged, r.etag, r.raw
FROM reminders r
JOIN reminder_lists l ON l.guid = r.list_guid
WHERE l.enabled = 1 AND r.due_at IS NOT NULL
@@ -125,8 +137,53 @@ impl Library {
due_at: row.get(4)?,
completed_at: row.get(5)?,
priority: row.get(6)?,
- etag: row.get(7)?,
- raw: row.get(8)?,
+ flagged: row.get::<_, i64>(7)? != 0,
+ etag: row.get(8)?,
+ raw: row.get(9)?,
+ })
+ })?;
+ Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
+ }
+
+ /// One of Apple's smart lists.
+ ///
+ /// These are the entry points people actually use: what is due today, everything with a
+ /// date, and whatever has been flagged. They are queries rather than stored lists, which
+ /// is what lets them stay correct as the clock moves.
+ pub fn reminders_smart(&self, kind: SmartList, until: i64) -> Result<Vec<Reminder>> {
+ // Only Today is bounded by the clock, so only Today binds a value — binding one
+ // regardless is what SQLite rejects as a parameter-count mismatch.
+ let (clause, args): (&str, Vec<i64>) = match kind {
+ // Overdue counts as today: Apple shows it there rather than hiding it in the past.
+ SmartList::Today => (
+ "r.completed_at IS NULL AND r.due_at IS NOT NULL AND r.due_at < ?1",
+ vec![until],
+ ),
+ SmartList::Scheduled => ("r.completed_at IS NULL AND r.due_at IS NOT NULL", vec![]),
+ SmartList::Flagged => ("r.completed_at IS NULL AND r.flagged = 1", vec![]),
+ SmartList::All => ("r.completed_at IS NULL", vec![]),
+ };
+ let sql = format!(
+ "SELECT r.guid, r.list_guid, r.title, r.notes, r.due_at, r.completed_at,
+ r.priority, r.flagged, r.etag, r.raw
+ FROM reminders r
+ JOIN reminder_lists l ON l.guid = r.list_guid
+ WHERE l.enabled = 1 AND {clause}
+ ORDER BY r.due_at IS NULL, r.due_at, r.priority DESC, r.title"
+ );
+ let mut stmt = self.conn.prepare(&sql)?;
+ let rows = stmt.query_map(rusqlite::params_from_iter(args), |row| {
+ Ok(Reminder {
+ guid: row.get(0)?,
+ list_guid: row.get(1)?,
+ title: row.get(2)?,
+ notes: row.get(3)?,
+ due_at: row.get(4)?,
+ completed_at: row.get(5)?,
+ priority: row.get(6)?,
+ flagged: row.get::<_, i64>(7)? != 0,
+ etag: row.get(8)?,
+ raw: row.get(9)?,
})
})?;
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
@@ -189,12 +246,13 @@ impl Library {
{
let mut stmt = tx.prepare(
"INSERT INTO reminders (guid, list_guid, title, notes, due_at, completed_at,
- priority, etag, raw, updated_at)
- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)
+ priority, flagged, etag, raw, updated_at)
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)
ON CONFLICT(guid) DO UPDATE SET
list_guid = excluded.list_guid, title = excluded.title,
notes = excluded.notes, due_at = excluded.due_at,
completed_at = excluded.completed_at, priority = excluded.priority,
+ flagged = excluded.flagged,
etag = excluded.etag, raw = excluded.raw,
updated_at = excluded.updated_at",
)?;
@@ -208,6 +266,7 @@ impl Library {
r.due_at,
r.completed_at,
r.priority,
+ i64::from(r.flagged),
r.etag,
r.raw,
stamp
@@ -242,7 +301,8 @@ impl Library {
/// is useless.
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, etag, raw
+ "SELECT guid, list_guid, title, notes, due_at, completed_at, priority, flagged,
+ etag, raw
FROM reminders
WHERE list_guid = ?1 AND (?2 = 1 OR completed_at IS NULL)
ORDER BY completed_at IS NOT NULL,
@@ -259,8 +319,9 @@ impl Library {
due_at: row.get(4)?,
completed_at: row.get(5)?,
priority: row.get(6)?,
- etag: row.get(7)?,
- raw: row.get(8)?,
+ flagged: row.get::<_, i64>(7)? != 0,
+ etag: row.get(8)?,
+ raw: row.get(9)?,
})
})?;
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
@@ -291,6 +352,7 @@ mod tests {
due_at: due,
completed_at: done,
priority: 0,
+ flagged: false,
etag: None,
raw: None,
}
@@ -443,3 +505,132 @@ mod tests {
);
}
}
+
+#[cfg(test)]
+mod smart_tests {
+ use super::*;
+
+ const DAY_START: i64 = 1_757_000_000;
+ const DAY_END: i64 = DAY_START + 86_400;
+
+ fn seeded() -> Library {
+ let mut lib = Library::in_memory().unwrap();
+ lib.put_reminder_lists(&[ReminderList {
+ guid: "l1".into(),
+ title: "Daily".into(),
+ colour: None,
+ ctag: None,
+ sort_order: 0,
+ enabled: true,
+ }])
+ .unwrap();
+ lib
+ }
+
+ fn reminder(guid: &str, due: Option<i64>, flagged: bool, done: Option<i64>) -> Reminder {
+ Reminder {
+ guid: guid.into(),
+ list_guid: "l1".into(),
+ title: guid.into(),
+ notes: None,
+ due_at: due,
+ completed_at: done,
+ priority: 0,
+ flagged,
+ etag: None,
+ raw: None,
+ }
+ }
+
+ /// Overdue belongs in Today: Apple shows it there rather than hiding it in the past.
+ #[test]
+ fn today_includes_overdue_and_excludes_the_future() {
+ let mut lib = seeded();
+ lib.put_reminders(&[
+ reminder("overdue", Some(DAY_START - 200_000), false, None),
+ reminder("today", Some(DAY_START + 3600), false, None),
+ reminder("tomorrow", Some(DAY_END + 3600), false, None),
+ reminder("undated", None, false, None),
+ reminder(
+ "done-today",
+ Some(DAY_START + 10),
+ false,
+ Some(DAY_START + 20),
+ ),
+ ])
+ .unwrap();
+
+ let guids: Vec<String> = lib
+ .reminders_smart(SmartList::Today, DAY_END)
+ .unwrap()
+ .into_iter()
+ .map(|r| r.guid)
+ .collect();
+ assert_eq!(guids, vec!["overdue", "today"]);
+ }
+
+ #[test]
+ fn scheduled_is_everything_dated_and_still_open() {
+ let mut lib = seeded();
+ lib.put_reminders(&[
+ reminder("dated", Some(DAY_END + 99_999), false, None),
+ reminder("undated", None, false, None),
+ ])
+ .unwrap();
+ let found = lib.reminders_smart(SmartList::Scheduled, DAY_END).unwrap();
+ assert_eq!(found.len(), 1);
+ assert_eq!(found[0].guid, "dated");
+ }
+
+ #[test]
+ fn flagged_shows_only_what_is_flagged_and_open() {
+ let mut lib = seeded();
+ lib.put_reminders(&[
+ reminder("flag", None, true, None),
+ reminder("flag-done", None, true, Some(1)),
+ reminder("plain", None, false, None),
+ ])
+ .unwrap();
+ let found = lib.reminders_smart(SmartList::Flagged, DAY_END).unwrap();
+ assert_eq!(found.len(), 1);
+ assert_eq!(found[0].guid, "flag");
+ }
+
+ /// Hiding a list must hide it from the smart lists too, or the counts disagree.
+ #[test]
+ fn a_disabled_list_is_excluded_everywhere() {
+ let mut lib = seeded();
+ lib.put_reminders(&[reminder("a", Some(DAY_START), true, None)])
+ .unwrap();
+ assert_eq!(
+ lib.reminders_smart(SmartList::All, DAY_END).unwrap().len(),
+ 1
+ );
+
+ lib.put_reminder_lists(&[ReminderList {
+ guid: "l1".into(),
+ title: "Daily".into(),
+ colour: None,
+ ctag: None,
+ sort_order: 0,
+ enabled: false,
+ }])
+ .unwrap();
+ for kind in [
+ SmartList::Today,
+ SmartList::Scheduled,
+ SmartList::Flagged,
+ SmartList::All,
+ ] {
+ assert!(lib.reminders_smart(kind, DAY_END).unwrap().is_empty());
+ }
+ }
+
+ #[test]
+ fn flagging_round_trips_through_storage() {
+ let mut lib = seeded();
+ lib.put_reminders(&[reminder("a", None, true, None)])
+ .unwrap();
+ assert!(lib.reminders_in("l1", true).unwrap()[0].flagged);
+ }
+}
diff --git a/crates/quince-core/src/schema.rs b/crates/quince-core/src/schema.rs
index ad1ce90..a729cfb 100644
--- a/crates/quince-core/src/schema.rs
+++ b/crates/quince-core/src/schema.rs
@@ -165,4 +165,9 @@ pub const MIGRATIONS: &[&str] = &[
-- Browsing is always "what is inside this folder", ordered folders first.
CREATE INDEX drive_by_parent ON drive_items (parent_id, kind, name);
"#,
+ // 7 — flagging, which Apple surfaces as one of its smart lists.
+ r#"
+ ALTER TABLE reminders ADD COLUMN flagged INTEGER NOT NULL DEFAULT 0;
+ CREATE INDEX reminders_flagged ON reminders (flagged, completed_at);
+ "#,
];
diff --git a/crates/quince-icloud/src/reminders.rs b/crates/quince-icloud/src/reminders.rs
index ac15de4..01a802d 100644
--- a/crates/quince-icloud/src/reminders.rs
+++ b/crates/quince-icloud/src/reminders.rs
@@ -47,6 +47,9 @@ fn reminder_from(v: &Value) -> Option<Reminder> {
due_at: optional_date(v, "dueDate"),
completed_at: optional_date(v, "completedDate"),
priority: v.get("priority").and_then(Value::as_i64).unwrap_or(0),
+ // The legacy endpoint does not carry a flag; CloudKit does, and that is the path
+ // this account actually uses.
+ flagged: v.get("flagged").and_then(Value::as_bool).unwrap_or(false),
etag: string(v, "etag"),
// Keep Apple's payload verbatim: a write echoes the whole task back, and
// reconstructing one from parsed columns would drop fields we do not model.
@@ -424,6 +427,7 @@ fn reminder_from_record(record: &Value) -> Option<Reminder> {
.flatten()
.or(if completed { Some(0) } else { None }),
priority: field::int(record, "Priority").unwrap_or(0),
+ flagged: field::flag(record, "Flagged"),
etag: record
.get("recordChangeTag")
.and_then(Value::as_str)
@@ -720,6 +724,119 @@ pub async fn delete_cloudkit(
Ok(())
}
+/// What to change about a reminder. Anything left `None` is untouched.
+///
+/// Written as one request so a title and a due date set together cannot half-apply.
+#[derive(Debug, Default, Clone, serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ReminderEdit {
+ pub title: Option<String>,
+ /// `Some(None)` clears the notes; `None` leaves them alone.
+ pub notes: Option<Option<String>>,
+ /// Unix seconds. `Some(None)` clears the due date.
+ pub due_at: Option<Option<i64>>,
+ pub flagged: Option<bool>,
+ pub completed: Option<bool>,
+}
+
+impl ReminderEdit {
+ fn is_empty(&self) -> bool {
+ self.title.is_none()
+ && self.notes.is_none()
+ && self.due_at.is_none()
+ && self.flagged.is_none()
+ && self.completed.is_none()
+ }
+}
+
+/// Apply an edit to a reminder.
+///
+/// Sends only the fields that changed, guarded by the record's change tag, so a reminder
+/// edited on the phone since we read it is refused rather than overwritten.
+pub async fn edit_cloudkit(
+ http: &reqwest::Client,
+ ckdatabasews_root: &str,
+ params: Vec<(String, String)>,
+ reminder: &Reminder,
+ edit: &ReminderEdit,
+) -> Result<()> {
+ if edit.is_empty() {
+ return Ok(());
+ }
+
+ let mut fields = serde_json::Map::new();
+
+ if let Some(title) = &edit.title {
+ let title = title.trim();
+ if title.is_empty() {
+ return Err(Error::Protocol("a reminder needs a title".into()));
+ }
+ fields.insert(
+ "TitleDocument".into(),
+ serde_json::json!({
+ "type": "ENCRYPTED_BYTES",
+ "value": crate::ckdocument::text_to_base64(title),
+ }),
+ );
+ }
+
+ if let Some(notes) = &edit.notes {
+ // Clearing writes an empty document rather than removing the field: Apple's clients
+ // expect it to exist.
+ let text = notes.as_deref().unwrap_or("");
+ fields.insert(
+ "NotesDocument".into(),
+ serde_json::json!({
+ "type": "ENCRYPTED_BYTES",
+ "value": crate::ckdocument::text_to_base64(text),
+ }),
+ );
+ }
+
+ if let Some(due) = &edit.due_at {
+ fields.insert(
+ "DueDate".into(),
+ match due {
+ Some(seconds) => serde_json::json!({
+ "type": "TIMESTAMP", "value": seconds.saturating_mul(1000)
+ }),
+ None => serde_json::json!({ "type": "TIMESTAMP", "value": null }),
+ },
+ );
+ }
+
+ if let Some(flagged) = edit.flagged {
+ fields.insert(
+ "Flagged".into(),
+ serde_json::json!({ "type": "NUMBER_INT64", "value": i64::from(flagged) }),
+ );
+ }
+
+ if let Some(completed) = edit.completed {
+ fields.insert(
+ "Completed".into(),
+ serde_json::json!({ "type": "NUMBER_INT64", "value": i64::from(completed) }),
+ );
+ }
+
+ fields.insert(
+ "LastModifiedDate".into(),
+ serde_json::json!({ "type": "TIMESTAMP", "value": now_millis() }),
+ );
+
+ let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);
+ client
+ .update_record(
+ ZONE,
+ &reminder.guid,
+ "Reminder",
+ reminder.etag.as_deref(),
+ Value::Object(fields),
+ )
+ .await?;
+ Ok(())
+}
+
/// Tick a CloudKit reminder off, or put it back.
///
/// Sends only the fields that change, guarded by the record's change tag, so a reminder
@@ -1093,6 +1210,7 @@ mod write_tests {
due_at: None,
completed_at: None,
priority: 0,
+ flagged: false,
etag: Some("tag-3".into()),
raw: None,
};
@@ -1113,3 +1231,198 @@ mod write_tests {
);
}
}
+
+#[cfg(test)]
+mod edit_tests {
+ use super::*;
+ use serde_json::json;
+ use wiremock::matchers::{method, path_regex};
+ use wiremock::{Mock, MockServer, ResponseTemplate};
+
+ async fn accepting() -> MockServer {
+ let server = MockServer::start().await;
+ Mock::given(method("POST"))
+ .and(path_regex(r".*/records/modify$"))
+ .respond_with(
+ ResponseTemplate::new(200)
+ .set_body_json(json!({ "records": [{ "recordName": "Reminder/1" }] })),
+ )
+ .mount(&server)
+ .await;
+ server
+ }
+
+ fn reminder() -> Reminder {
+ Reminder {
+ guid: "Reminder/1".into(),
+ list_guid: "List/a".into(),
+ title: "Old".into(),
+ notes: None,
+ due_at: None,
+ completed_at: None,
+ priority: 0,
+ flagged: false,
+ etag: Some("tag-1".into()),
+ raw: None,
+ }
+ }
+
+ async fn sent(server: &MockServer) -> Value {
+ let requests = server.received_requests().await.unwrap();
+ let body: Value = serde_json::from_slice(&requests[0].body).unwrap();
+ body["operations"][0]["record"]["fields"].clone()
+ }
+
+ #[tokio::test]
+ async fn a_new_title_is_written_so_it_reads_back() {
+ let server = accepting().await;
+ edit_cloudkit(
+ &reqwest::Client::new(),
+ &server.uri(),
+ vec![],
+ &reminder(),
+ &ReminderEdit {
+ title: Some("🥛 Buy oat milk".into()),
+ ..Default::default()
+ },
+ )
+ .await
+ .unwrap();
+
+ let fields = sent(&server).await;
+ let encoded = fields["TitleDocument"]["value"].as_str().unwrap();
+ assert_eq!(
+ crate::ckdocument::text_from_base64(encoded).as_deref(),
+ Some("🥛 Buy oat milk")
+ );
+ assert!(
+ fields.get("DueDate").is_none(),
+ "untouched fields must not be sent"
+ );
+ }
+
+ /// Seconds in, milliseconds out — a due date landing on the wrong day is worse than none.
+ #[tokio::test]
+ async fn a_due_date_is_written_in_milliseconds_and_can_be_cleared() {
+ let server = accepting().await;
+ edit_cloudkit(
+ &reqwest::Client::new(),
+ &server.uri(),
+ vec![],
+ &reminder(),
+ &ReminderEdit {
+ due_at: Some(Some(1_757_000_000)),
+ ..Default::default()
+ },
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ sent(&server).await["DueDate"]["value"],
+ 1_757_000_000_000_i64
+ );
+
+ let clearing = accepting().await;
+ edit_cloudkit(
+ &reqwest::Client::new(),
+ &clearing.uri(),
+ vec![],
+ &reminder(),
+ &ReminderEdit {
+ due_at: Some(None),
+ ..Default::default()
+ },
+ )
+ .await
+ .unwrap();
+ assert!(sent(&clearing).await["DueDate"]["value"].is_null());
+ }
+
+ #[tokio::test]
+ async fn notes_can_be_set_and_cleared() {
+ let server = accepting().await;
+ edit_cloudkit(
+ &reqwest::Client::new(),
+ &server.uri(),
+ vec![],
+ &reminder(),
+ &ReminderEdit {
+ notes: Some(Some("bring a bag".into())),
+ ..Default::default()
+ },
+ )
+ .await
+ .unwrap();
+ let encoded = sent(&server).await["NotesDocument"]["value"]
+ .as_str()
+ .unwrap()
+ .to_string();
+ assert_eq!(
+ crate::ckdocument::text_from_base64(&encoded).as_deref(),
+ Some("bring a bag")
+ );
+ }
+
+ #[tokio::test]
+ async fn an_empty_title_is_refused_before_anything_is_sent() {
+ let server = accepting().await;
+ assert!(edit_cloudkit(
+ &reqwest::Client::new(),
+ &server.uri(),
+ vec![],
+ &reminder(),
+ &ReminderEdit {
+ title: Some(" ".into()),
+ ..Default::default()
+ },
+ )
+ .await
+ .is_err());
+ assert!(server.received_requests().await.unwrap().is_empty());
+ }
+
+ /// An edit that changes nothing should not cost a request.
+ #[tokio::test]
+ async fn an_empty_edit_does_nothing() {
+ let server = accepting().await;
+ edit_cloudkit(
+ &reqwest::Client::new(),
+ &server.uri(),
+ vec![],
+ &reminder(),
+ &ReminderEdit::default(),
+ )
+ .await
+ .unwrap();
+ assert!(server.received_requests().await.unwrap().is_empty());
+ }
+
+ #[tokio::test]
+ async fn several_changes_travel_in_one_request() {
+ let server = accepting().await;
+ edit_cloudkit(
+ &reqwest::Client::new(),
+ &server.uri(),
+ vec![],
+ &reminder(),
+ &ReminderEdit {
+ title: Some("Renamed".into()),
+ due_at: Some(Some(1_757_000_000)),
+ flagged: Some(true),
+ ..Default::default()
+ },
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(
+ server.received_requests().await.unwrap().len(),
+ 1,
+ "one write, not three"
+ );
+ let fields = sent(&server).await;
+ assert!(fields.get("TitleDocument").is_some());
+ assert_eq!(fields["DueDate"]["value"], 1_757_000_000_000_i64);
+ assert_eq!(fields["Flagged"]["value"], 1);
+ }
+}
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 4b8c56d..243386c 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -6,7 +6,7 @@ use quince_core::calendar::{Calendar, Event};
use quince_core::contacts::Contact;
use quince_core::drive::DriveItem;
use quince_core::notes::{Note, NoteFolder};
-use quince_core::reminders::{Reminder, ReminderList};
+use quince_core::reminders::{Reminder, ReminderList, SmartList};
use quince_core::Library;
use serde::Serialize;
use std::path::PathBuf;
@@ -369,6 +369,53 @@ async fn reminder_delete(
Ok(())
}
+/// Apply an edit — title, notes, due date, flag, completion — in one write.
+#[tauri::command]
+async fn reminder_edit(
+ guid: String,
+ list_guid: String,
+ edit: quince_icloud::reminders::ReminderEdit,
+ auth: State<'_, Auth>,
+ data: State<'_, Data>,
+) -> UiResult<()> {
+ let (http, root, params) = cloudkit_context(&auth).await?;
+
+ let reminder = {
+ let library = data.0.lock().await;
+ library
+ .reminders_in(&list_guid, true)
+ .map_err(|e| e.to_string())?
+ .into_iter()
+ .find(|r| r.guid == guid)
+ .ok_or("That reminder is no longer in the local library.")?
+ };
+
+ quince_icloud::reminders::edit_cloudkit(&http, &root, params.clone(), &reminder, &edit)
+ .await
+ .map_err(|e| e.to_string())?;
+
+ let mut library = data.0.lock().await;
+ let since = library.sync_token("reminders").map_err(|e| e.to_string())?;
+ quince_icloud::reminders::sync_cloudkit(&http, &root, params, &mut library, since.as_deref())
+ .await
+ .map_err(|e| e.to_string())?;
+ Ok(())
+}
+
+/// One of Apple's smart lists. `until` is the end of today in the viewer's own timezone,
+/// which the interface knows and the backend does not.
+#[tauri::command]
+async fn reminders_smart(
+ kind: SmartList,
+ until: i64,
+ data: State<'_, Data>,
+) -> UiResult<Vec<Reminder>> {
+ let library = data.0.lock().await;
+ library
+ .reminders_smart(kind, until)
+ .map_err(|e| e.to_string())
+}
+
#[tauri::command]
async fn reminders_last_synced(data: State<'_, Data>) -> UiResult<Option<i64>> {
let library = data.0.lock().await;
@@ -523,6 +570,8 @@ fn main() {
reminders_due_between,
reminder_create,
reminder_delete,
+ reminder_edit,
+ reminders_smart,
notes_sync,
note_folders,
notes_in,
diff --git a/src/lib/ipc.ts b/src/lib/ipc.ts
index bd137f2..e48ff17 100644
--- a/src/lib/ipc.ts
+++ b/src/lib/ipc.ts
@@ -40,6 +40,10 @@ export const api = {
invoke<Reminder[]>("reminders_due_between", { from, to }),
reminderSetDone: (guid: string, listGuid: string, done: boolean) =>
invoke<void>("reminder_set_done", { guid, listGuid, done }),
+ reminderEdit: (guid: string, listGuid: string, edit: ReminderEdit) =>
+ invoke<void>("reminder_edit", { guid, listGuid, edit }),
+ remindersSmart: (kind: SmartList, until: number) =>
+ invoke<Reminder[]>("reminders_smart", { kind, until }),
reminderCreate: (listGuid: string, title: string) =>
invoke<void>("reminder_create", { listGuid, title }),
reminderDelete: (guid: string, listGuid: string) =>
@@ -95,6 +99,17 @@ export type ReminderList = {
enabled: boolean;
};
+export type SmartList = "today" | "scheduled" | "flagged" | "all";
+
+/** Anything omitted is left untouched; `null` clears a field. */
+export type ReminderEdit = {
+ title?: string;
+ notes?: string | null;
+ dueAt?: number | null;
+ flagged?: boolean;
+ completed?: boolean;
+};
+
export type Reminder = {
guid: string;
listGuid: string;
@@ -104,6 +119,7 @@ export type Reminder = {
/** null while outstanding */
completedAt: number | null;
priority: number;
+ flagged: boolean;
etag: string | null;
};
diff --git a/src/screens/RemindersView.tsx b/src/screens/RemindersView.tsx
index c736447..37c5f21 100644
--- a/src/screens/RemindersView.tsx
+++ b/src/screens/RemindersView.tsx
@@ -1,16 +1,48 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-import { api, messageOf, type Reminder, type ReminderList } from "../lib/ipc";
+import {
+ api,
+ messageOf,
+ type Reminder,
+ type ReminderList,
+ type SmartList,
+} from "../lib/ipc";
-const dueLabel = (seconds: number) => {
+/** Apple's built-in views, which is how most people enter Reminders. */
+const SMART: { kind: SmartList; title: string }[] = [
+ { kind: "today", title: "Today" },
+ { kind: "scheduled", title: "Scheduled" },
+ { kind: "flagged", title: "Flagged" },
+ { kind: "all", title: "All" },
+];
+
+/** End of today in the viewer's own timezone — the interface knows it, the backend doesn't. */
+function endOfToday(): number {
+ const d = new Date();
+ return Math.floor(new Date(d.getFullYear(), d.getMonth(), d.getDate() + 1).getTime() / 1000);
+}
+
+function dueLabel(seconds: number): { text: string; overdue: boolean } {
const due = new Date(seconds * 1000);
- const today = new Date();
- const sameDay =
- due.getFullYear() === today.getFullYear() &&
- due.getMonth() === today.getMonth() &&
- due.getDate() === today.getDate();
- if (sameDay) return `Today ${due.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" })}`;
- return due.toLocaleDateString(undefined, { day: "numeric", month: "short" });
-};
+ const now = new Date();
+ const midnight = new Date(now.getFullYear(), now.getMonth(), now.getDate());
+ const days = Math.floor((due.getTime() - midnight.getTime()) / 86_400_000);
+ const time = due.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" });
+ if (days < 0) return { text: due.toLocaleDateString(undefined, { day: "numeric", month: "short" }), overdue: true };
+ if (days === 0) return { text: `Today ${time}`, overdue: due.getTime() < now.getTime() };
+ if (days === 1) return { text: `Tomorrow ${time}`, overdue: false };
+ return {
+ text: due.toLocaleDateString(undefined, { day: "numeric", month: "short" }),
+ overdue: false,
+ };
+}
+
+/** `YYYY-MM-DDTHH:mm` for a datetime-local input, in local time. */
+function toInputValue(seconds: number | null): string {
+ if (seconds === null) return "";
+ const d = new Date(seconds * 1000);
+ const pad = (n: number) => String(n).padStart(2, "0");
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
+}
function relative(seconds: number | null): string {
if (seconds === null) return "never";
@@ -21,46 +53,41 @@ function relative(seconds: number | null): string {
return `${Math.floor(ago / 86_400)} d ago`;
}
+type Selection = { type: "smart"; kind: SmartList } | { type: "list"; guid: string };
+
export function RemindersView() {
const [lists, setLists] = useState<ReminderList[]>([]);
- const [selected, setSelected] = useState<string | null>(null);
+ const [selection, setSelection] = useState<Selection>({ type: "smart", kind: "today" });
const [items, setItems] = useState<Reminder[]>([]);
const [showDone, setShowDone] = useState(false);
const [lastSynced, setLastSynced] = useState<number | null>(null);
const [syncing, setSyncing] = useState(false);
const [busyGuid, setBusyGuid] = useState<string | null>(null);
+ const [openGuid, setOpenGuid] = useState<string | null>(null);
const [draft, setDraft] = useState("");
- const [adding, setAdding] = useState(false);
const [loaded, setLoaded] = useState(false);
const [error, setError] = useState<string | null>(null);
+ const inList = selection.type === "list";
+ const listGuid = inList ? selection.guid : null;
+
const readLists = useCallback(async () => {
const [found, synced] = await Promise.all([
api.reminderLists(),
api.remindersLastSynced(),
]);
- const safe = Array.isArray(found) ? found : [];
- setLists(safe);
+ setLists(Array.isArray(found) ? found : []);
setLastSynced(typeof synced === "number" ? synced : null);
- // Prefer a list with something outstanding: opening on an empty one looks broken.
- if (safe.length > 0) {
- const counts = await Promise.all(
- safe.map(async (l) => [l.guid, (await api.remindersIn(l.guid, false)).length] as const)
- );
- setSelected((current) => {
- if (current) return current;
- const busiest = counts.reduce((a, b) => (b[1] > a[1] ? b : a));
- return busiest[1] > 0 ? busiest[0] : safe[0].guid;
- });
- }
setLoaded(true);
}, []);
const readItems = useCallback(async () => {
- if (!selected) return setItems([]);
- const found = await api.remindersIn(selected, showDone);
+ const found =
+ selection.type === "smart"
+ ? await api.remindersSmart(selection.kind, endOfToday())
+ : await api.remindersIn(selection.guid, showDone);
setItems(Array.isArray(found) ? found : []);
- }, [selected, showDone]);
+ }, [selection, showDone]);
const refreshRef = useRef<null | (() => Promise<void>)>(null);
@@ -72,7 +99,6 @@ export function RemindersView() {
await readLists();
await readItems();
} catch (e) {
- // The library still holds the last good data, so the list stays usable.
setError(messageOf(e));
} finally {
setSyncing(false);
@@ -80,15 +106,13 @@ export function RemindersView() {
}, [readLists, readItems]);
refreshRef.current = refresh;
- // Render from the library first, then fetch if nothing is stored yet.
useEffect(() => {
let cancelled = false;
(async () => {
try {
await readLists();
if (cancelled) return;
- const synced = await api.remindersLastSynced();
- if (!cancelled && synced === null) void refreshRef.current?.();
+ if ((await api.remindersLastSynced()) === null) void refreshRef.current?.();
} catch (e) {
if (!cancelled) {
setError(messageOf(e));
@@ -105,65 +129,89 @@ export function RemindersView() {
readItems().catch((e) => setError(messageOf(e)));
}, [readItems]);
- async function toggle(reminder: Reminder) {
- setBusyGuid(reminder.guid);
- setError(null);
- try {
- // Writes to Apple, then re-reads — so what's on screen is what Apple stored.
- await api.reminderSetDone(reminder.guid, reminder.listGuid, !reminder.completedAt);
- await readItems();
- } catch (e) {
- setError(messageOf(e));
- } finally {
- setBusyGuid(null);
- }
- }
+ /** Every write goes through here: to Apple first, then re-read, so nothing on screen is a guess. */
+ const write = useCallback(
+ async (reminder: Reminder, run: () => Promise<void>) => {
+ setBusyGuid(reminder.guid);
+ setError(null);
+ try {
+ await run();
+ await readItems();
+ } catch (e) {
+ setError(messageOf(e));
+ } finally {
+ setBusyGuid(null);
+ }
+ },
+ [readItems]
+ );
+
+ const toggle = (r: Reminder) =>
+ write(r, () => api.reminderSetDone(r.guid, r.listGuid, !r.completedAt));
+ const flag = (r: Reminder) =>
+ write(r, () => api.reminderEdit(r.guid, r.listGuid, { flagged: !r.flagged }));
+ const remove = (r: Reminder) => write(r, () => api.reminderDelete(r.guid, r.listGuid));
+ const rename = (r: Reminder, title: string) =>
+ title.trim() && title.trim() !== r.title
+ ? write(r, () => api.reminderEdit(r.guid, r.listGuid, { title: title.trim() }))
+ : Promise.resolve();
+ const setDue = (r: Reminder, value: string) =>
+ write(r, () =>
+ api.reminderEdit(r.guid, r.listGuid, {
+ dueAt: value ? Math.floor(new Date(value).getTime() / 1000) : null,
+ })
+ );
+ const setNotes = (r: Reminder, notes: string) =>
+ write(r, () => api.reminderEdit(r.guid, r.listGuid, { notes: notes.trim() || null }));
async function add(e: React.FormEvent) {
e.preventDefault();
const title = draft.trim();
- if (!title || !selected || adding) return;
- setAdding(true);
+ // Adding needs a real list: a smart list is a view, not somewhere to put things.
+ if (!title || !listGuid) return;
+ setSyncing(true);
setError(null);
try {
- await api.reminderCreate(selected, title);
+ await api.reminderCreate(listGuid, title);
setDraft("");
await readItems();
} catch (err) {
setError(messageOf(err));
} finally {
- setAdding(false);
- }
- }
-
- async function remove(reminder: Reminder) {
- setBusyGuid(reminder.guid);
- setError(null);
- try {
- await api.reminderDelete(reminder.guid, reminder.listGuid);
- await readItems();
- } catch (err) {
- setError(messageOf(err));
- } finally {
- setBusyGuid(null);
+ setSyncing(false);
}
}
- const current = useMemo(
- () => lists.find((l) => l.guid === selected) ?? null,
- [lists, selected]
- );
+ const heading = inList
+ ? lists.find((l) => l.guid === listGuid)?.title ?? "Reminders"
+ : SMART.find((s) => s.kind === (selection as { kind: SmartList }).kind)?.title ?? "Reminders";
const outstanding = items.filter((r) => !r.completedAt).length;
+ const colour = useMemo(
+ () => lists.find((l) => l.guid === listGuid)?.colour || "var(--gold)",
+ [lists, listGuid]
+ );
return (
<div className="rem">
<aside className="rem-lists" aria-label="Reminder lists">
+ {SMART.map((s) => (
+ <button
+ key={s.kind}
+ className="rem-list"
+ aria-current={selection.type === "smart" && selection.kind === s.kind}
+ onClick={() => setSelection({ type: "smart", kind: s.kind })}
+ >
+ <span className="rem-list-name">{s.title}</span>
+ </button>
+ ))}
+
+ <p className="rem-lists-heading">My Lists</p>
{lists.map((list) => (
<button
key={list.guid}
className="rem-list"
- aria-current={selected === list.guid}
- onClick={() => setSelected(list.guid)}
+ aria-current={listGuid === list.guid}
+ onClick={() => setSelection({ type: "list", guid: list.guid })}
>
<span className="dot" style={{ background: list.colour || "var(--gold)" }} />
<span className="rem-list-name">{list.title}</span>
@@ -175,14 +223,16 @@ export function RemindersView() {
<section className="rem-items">
<header className="cal-bar">
<div className="cal-nav">
- <h1>{current?.title ?? "Reminders"}</h1>
- {outstanding > 0 && <span className="badge">{outstanding} left</span>}
+ <h1>{heading}</h1>
+ {outstanding > 0 && <span className="badge">{outstanding}</span>}
</div>
<div className="cal-actions">
- <button className="quiet" onClick={() => setShowDone((v) => !v)}>
- {showDone ? "Hide completed" : "Show completed"}
- </button>
- <span className="badge">Updated {relative(lastSynced)}</span>
+ {inList && (
+ <button className="quiet" onClick={() => setShowDone((v) => !v)}>
+ {showDone ? "Hide completed" : "Show completed"}
+ </button>
+ )}
+ <span className="badge">{relative(lastSynced)}</span>
<button className="quiet" onClick={refresh} disabled={syncing}>
{syncing ? "Refreshing…" : "Refresh"}
</button>
@@ -191,60 +241,119 @@ export function RemindersView() {
{error && <p className="error" role="alert">{error}</p>}
- {selected && (
+ {inList && (
<form className="rem-add" onSubmit={add}>
<span className="tick ghost" aria-hidden="true" />
<input
value={draft}
- onChange={(event) => setDraft(event.target.value)}
+ onChange={(e) => setDraft(e.target.value)}
placeholder="Add a reminder"
- aria-label={`Add a reminder to ${current?.title ?? "this list"}`}
- disabled={adding}
+ aria-label={`Add a reminder to ${heading}`}
+ disabled={syncing}
/>
</form>
)}
<ul className="rem-list-items">
- {items.map((reminder) => (
- <li key={reminder.guid} className={reminder.completedAt ? "is-done" : undefined}>
- <button
- className="tick"
- role="checkbox"
- aria-checked={Boolean(reminder.completedAt)}
- aria-label={reminder.title}
- disabled={busyGuid === reminder.guid}
- onClick={() => toggle(reminder)}
- style={{ borderColor: current?.colour || "var(--gold)" }}
- >
- {reminder.completedAt && (
- <span
- className="tick-fill"
- style={{ background: current?.colour || "var(--gold)" }}
- />
- )}
- </button>
- <div className="rem-text">
- <span className="rem-title">{reminder.title}</span>
- {reminder.notes && <span className="rem-notes">{reminder.notes}</span>}
- </div>
- <span className="rem-trailing">
- {reminder.dueAt && <span className="rem-due">{dueLabel(reminder.dueAt)}</span>}
+ {items.map((reminder) => {
+ const due = reminder.dueAt === null ? null : dueLabel(reminder.dueAt);
+ const isOpen = openGuid === reminder.guid;
+ return (
+ <li key={reminder.guid} className={reminder.completedAt ? "is-done" : undefined}>
<button
- className="rem-delete"
- aria-label={`Delete ${reminder.title}`}
+ className="tick"
+ role="checkbox"
+ aria-checked={Boolean(reminder.completedAt)}
+ aria-label={reminder.title}
disabled={busyGuid === reminder.guid}
- onClick={() => remove(reminder)}
+ onClick={() => toggle(reminder)}
+ style={{ borderColor: colour }}
>
- ×
+ {reminder.completedAt && (
+ <span className="tick-fill" style={{ background: colour }} />
+ )}
</button>
- </span>
- </li>
- ))}
+
+ <div className="rem-text">
+ <input
+ className="rem-title-edit"
+ defaultValue={reminder.title}
+ key={`${reminder.guid}-${reminder.title}`}
+ aria-label={`Rename ${reminder.title}`}
+ disabled={busyGuid === reminder.guid}
+ onBlur={(e) => void rename(reminder, e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") e.currentTarget.blur();
+ if (e.key === "Escape") {
+ e.currentTarget.value = reminder.title;
+ e.currentTarget.blur();
+ }
+ }}
+ />
+ {reminder.notes && !isOpen && (
+ <span className="rem-notes">{reminder.notes}</span>
+ )}
+
+ {isOpen && (
+ <div className="rem-detail">
+ <label>
+ <span>Due</span>
+ <input
+ type="datetime-local"
+ defaultValue={toInputValue(reminder.dueAt)}
+ onBlur={(e) => void setDue(reminder, e.target.value)}
+ />
+ </label>
+ <label>
+ <span>Notes</span>
+ <textarea
+ defaultValue={reminder.notes ?? ""}
+ rows={2}
+ onBlur={(e) => void setNotes(reminder, e.target.value)}
+ />
+ </label>
+ </div>
+ )}
+ </div>
+
+ <span className="rem-trailing">
+ {due && (
+ <span className={`rem-due${due.overdue ? " overdue" : ""}`}>{due.text}</span>
+ )}
+ <button
+ className={`rem-flag${reminder.flagged ? " on" : ""}`}
+ aria-label={reminder.flagged ? `Unflag ${reminder.title}` : `Flag ${reminder.title}`}
+ aria-pressed={reminder.flagged}
+ disabled={busyGuid === reminder.guid}
+ onClick={() => flag(reminder)}
+ >
+ ⚑
+ </button>
+ <button
+ className="rem-more"
+ aria-label={isOpen ? `Close details for ${reminder.title}` : `Details for ${reminder.title}`}
+ aria-expanded={isOpen}
+ onClick={() => setOpenGuid(isOpen ? null : reminder.guid)}
+ >
+ ⋯
+ </button>
+ <button
+ className="rem-delete"
+ aria-label={`Delete ${reminder.title}`}
+ disabled={busyGuid === reminder.guid}
+ onClick={() => remove(reminder)}
+ >
+ ×
+ </button>
+ </span>
+ </li>
+ );
+ })}
</ul>
{loaded && items.length === 0 && !error && (
<p className="cal-empty">
- {showDone ? "Nothing in this list." : "All done here."}
+ {inList ? (showDone ? "Nothing in this list." : "All done here.") : "Nothing here."}
</p>
)}
</section>
diff --git a/src/styles/app.css b/src/styles/app.css
index f14b9df..ffc9e57 100644
--- a/src/styles/app.css
+++ b/src/styles/app.css
@@ -967,3 +967,89 @@
.drive-meta { color: var(--text-2); font-size: var(--t-11); font-variant-numeric: tabular-nums; }
.content:has(.drive) { display: flex; flex-direction: column; overflow: hidden; }
+
+/* ---- reminders: smart lists, inline editing, flags ------------------------------ */
+
+.rem-lists-heading {
+ margin: 14px 8px 4px;
+ font-size: var(--t-11);
+ font-weight: 600;
+ color: var(--text-3);
+}
+
+/* The title is editable in place, so it must read as text until it is focused. */
+.rem-title-edit {
+ border: 0;
+ background: none;
+ color: inherit;
+ font: inherit;
+ font-size: var(--t-13);
+ padding: 1px 3px;
+ margin-left: -3px;
+ border-radius: 4px;
+ width: 100%;
+ outline: none;
+}
+
+.rem-title-edit:hover { background: color-mix(in srgb, var(--text) 5%, transparent); }
+.rem-title-edit:focus { background: var(--field); box-shadow: 0 0 0 2px var(--gold-ring); }
+.is-done .rem-title-edit { color: var(--text-3); text-decoration: line-through; }
+
+.rem-detail {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ margin: 6px 0 2px;
+ padding: 8px 9px;
+ border-radius: var(--r-field);
+ background: color-mix(in srgb, var(--text) 4.5%, transparent);
+}
+
+.rem-detail label { display: grid; grid-template-columns: 48px 1fr; gap: 8px; align-items: start; }
+.rem-detail label > span { font-size: var(--t-11); color: var(--text-2); padding-top: 5px; }
+
+.rem-detail input,
+.rem-detail textarea {
+ font: inherit;
+ font-size: var(--t-13);
+ color: var(--text);
+ background: var(--field);
+ border: 1px solid var(--field-edge);
+ border-radius: var(--r-field);
+ padding: 4px 7px;
+ outline: none;
+ resize: vertical;
+}
+
+.rem-detail input:focus,
+.rem-detail textarea:focus { border-color: var(--gold); box-shadow: 0 0 0 3px var(--gold-ring); }
+
+/* Overdue is the one thing in this list that should catch the eye. */
+.rem-due.overdue { color: var(--danger); }
+
+.rem-flag,
+.rem-more {
+ border: 0;
+ background: none;
+ color: var(--text-3);
+ font-size: var(--t-13);
+ line-height: 1;
+ padding: 3px 5px;
+ border-radius: var(--r-field);
+ cursor: pointer;
+ opacity: 0;
+}
+
+.rem-flag.on { opacity: 1; color: var(--gold); }
+
+.rem-list-items li:hover .rem-flag,
+.rem-list-items li:hover .rem-more,
+.rem-flag:focus-visible,
+.rem-more:focus-visible { opacity: 1; }
+
+.rem-flag:hover, .rem-more:hover { color: var(--text); background: color-mix(in srgb, var(--text) 8%, transparent); }
+.rem-flag:focus-visible, .rem-more:focus-visible { outline: 3px solid var(--gold-ring); outline-offset: 1px; }
+
+/* A row holding an open detail panel needs the controls at the top, not centred. */
+.rem-list-items li { align-items: start; }
+.rem-trailing { padding-top: 2px; }