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.

Events can be created, changed and deleted

Yashwanth Kamireddia93544470e2f
diff --git a/.uiverify/a11y.mjs b/.uiverify/a11y.mjs
index b4d8509..95ad02c 100644
--- a/.uiverify/a11y.mjs
+++ b/.uiverify/a11y.mjs
@@ -24,6 +24,8 @@ function installStub({ screen, services, twoFactor }) {
case "calendar_events": return [];
case "calendar_list": return [];
case "calendar_last_synced": return Math.floor(Date.now() / 1000);
+ case "event_save": return "E-new";
+ case "event_delete": return null;
case "calendar_sync": return { calendars: 0, events: 0 };
case "reminder_lists": return [];
case "reminders_in": return [];
diff --git a/.uiverify/assert.mjs b/.uiverify/assert.mjs
index 3d66858..0da59f8 100644
--- a/.uiverify/assert.mjs
+++ b/.uiverify/assert.mjs
@@ -11,6 +11,8 @@ await ctx.addInitScript(({ services }) => {
if (cmd === "account_services") return services;
if (cmd === "calendar_events") return [];
if (cmd === "calendar_list") return [];
+ if (cmd === "event_save") return "E-new";
+ if (cmd === "event_delete") return null;
if (cmd === "calendar_sync") return { calendars: 0, events: 0 };
if (cmd === "reminder_lists") return [];
if (cmd === "reminders_in") return [];
diff --git a/.uiverify/crash.mjs b/.uiverify/crash.mjs
index 2f20282..896b01a 100644
--- a/.uiverify/crash.mjs
+++ b/.uiverify/crash.mjs
@@ -16,6 +16,8 @@ await ctx.addInitScript(() => {
case "contacts_last_synced": return Math.floor(Date.now() / 1000);
case "reminder_lists": case "reminders_in": case "reminders_smart":
case "note_folders": case "notes_in": case "contacts_list": case "drive_children": return [];
+ case "event_save": return "E-new";
+ case "event_delete": return null;
case "calendar_sync": return { calendars: 0, events: 0 };
case "reminders_sync": case "notes_sync": return [0, 0];
case "contacts_sync": case "drive_sync_folder": return 0;
diff --git a/.uiverify/keyboard.mjs b/.uiverify/keyboard.mjs
index 90396dd..e234870 100644
--- a/.uiverify/keyboard.mjs
+++ b/.uiverify/keyboard.mjs
@@ -23,6 +23,8 @@ function installStub({ screen, services, twoFactor }) {
case "calendar_events": return [];
case "calendar_list": return [];
case "calendar_last_synced": return Math.floor(Date.now() / 1000);
+ case "event_save": return "E-new";
+ case "event_delete": return null;
case "calendar_sync": return { calendars: 0, events: 0 };
case "reminder_lists": return [];
case "reminders_in": return [];
@@ -158,6 +160,30 @@ const focused = (page) =>
await ctx.close();
}
+// --- calendar: the month is a grid, so one tab stop and arrows move within it ---
+{
+ const { ctx, page } = await open("library");
+ await page.getByRole("button", { name: "Calendar" }).click();
+ await page.waitForSelector(".cal-grid");
+
+ const stops = await page.evaluate(
+ () => document.querySelectorAll('.cal-grid button[tabindex="0"]').length
+ );
+ check("month grid is ONE tab stop, not forty-two", stops === 1, `${stops} tabbable`);
+
+ const day = () => page.locator(".cal-day-panel h2").innerText();
+ const before = await day();
+ await page.locator('.cal-grid button[tabindex="0"]').focus();
+ await page.keyboard.press("ArrowDown");
+ const down = await day();
+ check("ArrowDown moves a week down the month", before !== down, `${before} → ${down}`);
+
+ await page.keyboard.press("ArrowRight");
+ const right = await day();
+ check("ArrowRight moves a day along", down !== right, `${down} → ${right}`);
+ await ctx.close();
+}
+
await browser.close();
let failed = 0;
for (const c of checks) {
diff --git a/.uiverify/shots.mjs b/.uiverify/shots.mjs
index 82b6386..4740ea2 100644
--- a/.uiverify/shots.mjs
+++ b/.uiverify/shots.mjs
@@ -125,6 +125,8 @@ function installStub({ screen, services, twoFactor, calendarFixture, notesFixtur
case "account_services": return services;
case "calendar_events": return events;
case "calendar_list": return calendars;
+ case "event_save": return "E-new";
+ case "event_delete": return null;
case "calendar_sync": return { calendars: calendars.length, events: events.length };
case "reminder_lists": return !remindersFixture ? [] : reminderLists;
case "reminders_in": return !remindersFixture ? [] : reminderItems;
diff --git a/Cargo.lock b/Cargo.lock
index 570e2fc..768af0f 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3144,6 +3144,7 @@ dependencies = [
"tauri",
"tauri-build",
"tokio",
+ "uuid",
]
[[package]]
diff --git a/crates/quince-core/src/calendar.rs b/crates/quince-core/src/calendar.rs
index 4dc8dde..d442c17 100644
--- a/crates/quince-core/src/calendar.rs
+++ b/crates/quince-core/src/calendar.rs
@@ -182,6 +182,44 @@ impl Library {
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
}
+ /// One event by its guid, if the library still holds it.
+ pub fn event(&self, guid: &str) -> Result<Option<Event>> {
+ let mut stmt = self.conn.prepare(
+ "SELECT guid, calendar_guid, title, location, starts_at, ends_at, all_day,
+ timezone, url, notes, etag
+ FROM events WHERE guid = ?1",
+ )?;
+ let mut rows = stmt.query_map(params![guid], |row| {
+ Ok(Event {
+ guid: row.get(0)?,
+ calendar_guid: row.get(1)?,
+ title: row.get(2)?,
+ location: row.get(3)?,
+ starts_at: row.get(4)?,
+ ends_at: row.get(5)?,
+ all_day: row.get::<_, i64>(6)? != 0,
+ timezone: row.get(7)?,
+ url: row.get(8)?,
+ notes: row.get(9)?,
+ etag: row.get(10)?,
+ })
+ })?;
+ rows.next().transpose().map_err(Into::into)
+ }
+
+ /// Drop events Apple no longer has.
+ pub fn forget_events(&mut self, guids: &[String]) -> Result<()> {
+ let tx = self.conn.transaction()?;
+ {
+ let mut stmt = tx.prepare("DELETE FROM events WHERE guid = ?1")?;
+ for guid in guids {
+ stmt.execute(params![guid])?;
+ }
+ }
+ tx.commit()?;
+ Ok(())
+ }
+
/// Record that a service synced successfully.
pub fn mark_synced(&self, service: &str, token: Option<&str>) -> Result<()> {
self.conn.execute(
diff --git a/crates/quince-icloud/src/calendar.rs b/crates/quince-icloud/src/calendar.rs
index af63c8c..e062e76 100644
--- a/crates/quince-icloud/src/calendar.rs
+++ b/crates/quince-icloud/src/calendar.rs
@@ -142,6 +142,32 @@ fn event_from(v: &Value) -> Result<Option<Event>> {
}))
}
+/// `YYYY-MM-DD` for the day an instant falls on, in the event's own timezone.
+fn day_of(seconds: i64, timezone: Option<&str>) -> String {
+ let zone = timezone
+ .and_then(|name| TimeZone::get(name).ok())
+ .unwrap_or(TimeZone::UTC);
+ jiff::Timestamp::from_second(seconds)
+ .unwrap_or(jiff::Timestamp::UNIX_EPOCH)
+ .to_zoned(zone)
+ .strftime("%Y-%m-%d")
+ .to_string()
+}
+
+/// What the web client tells the service it already has.
+///
+/// Sending the collection's ctag is how Apple decides whether to answer with the whole
+/// calendar or just the change, which is the difference between a quick write and refetching
+/// the month on every save.
+fn client_state(calendar_guid: &str, ctag: Option<&str>) -> Value {
+ serde_json::json!({
+ "Collection": [{ "guid": calendar_guid, "ctag": ctag }],
+ "fullState": false,
+ "userTime": 0,
+ "alarmRange": 60,
+ })
+}
+
/// Everything one calendar refresh yields.
#[derive(Debug, Default)]
pub struct Snapshot {
@@ -201,6 +227,127 @@ impl<'a> CalendarClient<'a> {
Ok(parse_snapshot(&body))
}
+ /// Create an event, or replace one that already exists.
+ ///
+ /// Apple's calendar service takes the whole event on every write rather than a patch, so
+ /// an edit sends the event as it should end up. `guid` addresses it; a fresh one is a
+ /// create and an existing one is an update.
+ ///
+ /// The window in the query is not decoration: Apple answers with the events in it, and
+ /// sending the day the event falls on is what makes the response carry the event back so
+ /// a caller can confirm what was stored rather than assume.
+ pub async fn put_event(&self, event: &Event, ctag: Option<&str>) -> Result<Snapshot> {
+ let day = day_of(event.starts_at, event.timezone.as_deref());
+ let body = serde_json::json!({
+ "Event": self.event_body(event),
+ "ClientState": client_state(&event.calendar_guid, ctag),
+ });
+ let path = format!("/ca/events/{}/{}", event.calendar_guid, event.guid);
+ let answer = self
+ .post(&path, &body, &day, &day, event.timezone.as_deref(), None)
+ .await?;
+ Ok(parse_snapshot(&answer))
+ }
+
+ /// Remove an event.
+ ///
+ /// `etag` is what stops a delete from landing on a version of the event someone changed
+ /// on another device in the meantime.
+ pub async fn delete_event(&self, event: &Event, ctag: Option<&str>) -> Result<()> {
+ let day = day_of(event.starts_at, event.timezone.as_deref());
+ let body = serde_json::json!({
+ "Event": { "guid": event.guid, "pGuid": event.calendar_guid, "etag": event.etag },
+ "ClientState": client_state(&event.calendar_guid, ctag),
+ });
+ let path = format!("/ca/events/{}/{}", event.calendar_guid, event.guid);
+ self.post(
+ &path,
+ &body,
+ &day,
+ &day,
+ event.timezone.as_deref(),
+ Some("DELETE"),
+ )
+ .await?;
+ Ok(())
+ }
+
+ /// Apple's event object, in the shape its own web client sends.
+ ///
+ /// Every field is filled rather than left out: the service rejects a partial event, and
+ /// an omitted `duration` or `tz` comes back as a rejection that says nothing useful.
+ fn event_body(&self, event: &Event) -> Value {
+ let zone = event.timezone.as_deref();
+ let minutes = ((event.ends_at - event.starts_at) / 60).max(0);
+ serde_json::json!({
+ "guid": event.guid,
+ "pGuid": event.calendar_guid,
+ "title": event.title,
+ "location": event.location.clone().unwrap_or_default(),
+ "description": event.notes.clone().unwrap_or_default(),
+ "url": event.url,
+ "startDate": format_apple_date(event.starts_at, zone),
+ "endDate": format_apple_date(event.ends_at, zone),
+ "localStartDate": format_apple_date(event.starts_at, zone),
+ "localEndDate": format_apple_date(event.ends_at, zone),
+ "duration": minutes,
+ "allDay": event.all_day,
+ "tz": zone,
+ "etag": event.etag,
+ "icon": 0,
+ "recurrence": Value::Null,
+ "changeRecurring": Value::Null,
+ "alarms": [],
+ "invitees": [],
+ "hasAttachments": false,
+ "isJunk": false,
+ "readOnly": false,
+ "extendedDetailsAreIncluded": true,
+ })
+ }
+
+ async fn post(
+ &self,
+ path: &str,
+ body: &Value,
+ from: &str,
+ to: &str,
+ tz: Option<&str>,
+ method_override: Option<&str>,
+ ) -> Result<Value> {
+ let mut query = self.params.clone();
+ query.push(("clientVersion".into(), "5.1".into()));
+ query.push(("requestID".into(), "4".into()));
+ query.push(("startDate".into(), from.into()));
+ query.push(("endDate".into(), to.into()));
+ query.push(("lang".into(), "en-us".into()));
+ query.push(("usertz".into(), tz.unwrap_or("UTC").into()));
+ if let Some(method) = method_override {
+ query.push(("methodOverride".into(), method.into()));
+ }
+
+ let response = self
+ .http
+ .post(format!("{}{path}", self.root))
+ .query(&query)
+ .json(body)
+ .send()
+ .await?;
+ let status = response.status();
+ let text = response.text().await.unwrap_or_default();
+
+ if status.as_u16() == 450 {
+ return Err(Error::ReauthRequired);
+ }
+ if !status.is_success() {
+ return Err(Error::Protocol(format!(
+ "{path} returned {status}: {}",
+ text.chars().take(200).collect::<String>()
+ )));
+ }
+ Ok(serde_json::from_str(&text).unwrap_or(Value::Null))
+ }
+
async fn get(&self, path: &str, from: &str, to: &str, tz: &str) -> Result<Value> {
let mut query = self.params.clone();
// Apple's calendar service returns an empty body unless the web client's own
@@ -416,3 +563,162 @@ mod tests {
assert!(snap.calendars.is_empty() && snap.events.is_empty());
}
}
+
+#[cfg(test)]
+mod write_tests {
+ use super::*;
+ use wiremock::matchers::{method, path_regex};
+ use wiremock::{Mock, MockServer, Request, ResponseTemplate};
+
+ fn event() -> Event {
+ Event {
+ guid: "E-1".into(),
+ calendar_guid: "work".into(),
+ title: "Dentist".into(),
+ location: Some("Gachibowli".into()),
+ // 2026-09-14T09:30:00+05:30
+ starts_at: 1_789_358_400,
+ ends_at: 1_789_362_000,
+ all_day: false,
+ timezone: Some("Asia/Kolkata".into()),
+ url: None,
+ notes: None,
+ etag: None,
+ }
+ }
+
+ async fn server() -> MockServer {
+ let server = MockServer::start().await;
+ Mock::given(method("POST"))
+ .and(path_regex(r".*/ca/events/.*"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
+ "Event": [{
+ "guid": "E-1",
+ "pGuid": "work",
+ "title": "Dentist",
+ "tz": "Asia/Kolkata",
+ "startDate": [20260914, 2026, 9, 14, 9, 30, 570],
+ "endDate": [20260914, 2026, 9, 14, 10, 30, 630],
+ "etag": "stored"
+ }]
+ })))
+ .mount(&server)
+ .await;
+ server
+ }
+
+ async fn request(server: &MockServer) -> Request {
+ server.received_requests().await.unwrap().remove(0)
+ }
+
+ #[tokio::test]
+ async fn a_write_addresses_the_event_by_calendar_and_guid() {
+ let server = server().await;
+ let http = reqwest::Client::new();
+ let client = CalendarClient::new(&http, &server.uri(), vec![]);
+ client.put_event(&event(), Some("ctag-1")).await.unwrap();
+ assert_eq!(request(&server).await.url.path(), "/ca/events/work/E-1");
+ }
+
+ /// Apple answers with the events in the window it was given, so sending the event's own
+ /// day is what makes the reply carry the stored event back.
+ #[tokio::test]
+ async fn the_window_is_the_day_the_event_falls_on_locally() {
+ let server = server().await;
+ let http = reqwest::Client::new();
+ let client = CalendarClient::new(&http, &server.uri(), vec![]);
+ client.put_event(&event(), None).await.unwrap();
+
+ let sent = request(&server).await;
+ let query: std::collections::HashMap<_, _> = sent.url.query_pairs().collect();
+ // 04:00 UTC on the 14th is 09:30 on the 14th in Kolkata — the local day is what counts.
+ assert_eq!(query["startDate"], "2026-09-14");
+ assert_eq!(query["endDate"], "2026-09-14");
+ assert_eq!(query["usertz"], "Asia/Kolkata");
+ }
+
+ #[tokio::test]
+ async fn the_whole_event_is_sent_in_apples_own_shape() {
+ let server = server().await;
+ let http = reqwest::Client::new();
+ let client = CalendarClient::new(&http, &server.uri(), vec![]);
+ client.put_event(&event(), Some("ctag-1")).await.unwrap();
+
+ let sent = request(&server).await;
+ let body: Value = serde_json::from_slice(&sent.body).unwrap();
+ let e = &body["Event"];
+ assert_eq!(e["title"], "Dentist");
+ assert_eq!(e["location"], "Gachibowli");
+ assert_eq!(e["duration"], 60, "duration is minutes, not seconds");
+ assert_eq!(e["tz"], "Asia/Kolkata");
+ // The date is Apple's component array in the event's own zone, not a timestamp.
+ assert_eq!(
+ e["startDate"],
+ serde_json::json!([20260914, 2026, 9, 14, 9, 30, 570])
+ );
+ assert_eq!(body["ClientState"]["Collection"][0]["ctag"], "ctag-1");
+ }
+
+ /// What comes back is what gets stored — never what was sent.
+ #[tokio::test]
+ async fn the_stored_event_is_read_from_apples_reply() {
+ let server = server().await;
+ let http = reqwest::Client::new();
+ let client = CalendarClient::new(&http, &server.uri(), vec![]);
+ let answer = client.put_event(&event(), None).await.unwrap();
+ assert_eq!(answer.events.len(), 1);
+ assert_eq!(answer.events[0].etag.as_deref(), Some("stored"));
+ }
+
+ #[tokio::test]
+ async fn deleting_says_so_in_the_query_and_carries_the_etag() {
+ let server = server().await;
+ let http = reqwest::Client::new();
+ let client = CalendarClient::new(&http, &server.uri(), vec![]);
+ let mut gone = event();
+ gone.etag = Some("v3".into());
+ client.delete_event(&gone, None).await.unwrap();
+
+ let sent = request(&server).await;
+ let query: std::collections::HashMap<_, _> = sent.url.query_pairs().collect();
+ assert_eq!(query["methodOverride"], "DELETE");
+ let body: Value = serde_json::from_slice(&sent.body).unwrap();
+ assert_eq!(
+ body["Event"]["etag"], "v3",
+ "a delete must not race another device"
+ );
+ }
+
+ /// An all-day event has no meaningful duration, and a negative one is nonsense.
+ #[tokio::test]
+ async fn a_zero_length_event_reports_zero_minutes() {
+ let server = server().await;
+ let http = reqwest::Client::new();
+ let client = CalendarClient::new(&http, &server.uri(), vec![]);
+ let mut instant = event();
+ instant.ends_at = instant.starts_at;
+ client.put_event(&instant, None).await.unwrap();
+
+ let body: Value = serde_json::from_slice(&request(&server).await.body).unwrap();
+ assert_eq!(body["Event"]["duration"], 0);
+ }
+
+ #[tokio::test]
+ async fn a_rejection_reads_as_a_sentence() {
+ let server = MockServer::start().await;
+ Mock::given(method("POST"))
+ .and(path_regex(r".*/ca/events/.*"))
+ .respond_with(ResponseTemplate::new(400).set_body_string("bad event"))
+ .mount(&server)
+ .await;
+ let http = reqwest::Client::new();
+ let client = CalendarClient::new(&http, &server.uri(), vec![]);
+ let message = client
+ .put_event(&event(), None)
+ .await
+ .unwrap_err()
+ .to_string();
+ assert!(message.contains("400"), "{message}");
+ assert!(message.contains("bad event"), "{message}");
+ }
+}
diff --git a/crates/quince-icloud/src/sync.rs b/crates/quince-icloud/src/sync.rs
index e6539af..7bd9034 100644
--- a/crates/quince-icloud/src/sync.rs
+++ b/crates/quince-icloud/src/sync.rs
@@ -101,6 +101,62 @@ pub async fn fetch_calendar(
Ok(Snapshot { calendars, events })
}
+/// Create an event, or save changes to one, and store what Apple answers with.
+///
+/// Apple takes the whole event on every write, so an edit is the event as it should end up
+/// rather than a patch. The response carries the stored version back, which is what goes
+/// into the library — never the version that was sent.
+pub async fn put_event(
+ http: &reqwest::Client,
+ root: &str,
+ params: Vec<(String, String)>,
+ library: &mut Library,
+ event: &quince_core::calendar::Event,
+) -> Result<()> {
+ let client = CalendarClient::new(http, root, params);
+ let ctag = library
+ .calendars()?
+ .into_iter()
+ .find(|c| c.guid == event.calendar_guid)
+ .and_then(|c| c.ctag);
+
+ let answer = client.put_event(event, ctag.as_deref()).await?;
+ // Apple echoes the stored event back. If it did not, the local copy is what we sent,
+ // which is still better than showing nothing until the next refresh.
+ let stored: Vec<_> = if answer.events.is_empty() {
+ vec![event.clone()]
+ } else {
+ answer.events
+ };
+ let known: std::collections::HashSet<String> =
+ library.calendars()?.into_iter().map(|c| c.guid).collect();
+ let storable: Vec<_> = stored
+ .into_iter()
+ .filter(|e| known.contains(&e.calendar_guid))
+ .collect();
+ library.put_events(&storable)?;
+ Ok(())
+}
+
+/// Remove an event, locally as well as at Apple.
+pub async fn delete_event(
+ http: &reqwest::Client,
+ root: &str,
+ params: Vec<(String, String)>,
+ library: &mut Library,
+ event: &quince_core::calendar::Event,
+) -> Result<()> {
+ let client = CalendarClient::new(http, root, params);
+ let ctag = library
+ .calendars()?
+ .into_iter()
+ .find(|c| c.guid == event.calendar_guid)
+ .and_then(|c| c.ctag);
+ client.delete_event(event, ctag.as_deref()).await?;
+ library.forget_events(std::slice::from_ref(&event.guid))?;
+ Ok(())
+}
+
/// Store a fetched window. Touches no network.
pub fn apply_calendar(library: &mut Library, snapshot: Snapshot) -> Result<SyncSummary> {
library.put_calendars(&snapshot.calendars)?;
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 1c5eb59..46b14c1 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -19,3 +19,4 @@ serde_json.workspace = true
tokio = { workspace = true }
anyhow.workspace = true
jiff = "0.2.37"
+uuid.workspace = true
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 7c52909..76e10d2 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -236,6 +236,104 @@ async fn calendar_sync(
.map_err(|e| e.to_string())
}
+/// What the interface sends to create or change an event.
+///
+/// The guid is what decides which it is: absent means a new event, present means saving
+/// changes to one Apple already has.
+#[derive(serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct EventDraft {
+ guid: Option<String>,
+ calendar_guid: String,
+ title: String,
+ location: Option<String>,
+ starts_at: i64,
+ ends_at: i64,
+ all_day: bool,
+ timezone: Option<String>,
+ notes: Option<String>,
+ url: Option<String>,
+}
+
+/// Everything an event write needs from the session, with the auth lock released first.
+async fn calendar_context(
+ auth: &State<'_, Auth>,
+) -> Result<(reqwest::Client, String, Vec<(String, String)>), String> {
+ let client = auth.client.lock().await;
+ let root = client
+ .session()
+ .service_url("calendar")
+ .ok_or("Apple hasn't offered a calendar service for this account.")?;
+ Ok((client.http().clone(), root, client.service_params()))
+}
+
+/// Create an event, or save changes to one.
+///
+/// Apple takes the whole event on every write, so an edit sends the event as it should end
+/// up rather than a patch. What comes back from Apple is what gets stored.
+#[tauri::command]
+async fn event_save(
+ draft: EventDraft,
+ auth: State<'_, Auth>,
+ data: State<'_, Data>,
+) -> UiResult<String> {
+ let title = draft.title.trim();
+ if title.is_empty() {
+ return Err("An event needs a title.".into());
+ }
+ if draft.ends_at < draft.starts_at {
+ return Err("An event can't end before it starts.".into());
+ }
+ let (http, root, params) = calendar_context(&auth).await?;
+
+ // Apple's guids are uppercase UUIDs; a new event needs one before it can be addressed.
+ let guid = draft
+ .guid
+ .unwrap_or_else(|| uuid::Uuid::new_v4().to_string().to_uppercase());
+ let existing = {
+ let library = data.0.lock().await;
+ library.event(&guid).map_err(|e| e.to_string())?
+ };
+
+ let event = Event {
+ guid: guid.clone(),
+ calendar_guid: draft.calendar_guid,
+ title: title.to_string(),
+ location: draft.location.filter(|s| !s.trim().is_empty()),
+ starts_at: draft.starts_at,
+ ends_at: draft.ends_at,
+ all_day: draft.all_day,
+ timezone: draft.timezone,
+ url: draft.url.filter(|s| !s.trim().is_empty()),
+ notes: draft.notes.filter(|s| !s.trim().is_empty()),
+ // Apple rejects a write whose etag is not the version it holds, which is what stops
+ // this from landing on top of a change made on a phone.
+ etag: existing.and_then(|e| e.etag),
+ };
+
+ let mut library = data.0.lock().await;
+ quince_icloud::sync::put_event(&http, &root, params, &mut library, &event)
+ .await
+ .map_err(|e| e.to_string())?;
+ Ok(guid)
+}
+
+#[tauri::command]
+async fn event_delete(guid: String, auth: State<'_, Auth>, data: State<'_, Data>) -> UiResult<()> {
+ let (http, root, params) = calendar_context(&auth).await?;
+ let event = {
+ let library = data.0.lock().await;
+ library
+ .event(&guid)
+ .map_err(|e| e.to_string())?
+ .ok_or("That event is no longer in the local library.")?
+ };
+ let mut library = data.0.lock().await;
+ quince_icloud::sync::delete_event(&http, &root, params, &mut library, &event)
+ .await
+ .map_err(|e| e.to_string())
+}
+
/// Events overlapping `[from, to]`, as unix seconds. Read straight from the library.
#[tauri::command]
async fn calendar_events(from: i64, to: i64, data: State<'_, Data>) -> UiResult<Vec<Event>> {
@@ -711,6 +809,8 @@ fn main() {
sync_status,
calendar_sync,
calendar_events,
+ event_save,
+ event_delete,
calendar_list,
reminder_lists,
reminders_in,
diff --git a/src/lib/ipc.ts b/src/lib/ipc.ts
index e14d069..be90400 100644
--- a/src/lib/ipc.ts
+++ b/src/lib/ipc.ts
@@ -52,6 +52,8 @@ export const api = {
signOut: () => invoke<void>("auth_sign_out"),
services: () => invoke<string[]>("account_services"),
+ eventSave: (draft: EventWrite) => invoke<string>("event_save", { draft }),
+ eventDelete: (guid: string) => invoke<void>("event_delete", { guid }),
calendarSync: (from: string, to: string, timezone: string) =>
invoke<SyncSummary>("calendar_sync", { from, to, timezone }),
calendarEvents: (from: number, to: number) =>
@@ -105,6 +107,20 @@ export type Calendar = {
enabled: boolean;
};
+/** What the app sends to create or change an event. A guid means it already exists. */
+export type EventWrite = {
+ guid: string | null;
+ calendarGuid: string;
+ title: string;
+ location: string | null;
+ startsAt: number;
+ endsAt: number;
+ allDay: boolean;
+ timezone: string | null;
+ notes: string | null;
+ url: string | null;
+};
+
export type CalendarEvent = {
guid: string;
calendarGuid: string;
diff --git a/src/screens/CalendarView.tsx b/src/screens/CalendarView.tsx
index 182b250..34b3c6e 100644
--- a/src/screens/CalendarView.tsx
+++ b/src/screens/CalendarView.tsx
@@ -34,6 +34,55 @@ const clockTime = (seconds: number) =>
.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" })
.replace(":00", "");
+/** `YYYY-MM-DDTHH:mm` for a datetime-local input, in local time. */
+const toInputValue = (seconds: number) => {
+ 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())}`;
+};
+
+/** An event being written. A guid means it already exists at Apple. */
+type EventDraft = {
+ guid: string | null;
+ calendarGuid: string;
+ title: string;
+ location: string;
+ startsAt: number;
+ endsAt: number;
+ allDay: boolean;
+ notes: string;
+};
+
+/** A new event on `day`, at the next whole hour, running an hour — Apple's own default. */
+function blankEvent(day: Date, calendarGuid: string): EventDraft {
+ const now = new Date();
+ const at = new Date(day.getFullYear(), day.getMonth(), day.getDate(), now.getHours() + 1, 0, 0);
+ const startsAt = Math.floor(at.getTime() / 1000);
+ return {
+ guid: null,
+ calendarGuid,
+ title: "",
+ location: "",
+ startsAt,
+ endsAt: startsAt + 3600,
+ allDay: false,
+ notes: "",
+ };
+}
+
+function draftFrom(event: CalendarEvent): EventDraft {
+ return {
+ guid: event.guid,
+ calendarGuid: event.calendarGuid,
+ title: event.title,
+ location: event.location ?? "",
+ startsAt: event.startsAt,
+ endsAt: event.endsAt,
+ allDay: event.allDay,
+ notes: event.notes ?? "",
+ };
+}
+
/** The 42 days a month grid shows: the weeks containing the first and last of the month. */
function gridDays(anchor: Date): Date[] {
const first = new Date(anchor.getFullYear(), anchor.getMonth(), 1);
@@ -57,6 +106,11 @@ export function CalendarView() {
/** A month outside the window the shared refresh keeps warm is being fetched. */
const [fetchingMonth, setFetchingMonth] = useState(false);
const { revision } = useSync();
+ /** The day whose contents the inspector shows. Defaults to today. */
+ const [selected, setSelected] = useState<Date>(() => new Date(today));
+ /** The event being written, or null when the inspector is just listing. */
+ const [draft, setDraft] = useState<EventDraft | null>(null);
+ const [busy, setBusy] = useState(false);
const days = useMemo(() => gridDays(anchor), [anchor]);
const range = useMemo(
@@ -178,6 +232,82 @@ export function CalendarView() {
return map;
}, [events, dueReminders]);
+ const dayEntries = byDay.get(selected.toDateString()) ?? [];
+
+ // A month grid moves with the arrow keys, a week at a time vertically — the same shape
+ // as a spreadsheet, and what a screen reader announces a grid as being.
+ const selectedCell = useRef<HTMLButtonElement | null>(null);
+
+ const onGridKey = (e: React.KeyboardEvent, day: Date) => {
+ const step = (days: number) => {
+ e.preventDefault();
+ const to = new Date(day.getFullYear(), day.getMonth(), day.getDate() + days);
+ setSelected(to);
+ setDraft(null);
+ // Stepping off the month follows the selection there rather than stranding it.
+ if (to.getMonth() !== anchor.getMonth() || to.getFullYear() !== anchor.getFullYear()) {
+ setAnchor(new Date(to.getFullYear(), to.getMonth(), 1));
+ }
+ };
+ if (e.key === "ArrowRight") step(1);
+ else if (e.key === "ArrowLeft") step(-1);
+ else if (e.key === "ArrowDown") step(7);
+ else if (e.key === "ArrowUp") step(-7);
+ else if (e.key === "Home") step(-day.getDay());
+ else if (e.key === "End") step(6 - day.getDay());
+ };
+
+ // Keep focus with the selection when the arrows move it, but never steal it otherwise.
+ const hadFocus = useRef(false);
+ useEffect(() => {
+ if (hadFocus.current) selectedCell.current?.focus();
+ }, [selected]);
+
+ /** Every write goes to Apple first, then the library is re-read. */
+ const write = useCallback(
+ async (run: () => Promise<void>) => {
+ setBusy(true);
+ setError(null);
+ try {
+ await run();
+ await read();
+ return true;
+ } catch (e) {
+ setError(messageOf(e));
+ return false;
+ } finally {
+ setBusy(false);
+ }
+ },
+ [read]
+ );
+
+ const saveDraft = useCallback(async () => {
+ if (!draft) return;
+ const ok = await write(async () => {
+ await api.eventSave({
+ guid: draft.guid,
+ calendarGuid: draft.calendarGuid,
+ title: draft.title,
+ location: draft.location || null,
+ startsAt: draft.startsAt,
+ endsAt: draft.endsAt,
+ allDay: draft.allDay,
+ timezone: ZONE,
+ notes: draft.notes || null,
+ url: null,
+ });
+ });
+ if (ok) setDraft(null);
+ }, [draft, write]);
+
+ const removeEvent = useCallback(
+ async (guid: string) => {
+ if (await write(() => api.eventDelete(guid))) setDraft(null);
+ },
+ [write]
+ );
+
const shift = (months: number) =>
setAnchor((a) => new Date(a.getFullYear(), a.getMonth() + months, 1));
@@ -210,7 +340,17 @@ export function CalendarView() {
))}
</div>
- <div className="cal-grid" role="grid" aria-label={`${monthLabel} calendar`}>
+ <div
+ className="cal-grid"
+ role="grid"
+ aria-label={`${monthLabel} calendar`}
+ onFocus={() => {
+ hadFocus.current = true;
+ }}
+ onBlur={(e) => {
+ if (!e.currentTarget.contains(e.relatedTarget as Node)) hadFocus.current = false;
+ }}
+ >
{/* A grid's cells must sit inside rows, or screen readers cannot navigate it by
week. The rows use display:contents so the visual layout is unchanged. */}
{[0, 1, 2, 3, 4, 5].map((week) => (
@@ -224,16 +364,31 @@ export function CalendarView() {
day: "numeric",
month: "long",
});
+ const isSelected = sameDay(day, selected);
return (
<div
key={day.toISOString()}
- className={`cal-day${outside ? " outside" : ""}`}
+ className={`cal-day${outside ? " outside" : ""}${isSelected ? " is-selected" : ""}`}
role="gridcell"
- aria-label={
- items.length ? `${label}, ${items.length} event(s)` : label
- }
aria-current={isToday ? "date" : undefined}
>
+ <button
+ type="button"
+ className="cal-day-hit"
+ ref={(el) => {
+ if (isSelected) selectedCell.current = el;
+ }}
+ // One tab stop for the whole month, as a grid should have; the arrows
+ // move within it.
+ tabIndex={isSelected ? 0 : -1}
+ aria-label={items.length ? `${label}, ${items.length} item(s)` : label}
+ aria-pressed={isSelected}
+ onClick={() => {
+ setSelected(day);
+ setDraft(null);
+ }}
+ onKeyDown={(e) => onGridKey(e, day)}
+ >
<span className={`daynum${isToday ? " is-today" : ""}`}>
{day.getDate()}
</span>
@@ -288,6 +443,7 @@ export function CalendarView() {
<span className="chip more">{items.length - 3} more</span>
)}
</div>
+ </button>
</div>
);
})}
@@ -295,6 +451,163 @@ export function CalendarView() {
))}
</div>
+ <section
+ className="cal-day-panel"
+ aria-label={`${selected.toLocaleDateString(undefined, { weekday: "long", day: "numeric", month: "long" })}`}
+ >
+ <header className="cal-day-head">
+ <h2>
+ {selected.toLocaleDateString(undefined, {
+ weekday: "long",
+ day: "numeric",
+ month: "long",
+ })}
+ </h2>
+ <button
+ className="quiet"
+ disabled={busy || calendars.length === 0}
+ onClick={() => setDraft(blankEvent(selected, calendars[0]?.guid ?? ""))}
+ >
+ New event
+ </button>
+ </header>
+
+ {draft ? (
+ <form
+ className="cal-form"
+ onSubmit={(e) => {
+ e.preventDefault();
+ void saveDraft();
+ }}
+ >
+ <label>
+ <span>Title</span>
+ <input
+ value={draft.title}
+ autoFocus
+ onChange={(e) => setDraft({ ...draft, title: e.target.value })}
+ placeholder="New event"
+ />
+ </label>
+ <label>
+ <span>Calendar</span>
+ <select
+ value={draft.calendarGuid}
+ onChange={(e) => setDraft({ ...draft, calendarGuid: e.target.value })}
+ >
+ {calendars.map((c) => (
+ <option key={c.guid} value={c.guid}>
+ {c.title}
+ </option>
+ ))}
+ </select>
+ </label>
+ <label>
+ <span>Starts</span>
+ <input
+ type="datetime-local"
+ value={toInputValue(draft.startsAt)}
+ onChange={(e) => {
+ const startsAt = Math.floor(new Date(e.target.value).getTime() / 1000);
+ if (Number.isNaN(startsAt)) return;
+ // Dragging the start carries the end with it, keeping the length, which
+ // is what every calendar does and what nobody wants to redo by hand.
+ const length = Math.max(draft.endsAt - draft.startsAt, 0);
+ setDraft({ ...draft, startsAt, endsAt: startsAt + length });
+ }}
+ />
+ </label>
+ <label>
+ <span>Ends</span>
+ <input
+ type="datetime-local"
+ value={toInputValue(draft.endsAt)}
+ onChange={(e) => {
+ const endsAt = Math.floor(new Date(e.target.value).getTime() / 1000);
+ if (!Number.isNaN(endsAt)) setDraft({ ...draft, endsAt });
+ }}
+ />
+ </label>
+ <label className="cal-check">
+ <input
+ type="checkbox"
+ checked={draft.allDay}
+ onChange={(e) => setDraft({ ...draft, allDay: e.target.checked })}
+ />
+ <span>All day</span>
+ </label>
+ <label>
+ <span>Location</span>
+ <input
+ value={draft.location}
+ onChange={(e) => setDraft({ ...draft, location: e.target.value })}
+ />
+ </label>
+ <label>
+ <span>Notes</span>
+ <textarea
+ rows={2}
+ value={draft.notes}
+ onChange={(e) => setDraft({ ...draft, notes: e.target.value })}
+ />
+ </label>
+
+ <div className="cal-form-actions">
+ <button type="submit" className="primary" disabled={busy || !draft.title.trim()}>
+ {busy ? "Saving…" : draft.guid ? "Save" : "Add event"}
+ </button>
+ <button type="button" className="quiet" onClick={() => setDraft(null)}>
+ Cancel
+ </button>
+ {draft.guid && (
+ <button
+ type="button"
+ className="quiet danger"
+ disabled={busy}
+ onClick={() => void removeEvent(draft.guid as string)}
+ >
+ Delete
+ </button>
+ )}
+ </div>
+ </form>
+ ) : dayEntries.length === 0 ? (
+ <p className="cal-empty">Nothing on this day.</p>
+ ) : (
+ <ul className="cal-day-list">
+ {dayEntries.map((entry) =>
+ entry.kind === "event" ? (
+ <li key={`e${entry.event.guid}`}>
+ <button className="cal-day-item" onClick={() => setDraft(draftFrom(entry.event))}>
+ <span
+ className="chip-dot"
+ style={{ background: colours.get(entry.event.calendarGuid) || "var(--gold)" }}
+ />
+ <span className="cal-day-when">
+ {entry.event.allDay ? "All day" : clockTime(entry.event.startsAt)}
+ </span>
+ <span className="cal-day-title">{entry.event.title}</span>
+ </button>
+ </li>
+ ) : (
+ <li key={`r${entry.reminder.guid}`}>
+ {/* A reminder belongs to Reminders; the calendar shows it, and sends you
+ there to change it. */}
+ <span className="cal-day-item is-reminder">
+ <span className="chip-ring" />
+ <span className="cal-day-when">
+ {clockTime(entry.reminder.dueAt ?? 0)}
+ </span>
+ <span className="cal-day-title">{entry.reminder.title}</span>
+ <span className="badge">Reminder</span>
+ </span>
+ </li>
+ )
+ )}
+ </ul>
+ )}
+ </section>
+
{loaded && events.length === 0 && dueReminders.length === 0 && !error && (
<p className="cal-empty">
No events in this month. Quince keeps them on this computer once synced, so they
diff --git a/src/styles/app.css b/src/styles/app.css
index 701516d..e38f527 100644
--- a/src/styles/app.css
+++ b/src/styles/app.css
@@ -505,15 +505,45 @@
.cal-day {
background: var(--bg);
- padding: 4px 5px 5px;
min-width: 0;
overflow: hidden;
display: flex;
+ position: relative;
+}
+
+/* The whole cell is the target. A day is a thing you point at, not a small number in the
+ corner of one. */
+.cal-day-hit {
+ flex: 1;
+ min-width: 0;
+ display: flex;
flex-direction: column;
+ align-items: stretch;
gap: 2px;
+ padding: 4px 5px 5px;
+ border: 0;
+ background: none;
+ font: inherit;
+ color: inherit;
+ text-align: left;
+ cursor: pointer;
+ border-radius: 0;
+}
+
+.cal-day-hit:hover { background: color-mix(in srgb, var(--bg) 90%, var(--text) 7%); }
+
+.cal-day-hit:focus-visible {
+ outline: 2px solid var(--gold);
+ outline-offset: -2px;
}
+/* Selection is a ring, not a fill: the chips inside still have to be legible. */
+.cal-day.is-selected { box-shadow: inset 0 0 0 2px var(--gold-ring); }
+
.cal-day.outside { background: color-mix(in srgb, var(--bg) 88%, var(--text) 4%); }
+.cal-day.outside .cal-day-hit:hover {
+ background: color-mix(in srgb, var(--bg) 82%, var(--text) 9%);
+}
.cal-day.outside .daynum { color: var(--text-3); }
.daynum {
@@ -1296,3 +1326,124 @@ textarea.note-text:disabled {
outline: none;
box-shadow: 0 0 0 3px var(--gold-ring);
}
+
+/* The day inspector: what is on the selected day, and the one place events are written.
+ Apple puts this beside the month; at this width it reads better beneath it, where it can
+ use the full measure for a form. */
+.cal-day-panel {
+ margin-top: 10px;
+ padding: 10px 12px 12px;
+ background: var(--sheet);
+ border-radius: var(--r-plateau);
+ box-shadow: 0 0 0 0.5px var(--glass-edge);
+ max-height: 40vh;
+ overflow-y: auto;
+}
+
+.cal-day-head {
+ display: flex;
+ align-items: baseline;
+ justify-content: space-between;
+ gap: 12px;
+}
+
+.cal-day-head h2 {
+ margin: 0;
+ font-size: var(--t-13);
+ font-weight: 600;
+}
+
+.cal-day-list {
+ margin: 8px 0 0;
+ padding: 0;
+ list-style: none;
+ display: flex;
+ flex-direction: column;
+ gap: 1px;
+}
+
+.cal-day-item {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ width: 100%;
+ padding: 6px 7px;
+ border: 0;
+ background: none;
+ font: inherit;
+ font-size: var(--t-13);
+ color: inherit;
+ text-align: left;
+ border-radius: var(--r-field);
+ cursor: pointer;
+}
+
+button.cal-day-item:hover { background: color-mix(in srgb, var(--sheet) 92%, var(--text) 7%); }
+.cal-day-item.is-reminder { cursor: default; }
+
+.cal-day-when {
+ flex: none;
+ min-width: 5.5em;
+ color: var(--text-2);
+ font-size: var(--t-11);
+ font-variant-numeric: tabular-nums;
+}
+
+.cal-day-title {
+ flex: 1;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+/* Two columns of fields, so a date and its time sit together rather than stacking into a
+ tall form that pushes the actions off the panel. */
+.cal-form {
+ margin-top: 10px;
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(190px, 1fr));
+ gap: 8px 12px;
+ align-items: end;
+}
+
+.cal-form label {
+ display: flex;
+ flex-direction: column;
+ gap: 3px;
+ font-size: var(--t-11);
+ color: var(--text-2);
+ min-width: 0;
+}
+
+.cal-form input,
+.cal-form select,
+.cal-form textarea {
+ font: inherit;
+ font-size: var(--t-13);
+ color: var(--text);
+ padding: 5px 7px;
+ border-radius: var(--r-field);
+ border: 0.5px solid var(--field-edge);
+ background: var(--field);
+ box-shadow: var(--shadow-field);
+ min-width: 0;
+}
+
+.cal-form textarea { resize: vertical; }
+
+.cal-check {
+ flex-direction: row !important;
+ align-items: center;
+ gap: 6px;
+ padding-bottom: 6px;
+}
+
+.cal-check input { flex: none; }
+
+.cal-form-actions {
+ grid-column: 1 / -1;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin-top: 2px;
+}