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.

Calendar end to end: sync into the library and show it

Yashwanth Kamireddidaa5416831af
diff --git a/Cargo.lock b/Cargo.lock
index 1163675..4f46e8a 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2771,6 +2771,8 @@ version = "0.1.0"
dependencies = [
"anyhow",
"quince-auth",
+ "quince-core",
+ "quince-icloud",
"serde",
"serde_json",
"tauri",
diff --git a/crates/quince-auth/src/lib.rs b/crates/quince-auth/src/lib.rs
index 0f3f4d9..10cf26e 100644
--- a/crates/quince-auth/src/lib.rs
+++ b/crates/quince-auth/src/lib.rs
@@ -80,6 +80,11 @@ const WIDGET_KEY: &str = "d39ba9916b7251055b22c7f910e2ea796ee65e98b2ddecea8f5dde
const MIN_PBKDF2_ITERATIONS: u32 = 1_000;
const MAX_PBKDF2_ITERATIONS: u32 = 1_000_000;
+/// Version strings the iCloud web client sends. Cosmetic to Apple in practice, but sending
+/// something plausible keeps our requests looking like the client they are imitating.
+const CLIENT_BUILD: &str = "2523Project28";
+const CLIENT_MASTERING: &str = "2523B28";
+
const UA: &str = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 \
(KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36";
@@ -379,15 +384,28 @@ impl Client {
if !self.session.is_resumable() {
return Ok(false);
}
- match self.validate().await {
+ // Cheap path: the cookies are still good, so nothing needs re-establishing.
+ if let Ok(data) = self.validate().await {
+ self.absorb(&data);
+ self.persist()?;
+ return Ok(true);
+ }
+
+ // The cookies are missing or stale but the tokens are not. Apple's service endpoints
+ // authenticate by cookie — without X-APPLE-WEBAUTH-USER they answer 421 — so trade
+ // the stored tokens for a fresh set. No password, no code.
+ //
+ // This is what makes staying signed in survive a lost cookie file, a copied install,
+ // or cookies expiring before the trust token does.
+ match self.account_login().await {
Ok(data) => {
self.absorb(&data);
self.persist()?;
Ok(true)
}
Err(_) => {
- // The stored session is dead. Drop its challenge state now so it cannot
- // contaminate the sign-in that follows.
+ // Genuinely dead. Drop the challenge state so it cannot contaminate the
+ // sign-in that follows.
self.clear_challenge_state();
Ok(false)
}
@@ -809,6 +827,26 @@ impl Client {
}
}
+ /// Query parameters every iCloud service endpoint expects alongside the session cookies.
+ #[must_use]
+ pub fn service_params(&self) -> Vec<(String, String)> {
+ let mut params = vec![
+ ("clientBuildNumber".to_string(), CLIENT_BUILD.to_string()),
+ (
+ "clientMasteringNumber".to_string(),
+ CLIENT_MASTERING.to_string(),
+ ),
+ (
+ "clientId".to_string(),
+ self.session.client_id.clone().unwrap_or_default(),
+ ),
+ ];
+ if let Some(dsid) = &self.session.dsid {
+ params.push(("dsid".to_string(), dsid.clone()));
+ }
+ params
+ }
+
/// Shared HTTP client, for the service crates that ride this session.
pub fn http(&self) -> &HttpClient {
&self.http
diff --git a/crates/quince-auth/tests/auth_flow.rs b/crates/quince-auth/tests/auth_flow.rs
index 0a53aac..f9d1e66 100644
--- a/crates/quince-auth/tests/auth_flow.rs
+++ b/crates/quince-auth/tests/auth_flow.rs
@@ -504,3 +504,54 @@ async fn an_implausible_work_factor_is_refused() {
);
}
}
+
+/// Apple's service endpoints authenticate by cookie. If the cookies are lost but the tokens
+/// survive — a copied install, a cleared cache, cookies expiring before the trust token —
+/// resuming must re-establish them rather than leaving the app looking signed in while every
+/// service answers 421.
+#[tokio::test]
+async fn resume_rebuilds_a_session_from_tokens_alone() {
+ let server = MockServer::start().await;
+ // No valid cookies, so Apple rejects the cheap check.
+ Mock::given(method("POST"))
+ .and(path("/setup/ws/1/validate"))
+ .respond_with(ResponseTemplate::new(421).set_body_json(json!({
+ "reason": "Missing X-APPLE-WEBAUTH-USER cookie", "error": 1
+ })))
+ .mount(&server)
+ .await;
+ mount_init(&server, 200).await;
+ mount_complete(&server, 409).await;
+ Mock::given(method("POST"))
+ .and(path("/appleauth/auth/verify/trusteddevice/securitycode"))
+ .respond_with(ResponseTemplate::new(204))
+ .mount(&server)
+ .await;
+ mount_trust_and_login(&server).await;
+
+ let dir = tempfile::tempdir().unwrap();
+ {
+ let mut first = client_for(&server, dir.path());
+ first
+ .sign_in("[email protected]", "hunter2")
+ .await
+ .unwrap();
+ first.submit_two_factor("123456").await.unwrap();
+ }
+ // Throw the cookies away, keeping the tokens.
+ let cookies = dir.path().join("cookies.json");
+ if cookies.exists() {
+ std::fs::remove_file(&cookies).unwrap();
+ }
+
+ let mut resumed = client_for(&server, dir.path());
+ assert!(resumed.has_stored_session());
+ assert!(
+ resumed.resume().await.unwrap(),
+ "tokens alone must be enough to re-establish a session"
+ );
+ assert!(
+ resumed.session().webservices.is_some(),
+ "and the service map must come back with it"
+ );
+}
diff --git a/crates/quince-icloud/src/lib.rs b/crates/quince-icloud/src/lib.rs
index 7db8092..f910000 100644
--- a/crates/quince-icloud/src/lib.rs
+++ b/crates/quince-icloud/src/lib.rs
@@ -4,6 +4,7 @@
//! untrusted: a missing field or a malformed date returns an error, never a panic.
pub mod calendar;
+pub mod sync;
#[derive(Debug, thiserror::Error)]
pub enum Error {
diff --git a/crates/quince-icloud/src/sync.rs b/crates/quince-icloud/src/sync.rs
new file mode 100644
index 0000000..1343aef
--- /dev/null
+++ b/crates/quince-icloud/src/sync.rs
@@ -0,0 +1,268 @@
+//! Bringing Apple's calendar into the local library.
+//!
+//! The interface never waits on this. A sync reconciles into SQLite and the UI reads SQLite,
+//! so a slow or failed refresh leaves the last known good data on screen rather than an
+//! empty window.
+
+use crate::calendar::CalendarClient;
+use crate::Result;
+use quince_core::Library;
+
+/// What one refresh changed.
+#[derive(Debug, Default, Clone, Copy, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SyncSummary {
+ pub calendars: usize,
+ pub events: usize,
+}
+
+/// Fetch the window `[from, to]` (both `YYYY-MM-DD`) and reconcile it into the library.
+///
+/// Collections are written before events so the foreign key always resolves; an event whose
+/// calendar Apple did not report would otherwise be rejected.
+pub async fn calendar(
+ http: &reqwest::Client,
+ root: &str,
+ params: Vec<(String, String)>,
+ library: &mut Library,
+ from: &str,
+ to: &str,
+ timezone: &str,
+) -> Result<SyncSummary> {
+ let client = CalendarClient::new(http, root, params);
+
+ // `/ca/startup` reliably carries the collections but does not always carry events — on
+ // some accounts it returns collections alone. Asking `/ca/events` for the same window is
+ // what actually guarantees them, so do both and merge.
+ let startup = client.startup(from, to, timezone).await?;
+ let windowed = client.events(from, to, timezone).await?;
+
+ library.put_calendars(&startup.calendars)?;
+
+ let mut snapshot = startup;
+ if !windowed.events.is_empty() {
+ let known: std::collections::HashSet<&str> =
+ snapshot.events.iter().map(|e| e.guid.as_str()).collect();
+ let extra: Vec<_> = windowed
+ .events
+ .iter()
+ .filter(|e| !known.contains(e.guid.as_str()))
+ .cloned()
+ .collect();
+ snapshot.events.extend(extra);
+ }
+
+ // Drop events belonging to calendars Apple did not report: storing them would fail the
+ // foreign key, and they are not ours to show.
+ let known: std::collections::HashSet<&str> =
+ snapshot.calendars.iter().map(|c| c.guid.as_str()).collect();
+ let events: Vec<_> = snapshot
+ .events
+ .iter()
+ .filter(|e| known.contains(e.calendar_guid.as_str()))
+ .cloned()
+ .collect();
+
+ library.put_events(&events)?;
+ library.mark_synced("calendar", None)?;
+
+ Ok(SyncSummary {
+ calendars: snapshot.calendars.len(),
+ events: events.len(),
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+ use wiremock::matchers::{method, path};
+ use wiremock::{Mock, MockServer, ResponseTemplate};
+
+ fn body() -> serde_json::Value {
+ json!({
+ "Collection": [{ "guid": "cal-1", "title": "Work", "ctag": "c1" }],
+ "Event": [
+ { "guid": "ev-1", "pGuid": "cal-1", "title": "Standup", "tz": "Asia/Kolkata",
+ "startDate": [20260912, 2026, 9, 12, 9, 30, 570],
+ "endDate": [20260912, 2026, 9, 12, 9, 45, 585] },
+ // Belongs to a calendar Apple did not report — must be dropped, not stored.
+ { "guid": "ev-2", "pGuid": "cal-missing", "title": "Orphan",
+ "startDate": [20260912, 2026, 9, 12, 11, 0, 660], "duration": 30 }
+ ]
+ })
+ }
+
+ /// Some accounts get collections from /ca/startup and nothing else; the events arrive
+ /// only from /ca/events. A sync that trusts startup alone silently shows an empty
+ /// calendar.
+ #[tokio::test]
+ async fn events_are_collected_even_when_startup_omits_them() {
+ let server = MockServer::start().await;
+ Mock::given(method("GET"))
+ .and(path("/ca/startup"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({
+ "Collection": [{ "guid": "cal-1", "title": "Work" }]
+ })))
+ .mount(&server)
+ .await;
+ Mock::given(method("GET"))
+ .and(path("/ca/events"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({
+ "Event": [{ "guid": "ev-9", "pGuid": "cal-1", "title": "From events",
+ "startDate": [20260912, 2026, 9, 12, 9, 0, 540], "duration": 30 }]
+ })))
+ .mount(&server)
+ .await;
+
+ let http = reqwest::Client::new();
+ let mut library = Library::in_memory().unwrap();
+ let summary = calendar(
+ &http,
+ &server.uri(),
+ vec![],
+ &mut library,
+ "2026-09-01",
+ "2026-09-30",
+ "UTC",
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(
+ summary.events, 1,
+ "events must come from /ca/events when startup omits them"
+ );
+ assert_eq!(
+ library.events_between(0, i64::MAX).unwrap()[0].title,
+ "From events"
+ );
+ }
+
+ #[tokio::test]
+ async fn a_sync_lands_in_the_library() {
+ let server = MockServer::start().await;
+ Mock::given(method("GET"))
+ .and(path("/ca/startup"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(body()))
+ .mount(&server)
+ .await;
+ Mock::given(method("GET"))
+ .and(path("/ca/events"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({})))
+ .mount(&server)
+ .await;
+
+ let http = reqwest::Client::new();
+ let mut library = Library::in_memory().unwrap();
+
+ let summary = calendar(
+ &http,
+ &server.uri(),
+ vec![],
+ &mut library,
+ "2026-09-01",
+ "2026-09-30",
+ "Asia/Kolkata",
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(summary.calendars, 1);
+ assert_eq!(summary.events, 1, "the orphaned event must be dropped");
+
+ let stored = library.events_between(0, i64::MAX).unwrap();
+ assert_eq!(stored.len(), 1);
+ assert_eq!(stored[0].title, "Standup");
+ assert!(library.last_synced("calendar").unwrap().is_some());
+ }
+
+ /// Running twice must converge, not accumulate.
+ #[tokio::test]
+ async fn syncing_twice_is_idempotent() {
+ let server = MockServer::start().await;
+ Mock::given(method("GET"))
+ .and(path("/ca/startup"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(body()))
+ .mount(&server)
+ .await;
+
+ Mock::given(method("GET"))
+ .and(path("/ca/events"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({})))
+ .mount(&server)
+ .await;
+
+ let http = reqwest::Client::new();
+ let mut library = Library::in_memory().unwrap();
+ for _ in 0..3 {
+ calendar(
+ &http,
+ &server.uri(),
+ vec![],
+ &mut library,
+ "2026-09-01",
+ "2026-09-30",
+ "UTC",
+ )
+ .await
+ .unwrap();
+ }
+ assert_eq!(library.events_between(0, i64::MAX).unwrap().len(), 1);
+ assert_eq!(library.calendars().unwrap().len(), 1);
+ }
+
+ /// A failed refresh must leave the last good data alone.
+ #[tokio::test]
+ async fn a_failed_sync_does_not_empty_the_library() {
+ let ok = MockServer::start().await;
+ Mock::given(method("GET"))
+ .and(path("/ca/startup"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(body()))
+ .mount(&ok)
+ .await;
+ Mock::given(method("GET"))
+ .and(path("/ca/events"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({})))
+ .mount(&ok)
+ .await;
+
+ let http = reqwest::Client::new();
+ let mut library = Library::in_memory().unwrap();
+ calendar(
+ &http,
+ &ok.uri(),
+ vec![],
+ &mut library,
+ "2026-09-01",
+ "2026-09-30",
+ "UTC",
+ )
+ .await
+ .unwrap();
+
+ let broken = MockServer::start().await;
+ Mock::given(method("GET"))
+ .and(path("/ca/startup"))
+ .respond_with(ResponseTemplate::new(503))
+ .mount(&broken)
+ .await;
+
+ assert!(calendar(
+ &http,
+ &broken.uri(),
+ vec![],
+ &mut library,
+ "2026-09-01",
+ "2026-09-30",
+ "UTC"
+ )
+ .await
+ .is_err());
+ assert_eq!(
+ library.events_between(0, i64::MAX).unwrap().len(),
+ 1,
+ "a failed refresh must not clear what we already had"
+ );
+ }
+}
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 26f795e..ff89739 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -11,6 +11,8 @@ tauri-build = { version = "2", features = [] }
[dependencies]
tauri = { version = "2", features = [] }
quince-auth = { path = "../crates/quince-auth" }
+quince-core = { path = "../crates/quince-core" }
+quince-icloud = { path = "../crates/quince-icloud" }
serde.workspace = true
serde_json.workspace = true
tokio = { workspace = true }
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index f35bf93..c7f390b 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -2,6 +2,8 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use quince_auth::{Client, SignInOutcome, TwoFactorOptions};
+use quince_core::calendar::{Calendar, Event};
+use quince_core::Library;
use serde::Serialize;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
@@ -35,6 +37,8 @@ struct Status {
signed_in: bool,
}
+struct Data(Mutex<Library>);
+
/// Errors cross to the UI as plain sentences a person can act on.
type UiResult<T> = Result<T, String>;
@@ -167,6 +171,55 @@ fn spawn_heartbeat(client: Arc<Mutex<Client>>) {
});
}
+/// Refresh the calendar window `[from, to]` (both `YYYY-MM-DD`) from Apple.
+///
+/// The interface does not wait on this to render: it reads the library, which still holds
+/// the last good data while a refresh is in flight or failing.
+#[tauri::command]
+async fn calendar_sync(
+ from: String,
+ to: String,
+ timezone: String,
+ auth: State<'_, Auth>,
+ data: State<'_, Data>,
+) -> UiResult<quince_icloud::sync::SyncSummary> {
+ // Take what the sync needs and release the auth lock before the network work, so a slow
+ // refresh cannot block the heartbeat or a sign-out.
+ let (http, root, params) = {
+ 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.")?;
+ (client.http().clone(), root, client.service_params())
+ };
+
+ let mut library = data.0.lock().await;
+ quince_icloud::sync::calendar(&http, &root, params, &mut library, &from, &to, &timezone)
+ .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>> {
+ let library = data.0.lock().await;
+ library.events_between(from, to).map_err(|e| e.to_string())
+}
+
+#[tauri::command]
+async fn calendar_list(data: State<'_, Data>) -> UiResult<Vec<Calendar>> {
+ let library = data.0.lock().await;
+ library.calendars().map_err(|e| e.to_string())
+}
+
+/// When the calendar last synced, as unix seconds.
+#[tauri::command]
+async fn calendar_last_synced(data: State<'_, Data>) -> UiResult<Option<i64>> {
+ let library = data.0.lock().await;
+ library.last_synced("calendar").map_err(|e| e.to_string())
+}
+
fn main() {
tauri::Builder::default()
.setup(|app| {
@@ -176,6 +229,9 @@ fn main() {
client: Arc::clone(&client),
signing_in: AtomicBool::new(false),
});
+ // The local library. Opened once at startup so every command shares one
+ // connection and the WAL behaves.
+ app.manage(Data(Mutex::new(Library::open(&dir)?)));
spawn_heartbeat(client);
Ok(())
})
@@ -190,6 +246,10 @@ fn main() {
auth_submit_sms_code,
auth_sign_out,
account_services,
+ calendar_sync,
+ calendar_events,
+ calendar_list,
+ calendar_last_synced,
])
.run(tauri::generate_context!())
.expect("Quince failed to start");
diff --git a/src/App.tsx b/src/App.tsx
index c3cbb3a..43b9dc2 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -16,7 +16,9 @@ export default function App() {
(async () => {
try {
const status = await api.status();
- if (status.signedIn) return !cancelled && setPhase("library");
+ // Always resume rather than trusting stored metadata. Apple's service endpoints
+ // authenticate by cookie, and holding a token is not the same as being able to call
+ // them — resuming is what establishes the cookies that make the session usable.
if (status.hasStoredSession && (await api.resume())) {
return !cancelled && setPhase("library");
}
diff --git a/src/lib/ipc.ts b/src/lib/ipc.ts
index 6dff85d..b033fd9 100644
--- a/src/lib/ipc.ts
+++ b/src/lib/ipc.ts
@@ -23,9 +23,42 @@ export const api = {
invoke<void>("auth_submit_sms_code", { phoneId, code }),
signOut: () => invoke<void>("auth_sign_out"),
services: () => invoke<string[]>("account_services"),
+
+ calendarSync: (from: string, to: string, timezone: string) =>
+ invoke<SyncSummary>("calendar_sync", { from, to, timezone }),
+ calendarEvents: (from: number, to: number) =>
+ invoke<CalendarEvent[]>("calendar_events", { from, to }),
+ calendarList: () => invoke<Calendar[]>("calendar_list"),
+ calendarLastSynced: () => invoke<number | null>("calendar_last_synced"),
};
/** Tauri rejects with a plain string from our commands; keep it readable either way. */
+export type Calendar = {
+ guid: string;
+ title: string;
+ colour: string | null;
+ ctag: string | null;
+ sortOrder: number;
+ enabled: boolean;
+};
+
+export type CalendarEvent = {
+ guid: string;
+ calendarGuid: string;
+ title: string;
+ location: string | null;
+ /** Unix seconds, UTC. */
+ startsAt: number;
+ endsAt: number;
+ allDay: boolean;
+ timezone: string | null;
+ url: string | null;
+ notes: string | null;
+ etag: string | null;
+};
+
+export type SyncSummary = { calendars: number; events: number };
+
export function messageOf(e: unknown): string {
if (typeof e === "string") return e;
if (e instanceof Error) return e.message;
diff --git a/src/screens/CalendarView.tsx b/src/screens/CalendarView.tsx
new file mode 100644
index 0000000..eb7cde8
--- /dev/null
+++ b/src/screens/CalendarView.tsx
@@ -0,0 +1,172 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { api, messageOf, type Calendar, type CalendarEvent } from "../lib/ipc";
+
+const DAY = 86_400;
+const ZONE = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
+
+const isoDate = (seconds: number) =>
+ new Date(seconds * 1000).toISOString().slice(0, 10);
+
+const dayKey = (seconds: number) =>
+ new Date(seconds * 1000).toLocaleDateString(undefined, {
+ year: "numeric",
+ month: "2-digit",
+ day: "2-digit",
+ });
+
+const dayHeading = (seconds: number) =>
+ new Date(seconds * 1000).toLocaleDateString(undefined, {
+ weekday: "long",
+ day: "numeric",
+ month: "long",
+ });
+
+const clockTime = (seconds: number) =>
+ new Date(seconds * 1000).toLocaleTimeString(undefined, {
+ hour: "numeric",
+ minute: "2-digit",
+ });
+
+function relative(seconds: number | null): string {
+ if (seconds === null) return "not yet";
+ const ago = Math.max(0, Math.floor(Date.now() / 1000) - seconds);
+ if (ago < 60) return "just now";
+ if (ago < 3600) return `${Math.floor(ago / 60)} min ago`;
+ if (ago < 86_400) return `${Math.floor(ago / 3600)} h ago`;
+ return `${Math.floor(ago / 86_400)} d ago`;
+}
+
+export function CalendarView() {
+ const [events, setEvents] = useState<CalendarEvent[]>([]);
+ const [calendars, setCalendars] = useState<Calendar[]>([]);
+ const [lastSynced, setLastSynced] = useState<number | null>(null);
+ const [syncing, setSyncing] = useState(false);
+ const [loaded, setLoaded] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ // A four-week window from a week ago: enough to be useful without pulling a decade.
+ const window = useMemo(() => {
+ const now = Math.floor(Date.now() / 1000);
+ return { from: now - 7 * DAY, to: now + 21 * DAY };
+ }, []);
+
+ const read = useCallback(async () => {
+ const [found, cals, synced] = await Promise.all([
+ api.calendarEvents(window.from, window.to),
+ api.calendarList(),
+ api.calendarLastSynced(),
+ ]);
+ setEvents(found);
+ setCalendars(cals);
+ setLastSynced(synced);
+ setLoaded(true);
+ }, [window]);
+
+ // Render from the library first — instant, and works offline — then refresh behind it.
+ // On a first ever open there is nothing stored, so fetch straight away rather than
+ // showing an empty screen and asking the person to press a button.
+ useEffect(() => {
+ let cancelled = false;
+ (async () => {
+ try {
+ await read();
+ if (cancelled) return;
+ const synced = await api.calendarLastSynced();
+ if (!cancelled && synced === null) void refreshRef.current?.();
+ } catch (e) {
+ if (!cancelled) {
+ setError(messageOf(e));
+ setLoaded(true);
+ }
+ }
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [read]);
+
+ // Held in a ref so the first-open effect can trigger a refresh without depending on it.
+ const refreshRef = useRef<null | (() => Promise<void>)>(null);
+
+ const refresh = useCallback(async () => {
+ setSyncing(true);
+ setError(null);
+ try {
+ await api.calendarSync(isoDate(window.from), isoDate(window.to), ZONE);
+ await read();
+ } catch (e) {
+ // The library still holds the last good data, so the view stays usable.
+ setError(messageOf(e));
+ } finally {
+ setSyncing(false);
+ }
+ }, [window, read]);
+
+ refreshRef.current = refresh;
+
+ const colours = useMemo(
+ () => new Map(calendars.map((c) => [c.guid, c.colour])),
+ [calendars]
+ );
+
+ const days = useMemo(() => {
+ const grouped = new Map<string, CalendarEvent[]>();
+ for (const event of events) {
+ const key = dayKey(event.startsAt);
+ const bucket = grouped.get(key);
+ if (bucket) bucket.push(event);
+ else grouped.set(key, [event]);
+ }
+ return [...grouped.values()];
+ }, [events]);
+
+ return (
+ <>
+ <div className="toolbar">
+ <span className="badge">
+ {lastSynced === null && loaded ? "Never synced" : `Updated ${relative(lastSynced)}`}
+ </span>
+ <button className="quiet" onClick={refresh} disabled={syncing}>
+ {syncing ? "Refreshing…" : "Refresh"}
+ </button>
+ </div>
+
+ <h1>Calendar</h1>
+
+ {error && <p className="error" role="alert">{error}</p>}
+
+ {loaded && events.length === 0 && (
+ <p>
+ Nothing here yet. Refresh to pull the next few weeks from iCloud — after that it
+ opens instantly, with or without a connection.
+ </p>
+ )}
+
+ <div className="agenda">
+ {days.map((day) => (
+ <section key={dayKey(day[0].startsAt)} className="agenda-day">
+ <h2>{dayHeading(day[0].startsAt)}</h2>
+ <ul>
+ {day.map((event) => (
+ <li key={event.guid}>
+ <span
+ className="dot"
+ style={{ background: colours.get(event.calendarGuid) || "var(--gold)" }}
+ aria-hidden="true"
+ />
+ <span className="when">
+ {event.allDay ? "All day" : clockTime(event.startsAt)}
+ </span>
+ <span className="what">
+ {event.title}
+ {event.location && <span className="where">{event.location}</span>}
+ </span>
+ </li>
+ ))}
+ </ul>
+ </section>
+ ))}
+ </div>
+ </>
+ );
+}
diff --git a/src/screens/Library.tsx b/src/screens/Library.tsx
index 4c0d343..1e31e9a 100644
--- a/src/screens/Library.tsx
+++ b/src/screens/Library.tsx
@@ -1,5 +1,6 @@
import { useEffect, useRef, useState } from "react";
import { api, messageOf } from "../lib/ipc";
+import { CalendarView } from "./CalendarView";
const NAMES: Record<string, string> = {
photos: "Photos",
@@ -37,6 +38,10 @@ const NAMES: Record<string, string> = {
schoolwork: "Schoolwork",
};
+/** Services with a real screen behind them. Opening on one of these beats opening on a
+ * placeholder, so selection prefers them. */
+const BUILT = new Set(["calendar"]);
+
/** What a person actually came for, in the order they'd look for it. */
const PRIMARY = [
"photos",
@@ -70,7 +75,12 @@ export function Library({ onSignOut }: { onSignOut: () => void }) {
return true;
});
setServices(unique);
- setSelected(PRIMARY.find((k) => unique.includes(k)) ?? unique[0] ?? null);
+ setSelected(
+ PRIMARY.find((k) => unique.includes(k) && BUILT.has(k)) ??
+ PRIMARY.find((k) => unique.includes(k)) ??
+ unique[0] ??
+ null
+ );
})
.catch((e) => setError(messageOf(e)));
}, []);
@@ -138,6 +148,10 @@ export function Library({ onSignOut }: { onSignOut: () => void }) {
</nav>
<main className="content">
+ {selected === "calendar" ? (
+ <CalendarView />
+ ) : (
+ <>
<div className="toolbar">
<button className="quiet" onClick={onSignOut}>Sign out</button>
</div>
@@ -153,6 +167,8 @@ export function Library({ onSignOut }: { onSignOut: () => void }) {
the data layer isn't built yet.
</p>
{error && <p className="error" role="alert">{error}</p>}
+ </>
+ )}
</main>
</div>
);
diff --git a/src/styles/app.css b/src/styles/app.css
index aabaea7..f50ee65 100644
--- a/src/styles/app.css
+++ b/src/styles/app.css
@@ -313,3 +313,53 @@
from { opacity: 0; transform: scale(0.972); }
to { opacity: 1; transform: none; }
}
+
+/* ---- agenda ------------------------------------------------------------------ */
+
+.agenda { margin-top: 4px; }
+
+.agenda-day { margin-bottom: 22px; }
+
+.agenda-day h2 {
+ margin: 0 0 7px;
+ font-size: var(--t-13);
+ font-weight: 600;
+ color: var(--text-2);
+}
+
+.agenda-day ul { list-style: none; margin: 0; padding: 0; }
+
+.agenda-day li {
+ display: grid;
+ grid-template-columns: 8px 74px 1fr;
+ align-items: baseline;
+ gap: 10px;
+ padding: 7px 9px;
+ border-radius: var(--r-field);
+}
+
+.agenda-day li:hover { background: color-mix(in srgb, var(--text) 5%, transparent); }
+
+.dot {
+ width: 7px;
+ height: 7px;
+ border-radius: var(--r-pill);
+ align-self: center;
+}
+
+.when {
+ color: var(--text-2);
+ font-size: var(--t-13);
+ font-variant-numeric: tabular-nums;
+}
+
+.what { font-size: var(--t-15); }
+
+.where {
+ display: block;
+ color: var(--text-2);
+ font-size: var(--t-11);
+ margin-top: 1px;
+}
+
+.toolbar { align-items: center; gap: 12px; }