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: Alert and 2nd Alert in the event editor, icloud.com's presets, read from Apple on open and written only when changed; pickers open upward when there is no room below

Yashwanth Kamireddi0392148c957b
diff --git a/.uiverify/calendar-alerts.mjs b/.uiverify/calendar-alerts.mjs
new file mode 100644
index 0000000..f1e098d
--- /dev/null
+++ b/.uiverify/calendar-alerts.mjs
@@ -0,0 +1,37 @@
+// An event's alerts: read from Apple when it opens, changed from icloud.com's presets, and
+// written only when changed — a save that did not touch them sends none, so a slow read can
+// never clear them.
+import { engine } from "./engine.mjs";
+import { SERVICES, installStub, openScreen } from "./stub.mjs";
+const b = await engine.launch();
+const ctx = await b.newContext({ viewport: { width: 1300, height: 850 } });
+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, calendarFixture: true });
+const page = await ctx.newPage();
+await page.goto("http://localhost:4173", { waitUntil: "networkidle" });
+await openScreen(page, "Calendar");
+await page.keyboard.press("Control+2");
+await page.waitForTimeout(300);
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };
+
+await page.locator(".cx-block", { hasText: "Dentist" }).first().click();
+await page.waitForTimeout(300);
+const shown = await page.getByRole("button", { name: "Alert", exact: true }).innerText();
+ok(/15 minutes before/.test(shown), `an event opens with the alert Apple holds [${shown.trim()}]`);
+ok((await page.getByRole("button", { name: "Second alert" }).count()) === 1, "and a second alert can be added");
+await page.getByRole("button", { name: "Alert", exact: true }).click();
+await page.getByRole("option", { name: "1 hour before" }).click();
+await page.locator('input[placeholder="New Event"]').first().press("Enter");
+await page.waitForTimeout(300);
+let sent = await page.evaluate(() => window.__eventSaves?.at(-1));
+ok(JSON.stringify(sent?.alerts) === "[60]", `a changed alert is written ${JSON.stringify(sent?.alerts)}`);
+
+await page.locator(".cx-block", { hasText: "Design review" }).first().click();
+await page.waitForTimeout(300);
+await page.locator('input[placeholder="New Event"]').first().fill("Design review, again");
+await page.locator('input[placeholder="New Event"]').first().press("Enter");
+await page.waitForTimeout(300);
+sent = await page.evaluate(() => window.__eventSaves?.at(-1));
+ok(sent && !("alerts" in sent), `an edit that leaves the alerts alone sends none ${JSON.stringify(Object.keys(sent ?? {}))}`);
+await b.close();
+process.exitCode = failures ? 1 : 0;
diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjs
index 98d2831..021c667 100644
--- a/.uiverify/stub.mjs
+++ b/.uiverify/stub.mjs
@@ -140,7 +140,8 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
.sort((a, b) => a.startsAt - b.startsAt);
}
case "calendar_list": return calendars;
- case "event_save": return "E-new";
+ case "event_alerts": return args.guid === "e2" ? [15] : [];
+ case "event_save": (window.__eventSaves ??= []).push(args.draft); return "E-new";
case "event_delete": return null;
case "calendar_sync": return { calendars: calendars.length, events: events.length };
case "reminder_counts": return { today: 4, scheduled: 7, flagged: 2, all: 12, lists: [["L1", 5], ["L2", 3], ["lists", 4]] };
diff --git a/check.sh b/check.sh
index 9c1670a..a877e71 100755
--- a/check.sh
+++ b/check.sh
@@ -60,6 +60,7 @@ step "notes folders" node .uiverify/notes-folders.mjs
step "list info" node .uiverify/reminders-list-info.mjs
step "reminder date" node .uiverify/reminders-date.mjs
step "contacts order" node .uiverify/contacts-order.mjs
+step "calendar alerts" node .uiverify/calendar-alerts.mjs
# The same screens in WebKit, the engine Quince draws in. Chromium above catches most things;
# this catches what only WebKit does — pointer capture, blur on removal, its own layout.
diff --git a/crates/quince-icloud/src/sync.rs b/crates/quince-icloud/src/sync.rs
index db5ecee..c8d5dcb 100644
--- a/crates/quince-icloud/src/sync.rs
+++ b/crates/quince-icloud/src/sync.rs
@@ -155,9 +155,21 @@ pub async fn save_event(
params: Vec<(String, String)>,
ctag: Option<&str>,
event: &quince_core::calendar::Event,
+) -> Result<Vec<quince_core::calendar::Event>> {
+ save_event_with_alerts(http, root, params, ctag, event, None).await
+}
+
+/// [`save_event`], with the event's alerts set to `alerts` when given.
+pub async fn save_event_with_alerts(
+ http: &reqwest::Client,
+ root: &str,
+ params: Vec<(String, String)>,
+ ctag: Option<&str>,
+ event: &quince_core::calendar::Event,
+ alerts: Option<&[i64]>,
) -> Result<Vec<quince_core::calendar::Event>> {
let client = CalendarClient::new(http, root, params);
- let answer = client.put_event(event, ctag).await?;
+ let answer = client.put_event_with_alerts(event, ctag, alerts).await?;
// What goes into the library is what Apple holds, never what was sent. Measured: a save
// to the account answers with an empty list, and storing the sent copy instead kept an
// event with no etag — so the next edit or delete went without one — and, where Apple
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 88aab85..38566a0 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -355,6 +355,10 @@ struct EventDraft {
timezone: Option<String>,
notes: Option<String>,
url: Option<String>,
+ /// Set the alerts to exactly these, minutes before the start (`0` at the time); absent,
+ /// the event's alerts are left as Apple holds them.
+ #[serde(default)]
+ alerts: Option<Vec<i64>>,
}
/// Everything an event write needs from the session, with the auth lock released first.
@@ -373,6 +377,27 @@ async fn calendar_context(
///
/// 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.
+/// An event's alerts as Apple holds them: minutes before its start, `0` at the time.
+#[tauri::command]
+async fn event_alerts(
+ guid: String,
+ auth: State<'_, Auth>,
+ data: State<'_, Data>,
+) -> UiResult<Vec<i64>> {
+ let event = {
+ let library = data.0.lock().await;
+ library.event(&guid).map_err(|e| e.to_string())?
+ };
+ let Some(event) = event else {
+ return Ok(Vec::new());
+ };
+ let (http, root, params) = calendar_context(&auth).await?;
+ quince_icloud::calendar::CalendarClient::new(&http, &root, params)
+ .alerts(&event)
+ .await
+ .map_err(|e| e.to_string())
+}
+
#[tauri::command]
async fn event_save(
draft: EventDraft,
@@ -414,9 +439,16 @@ async fn event_save(
};
let ctag = quince_icloud::sync::calendar_ctag(&*data.0.lock().await, &event.calendar_guid);
- let kept = quince_icloud::sync::save_event(&http, &root, params, ctag.as_deref(), &event)
- .await
- .map_err(|e| e.to_string())?;
+ let kept = quince_icloud::sync::save_event_with_alerts(
+ &http,
+ &root,
+ params,
+ ctag.as_deref(),
+ &event,
+ draft.alerts.as_deref(),
+ )
+ .await
+ .map_err(|e| e.to_string())?;
let mut library = data.0.lock().await;
quince_icloud::sync::store_events(&mut library, kept).map_err(|e| e.to_string())?;
Ok(guid)
@@ -2317,6 +2349,7 @@ fn main() {
calendar_sync,
calendar_events,
event_save,
+ event_alerts,
event_delete,
calendar_list,
calendar_search,
diff --git a/src/components/Picker.tsx b/src/components/Picker.tsx
index 2a90c25..94beb48 100644
--- a/src/components/Picker.tsx
+++ b/src/components/Picker.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useId, useRef, useState } from "react";
+import { useCallback, useEffect, useId, useLayoutEffect, useRef, useState } from "react";
export type PickerOption = { value: string; label: string };
@@ -39,6 +39,17 @@ export function Picker({
const current = options.find((o) => o.value === value);
+ // Where there is room: below, as usual, or above when the menu would run off the bottom of
+ // the window — near the foot of a popover it did, and its choices could not be reached.
+ const menu = useRef<HTMLUListElement | null>(null);
+ const [up, setUp] = useState(false);
+ useLayoutEffect(() => {
+ if (!open || !menu.current || !button.current) return;
+ const b = button.current.getBoundingClientRect();
+ const h = menu.current.getBoundingClientRect().height;
+ setUp(b.bottom + 4 + h > window.innerHeight - 8 && b.top - 4 - h > 8);
+ }, [open]);
+
const close = useCallback(
(restoreFocus: boolean) => {
setOpen(false);
@@ -133,7 +144,7 @@ export function Picker({
</button>
{open && (
- <ul className="picker-menu" role="listbox" id={listId} aria-label={label}>
+ <ul ref={menu} className={`picker-menu${up ? " is-up" : ""}`} role="listbox" id={listId} aria-label={label}>
{options.map((option, index) => (
<li
key={option.value}
diff --git a/src/lib/ipc.ts b/src/lib/ipc.ts
index d1faf2c..fe1844a 100644
--- a/src/lib/ipc.ts
+++ b/src/lib/ipc.ts
@@ -74,6 +74,7 @@ export const api = {
services: () => invoke<string[]>("account_services"),
eventSave: (draft: EventWrite) => invoke<string>("event_save", { draft }),
+ eventAlerts: (guid: string) => invoke<number[]>("event_alerts", { guid }),
eventDelete: (guid: string) => invoke<void>("event_delete", { guid }),
calendarSync: (from: string, to: string, timezone: string) =>
invoke<SyncSummary>("calendar_sync", { from, to, timezone }),
@@ -216,6 +217,9 @@ export type EventWrite = {
timezone: string | null;
notes: string | null;
url: string | null;
+ /** Set the alerts to exactly these minutes before the start (0 at the time); left out,
+ * the event keeps the alerts Apple holds. */
+ alerts?: number[];
};
export type CalendarEvent = {
diff --git a/src/screens/calendar/CalendarView.tsx b/src/screens/calendar/CalendarView.tsx
index b8298dd..52a38bc 100644
--- a/src/screens/calendar/CalendarView.tsx
+++ b/src/screens/calendar/CalendarView.tsx
@@ -32,6 +32,33 @@ import {
const ZONE = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
+/** icloud.com's alert presets, minutes before the start; an all-day event's are by the day. */
+const ALERTS = [
+ { minutes: 0, label: "At time of event" },
+ { minutes: 5, label: "5 minutes before" },
+ { minutes: 15, label: "15 minutes before" },
+ { minutes: 30, label: "30 minutes before" },
+ { minutes: 60, label: "1 hour before" },
+ { minutes: 120, label: "2 hours before" },
+ { minutes: 1440, label: "1 day before" },
+ { minutes: 2880, label: "2 days before" },
+];
+const ALL_DAY_ALERTS = [
+ { minutes: 0, label: "On day of event" },
+ { minutes: 1440, label: "1 day before" },
+ { minutes: 2880, label: "2 days before" },
+ { minutes: 10080, label: "1 week before" },
+];
+/** An alert Apple holds that no preset names — set on a phone, say. */
+function alertLabel(m: number): string {
+ if (m === 0) return "At time of event";
+ const after = m < 0;
+ const a = Math.abs(m);
+ const text = a % 1440 === 0 ? `${a / 1440} day${a === 1440 ? "" : "s"}`
+ : a % 60 === 0 ? `${a / 60} hour${a === 60 ? "" : "s"}` : `${a} minutes`;
+ return `${text} ${after ? "after" : "before"}`;
+}
+
/** Apple's four scopes, in Apple's order. */
const VIEWS = [
{ key: "day", label: "Day" },
@@ -81,6 +108,11 @@ type Draft = {
/** The zone the event was made in. Sending this machine's instead moved a meeting set in
* New York to local time on every edit, on every device. New events take this machine's. */
timezone: string | null;
+ /** The alerts, minutes before the start; `undefined` until read from Apple — and while
+ * undefined a save leaves them as they are, so a slow read can never clear them. */
+ alerts?: number[];
+ /** Whether the alerts were changed here, and so are to be written. */
+ alertsChanged?: boolean;
};
/**
@@ -349,6 +381,7 @@ export function CalendarView() {
timezone: d.allDay ? ZONE : (d.timezone ?? ZONE),
notes: d.notes.trim() || null,
url: d.url?.trim() || null,
+ ...(d.alertsChanged && d.alerts ? { alerts: d.alerts } : {}),
});
}, (rows) => {
// Shown where it now sits at once; a new one is drawn by its draft until Apple names it.
@@ -389,8 +422,15 @@ export function CalendarView() {
}, [undo]);
const openDraft = (d: Draft, at: Anchor) => {
- setDraft(d);
+ setDraft(d.guid ? d : { ...d, alerts: [] });
setAnchor(at);
+ const guid = d.guid;
+ if (guid && !guid.startsWith("quince:")) {
+ api.eventAlerts(guid).then(
+ (alerts) => setDraft((cur) => (cur && cur.guid === guid && !cur.alertsChanged ? { ...cur, alerts } : cur)),
+ () => {},
+ );
+ }
};
const newAt = (startsAt: number, endsAt: number, allDay: boolean, at: Anchor) => {
if (!target) return;
@@ -1722,6 +1762,37 @@ function EventPopover({
options={choices.map((c) => ({ value: c.guid, label: c.title }))}
/>
</div>
+ {/* Alert, and a second once there is a first — icloud.com's own pair and presets. */}
+ {[0, 1].map((n) => {
+ const alerts = draft.alerts;
+ if (n === 1 && !(alerts && alerts.length >= 1)) return null;
+ const presets = draft.allDay ? ALL_DAY_ALERTS : ALERTS;
+ const current = alerts?.[n];
+ const options = [
+ { value: "none", label: "None" },
+ ...presets.map((p) => ({ value: String(p.minutes), label: p.label })),
+ ...(current !== undefined && !presets.some((p) => p.minutes === current)
+ ? [{ value: String(current), label: alertLabel(current) }]
+ : []),
+ ];
+ return (
+ <div className="cx-pop-row cal-field" key={`alert${n}`}>
+ <span>{n === 0 ? "alert" : "2nd alert"}</span>
+ <Picker
+ label={n === 0 ? "Alert" : "Second alert"}
+ value={alerts === undefined ? "loading" : current === undefined ? "none" : String(current)}
+ disabled={!editable || alerts === undefined}
+ onChange={(v) => {
+ const next = [...(alerts ?? [])];
+ if (v === "none") next.splice(n, 1);
+ else next[n] = Number(v);
+ set({ alerts: next.slice(0, 2), alertsChanged: true });
+ }}
+ options={alerts === undefined ? [{ value: "loading", label: "…" }] : options}
+ />
+ </div>
+ );
+ })}
</div>
<input
className="cx-pop-line"
diff --git a/src/styles/app.css b/src/styles/app.css
index 7f7a593..2a1824b 100644
--- a/src/styles/app.css
+++ b/src/styles/app.css
@@ -1806,3 +1806,4 @@
.drive > .cal-bar .with-glyph:not(.primary) { font-size: 0; gap: 0; padding-inline: 8px; }
.drive > .cal-bar .with-glyph:not(.primary) svg { font-size: initial; }
}
+.picker-menu.is-up { top: auto; bottom: calc(100% + 4px); }