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: an audit of sync and writes, and its fixes

Yashwanth Kamireddic4f5fbca8096
diff --git a/.uiverify/calendar-model.test.mjs b/.uiverify/calendar-model.test.mjs
index 558ede8..9bd452d 100644
--- a/.uiverify/calendar-model.test.mjs
+++ b/.uiverify/calendar-model.test.mjs
@@ -117,3 +117,11 @@ test("a zone named as Calendar names it", () => {
assert.deepEqual(zoneName("America/New_York", Z(2026, 10, 21, 0, 0)), { city: "New York", offset: "GMT−4" });
assert.deepEqual(zoneName("UTC", Z(2026, 10, 21, 0, 0)).offset, "GMT");
});
+import { addDaysIn } from "../src/screens/calendar/model.ts";
+test("a day on is a calendar day, across a clock change too", () => {
+ // Fri 30 Oct 2026, all day in New York, a week on: Fri 6 Nov at midnight, not Thu at 23:00.
+ const fri = Z(2026, 10, 30, 4, 0);
+ assert.equal(addDaysIn("America/New_York", fri, 7), Z(2026, 11, 6, 5, 0));
+ assert.equal(addDaysIn("Asia/Kolkata", Z(2026, 10, 21, 3, 30), 1), Z(2026, 10, 22, 3, 30));
+ assert.equal(addDaysIn("America/New_York", Z(2026, 10, 31, 4, 0), 1), Z(2026, 11, 1, 4, 0));
+});
diff --git a/crates/quince-icloud/src/calendar.rs b/crates/quince-icloud/src/calendar.rs
index 6a5d789..757f811 100644
--- a/crates/quince-icloud/src/calendar.rs
+++ b/crates/quince-icloud/src/calendar.rs
@@ -128,11 +128,14 @@ fn collection_from(v: &Value) -> Option<Calendar> {
/// day wherever it is looked at, as on the phone. Read as midnight UTC (measured: the account
/// stores it so), it fell on the day before for anyone west of Greenwich. So all-day dates are
/// this machine's own midnight, which is where the interface draws a day.
+///
+/// A timed event with no zone floats, as Calendar calls it: 9:00 wherever it is looked at.
+/// Read as UTC it was drawn hours off, and an edit wrote that wrong instant back, moving the
+/// meeting on every device. So it too is this machine's clock.
fn dates_zone(all_day: bool, timezone: Option<&str>) -> Option<String> {
- if all_day {
- TimeZone::system().iana_name().map(ToString::to_string)
- } else {
- timezone.map(ToString::to_string)
+ match timezone {
+ Some(zone) if !all_day => Some(zone.to_string()),
+ _ => TimeZone::system().iana_name().map(ToString::to_string),
}
}
@@ -488,6 +491,25 @@ impl<'a> CalendarClient<'a> {
repeat: Option<Option<&EventRepeat>>,
scope: Option<Scope>,
) -> Result<Snapshot> {
+ self.put_event_moved(event, ctag, alerts, repeat, scope, None)
+ .await
+ }
+
+ /// [`Self::put_event_full`] for an event that may be moving from another calendar:
+ /// `from` is that calendar and its ctag. As icloud.com moves one: the event is read where it
+ /// is, named with `oldpGuid`, and both calendars go in the client state. Read under the
+ /// new calendar it was not found, and was rebuilt from nothing — its alerts, guests and
+ /// repeat gone — and written as a second event.
+ pub async fn put_event_moved(
+ &self,
+ event: &Event,
+ ctag: Option<&str>,
+ alerts: Option<&[i64]>,
+ repeat: Option<Option<&EventRepeat>>,
+ scope: Option<Scope>,
+ from: Option<(&str, Option<&str>)>,
+ ) -> Result<Snapshot> {
+ let from = from.filter(|(old, _)| *old != event.calendar_guid);
// One occurrence of a repeating event, sent as though it were an event of its own,
// made Apple take it as the whole series — measured: a weekly event three times over
// came back one event, repeating no more. An occurrence is changed only with its
@@ -518,7 +540,14 @@ impl<'a> CalendarClient<'a> {
// repeats in — and Apple takes the whole event on every write. Building one from
// our own fields alone did not merely drop those, it cleared them: a weekly meeting
// edited here came back a one-off with no alerts and no guests.
- let detail = self.event_detail_body(event, &day).await?;
+ let detail = match from {
+ Some((old, _)) => {
+ let mut there = event.clone();
+ there.calendar_guid = old.to_string();
+ self.event_detail_body(&there, &day).await?
+ }
+ None => self.event_detail_body(event, &day).await?,
+ };
let existing = detail.as_ref().and_then(event_of);
// For the whole series from one of its occurrences, the series keeps its own dates —
// icloud.com sends the master's start and end — moved by however far this occurrence
@@ -582,11 +611,9 @@ impl<'a> CalendarClient<'a> {
.unwrap_or_default();
let alarms: Vec<Value> = match alerts {
None => held,
- Some(minutes) => minutes
- .iter()
- .take(2) // as icloud.com allows: an alert and a second alert
- .map(|m| alarm_for(&owner, *m))
- .collect(),
+ // Every one asked for: icloud.com shows two, but an event made on a Mac can hold
+ // more, and cutting to two deleted the rest from every device.
+ Some(minutes) => minutes.iter().map(|m| alarm_for(&owner, *m)).collect(),
};
// Only a change of alerts rewrites the event's list of them; otherwise it goes back
// exactly as Apple sent it, beside the alert objects it names.
@@ -602,6 +629,12 @@ impl<'a> CalendarClient<'a> {
"Event": event_value,
"ClientState": client_state(&event.calendar_guid, ctag),
});
+ if let Some((old, old_ctag)) = from {
+ body["Event"]["oldpGuid"] = Value::from(old);
+ if let Some(list) = body["ClientState"]["Collection"].as_array_mut() {
+ list.push(serde_json::json!({ "guid": old, "ctag": old_ctag }));
+ }
+ }
if !alarms.is_empty() {
body["Alarm"] = Value::Array(alarms);
}
diff --git a/crates/quince-icloud/src/sync.rs b/crates/quince-icloud/src/sync.rs
index 2f60938..83ddb58 100644
--- a/crates/quince-icloud/src/sync.rs
+++ b/crates/quince-icloud/src/sync.rs
@@ -156,7 +156,7 @@ pub async fn save_event(
ctag: Option<&str>,
event: &quince_core::calendar::Event,
) -> Result<Vec<quince_core::calendar::Event>> {
- save_event_with_alerts(http, root, params, ctag, event, None, None, None).await
+ save_event_with_alerts(http, root, params, ctag, event, None, None, None, None).await
}
/// [`save_event`], with the event's alerts set to `alerts` when given.
@@ -170,10 +170,11 @@ pub async fn save_event_with_alerts(
alerts: Option<&[i64]>,
repeat: Option<Option<&crate::calendar::EventRepeat>>,
scope: Option<crate::calendar::Scope>,
+ from: Option<(&str, Option<&str>)>,
) -> Result<Vec<quince_core::calendar::Event>> {
let client = CalendarClient::new(http, root, params);
let answer = client
- .put_event_full(event, ctag, alerts, repeat, scope)
+ .put_event_moved(event, ctag, alerts, repeat, scope, from)
.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
@@ -186,13 +187,30 @@ pub async fn save_event_with_alerts(
let zone = crate::calendar::event_zone(event);
let day = crate::calendar::day_of(event.starts_at, zone.as_deref());
let tz = zone.as_deref().unwrap_or("UTC");
+ // A repeat set or cleared, or a series split, gives the day's occurrence another id than
+ // the one sent (`S` and `S__<start>` are one series): found by its series, not its id.
+ let series = event
+ .guid
+ .split("__")
+ .next()
+ .unwrap_or(&event.guid)
+ .to_string();
+ let reshaped = repeat.is_some() || scope.is_some() || series != event.guid;
let kept: Vec<_> = client
.events(&day, &day, tz)
.await?
.events
.into_iter()
- .filter(|e| e.guid == event.guid)
+ .filter(|e| {
+ e.guid == event.guid
+ || (reshaped && (e.guid == series || e.guid.starts_with(&format!("{series}__"))))
+ })
.collect();
+ // A series split ("this and future") lands under a new id Apple chooses: saved all the same,
+ // and the next pass brings it.
+ if kept.is_empty() && reshaped {
+ return Ok(kept);
+ }
if kept.is_empty() {
return Err(Error::Protocol(
"iCloud took the event but did not keep it — nothing was saved".into(),
diff --git a/probe/examples/calendar_move_live.rs b/probe/examples/calendar_move_live.rs
new file mode 100644
index 0000000..21fe8e2
--- /dev/null
+++ b/probe/examples/calendar_move_live.rs
@@ -0,0 +1,144 @@
+//! Live, throwaway event only: made with an alert in one calendar, moved to another as the app
+//! moves one, and read back — one event, in the new calendar, its alert kept — then deleted.
+use anyhow::{anyhow, Result};
+use quince_core::calendar::Event;
+
+#[tokio::main]
+async fn main() -> Result<()> {
+ let dir = std::path::PathBuf::from(std::env::var("HOME")?).join(".local/share/quince-probe");
+ let mut client = quince_auth::Client::new(&dir)?;
+ if !client.resume().await? {
+ return Err(anyhow!("no session"));
+ }
+ let root = client
+ .session()
+ .service_url("calendar")
+ .ok_or_else(|| anyhow!("no calendar"))?;
+ let (http, params) = (client.http().clone(), client.service_params());
+ let tz = jiff::tz::TimeZone::system()
+ .iana_name()
+ .unwrap_or("UTC")
+ .to_string();
+ let today = jiff::Zoned::now().date();
+ let (from, to) = (
+ today.to_string(),
+ today.saturating_add(jiff::Span::new().days(3)).to_string(),
+ );
+ let read = || {
+ let (http, root, params, from, to, tz) = (&http, &root, params.clone(), &from, &to, &tz);
+ async move { quince_icloud::sync::fetch_calendar(http, root, params, from, to, tz).await }
+ };
+ let snap = read().await?;
+ let writable: Vec<_> = snap.calendars.iter().filter(|c| c.writable).collect();
+ let [a, b, ..] = writable.as_slice() else {
+ return Err(anyhow!("two writable calendars are needed"));
+ };
+ let start = jiff::Timestamp::now().as_second() + 86_400;
+ let start = start - start % 3600;
+ let mut event = Event {
+ guid: uuid::Uuid::new_v4().to_string().to_uppercase(),
+ calendar_guid: a.guid.clone(),
+ title: "Quince move test — safe to delete".into(),
+ location: None,
+ starts_at: start,
+ ends_at: start + 1800,
+ all_day: false,
+ timezone: Some(tz.clone()),
+ url: None,
+ notes: None,
+ etag: None,
+ };
+ let cal = quince_icloud::calendar::CalendarClient::new(&http, &root, params.clone());
+ quince_icloud::sync::save_event_with_alerts(
+ &http,
+ &root,
+ params.clone(),
+ a.ctag.as_deref(),
+ &event,
+ Some(&[15]),
+ None,
+ None,
+ None,
+ )
+ .await?;
+ let result = async {
+ let made = read().await?;
+ let held = made
+ .events
+ .iter()
+ .find(|e| e.guid == event.guid)
+ .ok_or_else(|| anyhow!("not made"))?
+ .clone();
+ println!(
+ "made in {:?}, alerts {:?}",
+ a.title,
+ cal.alerts(&held).await?
+ );
+ // Moved as the app moves one: its etag, and where it was.
+ event.etag = held.etag.clone();
+ event.calendar_guid = b.guid.clone();
+ let a_tag = made
+ .calendars
+ .iter()
+ .find(|c| c.guid == a.guid)
+ .and_then(|c| c.ctag.clone());
+ let b_tag = made
+ .calendars
+ .iter()
+ .find(|c| c.guid == b.guid)
+ .and_then(|c| c.ctag.clone());
+ quince_icloud::sync::save_event_with_alerts(
+ &http,
+ &root,
+ params.clone(),
+ b_tag.as_deref(),
+ &event,
+ None,
+ None,
+ None,
+ Some((a.guid.as_str(), a_tag.as_deref())),
+ )
+ .await?;
+ let after = read().await?;
+ let copies: Vec<_> = after
+ .events
+ .iter()
+ .filter(|e| e.guid == event.guid || e.title == event.title)
+ .collect();
+ println!(
+ "after the move: {} cop{}, in {:?}",
+ copies.len(),
+ if copies.len() == 1 { "y" } else { "ies" },
+ copies
+ .iter()
+ .map(|e| e.calendar_guid == b.guid)
+ .collect::<Vec<_>>()
+ );
+ anyhow::ensure!(copies.len() == 1 && copies[0].calendar_guid == b.guid);
+ let alerts = cal.alerts(copies[0]).await?;
+ println!("its alerts: {alerts:?}");
+ anyhow::ensure!(alerts == vec![15]);
+ anyhow::Ok(())
+ }
+ .await;
+ // Away, wherever it is.
+ let last = read().await?;
+ for e in last.events.iter().filter(|e| e.title == event.title) {
+ let tag = last
+ .calendars
+ .iter()
+ .find(|c| c.guid == e.calendar_guid)
+ .and_then(|c| c.ctag.clone());
+ cal.delete_event(e, tag.as_deref()).await?;
+ }
+ let left = read()
+ .await?
+ .events
+ .iter()
+ .filter(|e| e.title == event.title)
+ .count();
+ println!("{left} left behind");
+ result?;
+ anyhow::ensure!(left == 0);
+ Ok(())
+}
diff --git a/probe/examples/calendar_roundtrip.rs b/probe/examples/calendar_roundtrip.rs
index d608e07..be04b6d 100644
--- a/probe/examples/calendar_roundtrip.rs
+++ b/probe/examples/calendar_roundtrip.rs
@@ -63,8 +63,10 @@ async fn main() -> Result<()> {
calendar_guid: calendar.guid.clone(),
title: "Quince all day — safe to delete".into(),
location: None,
- starts_at: start - start % 86_400,
- ends_at: start - start % 86_400 + 86_400,
+ // A day on the calendar is this machine's midnight to midnight, as Quince reads
+ // an all-day event (Apple keeps no zone on one).
+ starts_at: local_midnight(start),
+ ends_at: local_midnight(start + 86_400),
all_day: true,
timezone: Some(tz.clone()),
url: None,
@@ -145,3 +147,13 @@ async fn main() -> Result<()> {
println!("every field survived the round trip, and nothing was left behind");
Ok(())
}
+
+/// The local midnight starting the day `s` falls on.
+fn local_midnight(s: i64) -> i64 {
+ let zoned = jiff::Timestamp::from_second(s)
+ .unwrap_or(jiff::Timestamp::UNIX_EPOCH)
+ .to_zoned(jiff::tz::TimeZone::system());
+ zoned
+ .start_of_day()
+ .map_or(s, |z| z.timestamp().as_second())
+}
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 21b986d..50e028a 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -712,6 +712,28 @@ pub async fn same_account(app: &tauri::AppHandle) -> bool {
session.is_some() && session == owner
}
+/// The account the session is signed in to now, as the library records its owner.
+async fn account_now(auth: &Auth) -> Option<String> {
+ auth.client
+ .lock()
+ .await
+ .session()
+ .dsid
+ .as_deref()
+ .map(account_tag)
+}
+
+/// Whether the library still belongs to `account`, taken when a command began: a result that
+/// came back after a sign-out, or another account's sign-in, is never stored over its data.
+fn still_owned(library: &quince_core::Library, account: Option<&str>) -> Result<(), String> {
+ let owner = library.state(ACCOUNT_KEY).ok().flatten();
+ if account.is_some() && owner.as_deref() == account {
+ Ok(())
+ } else {
+ Err("Signed out while this was on its way, so nothing was stored.".into())
+ }
+}
+
/// Signed in, then the library made this account's; if it could not be, signed out again with
/// the reason, never left signed in over someone else's data.
async fn signed_in(app: &tauri::AppHandle, client: &mut Client) -> Result<(), String> {
@@ -1012,6 +1034,7 @@ async fn calendar_sync(
) -> 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 account = account_now(&auth).await;
let (http, root, params) = {
let client = auth.client.lock().await;
let root = client
@@ -1027,6 +1050,7 @@ async fn calendar_sync(
.await
.map_err(|e| e.to_string())?;
let mut library = data.0.lock().await;
+ still_owned(&library, account.as_deref())?;
quince_icloud::sync::apply_calendar(&mut library, fetched).map_err(|e| e.to_string())
}
@@ -1132,9 +1156,11 @@ async fn event_save(
if draft.ends_at < draft.starts_at {
return Err("An event can't end before it starts.".into());
}
+ let account = account_now(&auth).await;
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 was_saved = draft.guid.is_some();
let guid = draft
.guid
.unwrap_or_else(|| uuid::Uuid::new_v4().to_string().to_uppercase());
@@ -1142,6 +1168,16 @@ async fn event_save(
let library = data.0.lock().await;
library.event(&guid).map_err(|e| e.to_string())?
};
+ // An event opened as one already saved, and no longer here: deleted on another device
+ // since. Saved, it came back as new on every device, without its alerts or guests.
+ if was_saved && existing.is_none() && !quince_icloud::calendar::is_occurrence(&guid) {
+ return Err("This event was deleted on another device, so it wasn’t saved.".into());
+ }
+ // The calendar it is in now, when that is not the one it is saved to: a move.
+ let moved_from = existing
+ .as_ref()
+ .map(|e| e.calendar_guid.clone())
+ .filter(|old| *old != draft.calendar_guid);
let event = Event {
guid: guid.clone(),
@@ -1160,6 +1196,14 @@ async fn event_save(
};
let ctag = quince_icloud::sync::calendar_ctag(&*data.0.lock().await, &event.calendar_guid);
+ // Moving to another calendar: where it is now, and that calendar's tag.
+ let from = match moved_from {
+ Some(old) => {
+ let tag = quince_icloud::sync::calendar_ctag(&*data.0.lock().await, &old);
+ Some((old, tag))
+ }
+ None => None,
+ };
let kept = quince_icloud::sync::save_event_with_alerts(
&http,
&root,
@@ -1169,10 +1213,13 @@ async fn event_save(
draft.alerts.as_deref(),
draft.repeat_changed.then_some(draft.repeat.as_ref()),
draft.scope,
+ from.as_ref()
+ .map(|(old, tag)| (old.as_str(), tag.as_deref())),
)
.await
.map_err(|e| e.to_string())?;
let mut library = data.0.lock().await;
+ still_owned(&library, account.as_deref())?;
quince_icloud::sync::store_events(&mut library, kept).map_err(|e| e.to_string())?;
Ok(guid)
}
@@ -1184,6 +1231,7 @@ async fn event_delete(
auth: State<'_, Auth>,
data: State<'_, Data>,
) -> UiResult<()> {
+ let account = account_now(&auth).await;
let _one = CALENDAR_PASS.lock().await;
let (http, root, params) = calendar_context(&auth).await?;
let event = {
@@ -1202,6 +1250,7 @@ async fn event_delete(
// for this-and-future — not just the one day, which left the rest of a deleted series on
// screen until the next sync.
let mut library = data.0.lock().await;
+ still_owned(&library, account.as_deref())?;
let series = quince_icloud::calendar::series_of(&event.guid).to_string();
let gone: Vec<String> = match scope {
Some(quince_icloud::calendar::Scope::All)
diff --git a/src/screens/calendar/CalendarView.tsx b/src/screens/calendar/CalendarView.tsx
index b9c94f1..64eab73 100644
--- a/src/screens/calendar/CalendarView.tsx
+++ b/src/screens/calendar/CalendarView.tsx
@@ -18,6 +18,7 @@ import { Picker } from "../../components/Picker";
import { RowMenu } from "../../components/RowMenu";
import {
addDays,
+ addDaysIn,
allZones,
clock,
dateOf,
@@ -294,7 +295,8 @@ export function CalendarView() {
draftRef.current = draft;
const [anchor, setAnchor] = useState<Anchor | null>(null);
/** The last event deleted, held so the deletion can be taken back. */
- const [undo, setUndo] = useState<CalendarEvent | null>(null);
+ /** The last event deleted, with its alerts, held so the deletion can be taken back. */
+ const [undo, setUndo] = useState<(CalendarEvent & { alerts: number[] }) | null>(null);
const { revision } = useSync();
// The current-time line moves once a minute, on the minute — not on a busy timer.
@@ -504,7 +506,7 @@ export function CalendarView() {
title: d.title.trim() || "New Event",
location: d.location.trim() || null,
startsAt: d.startsAt,
- endsAt: Math.max(d.endsAt, d.startsAt + (d.allDay ? 86_400 : 900)),
+ endsAt: Math.max(d.endsAt, (d.allDay ? addDaysIn(ZONE, d.startsAt, 1) : d.startsAt + 900)),
allDay: d.allDay,
timezone: d.allDay ? ZONE : (d.timezone ?? ZONE),
notes: d.notes.trim() || null,
@@ -518,7 +520,7 @@ export function CalendarView() {
return [...rows, {
guid: `pending:${d.startsAt}:${d.title}`, calendarGuid: d.calendarGuid,
title: d.title.trim() || "New Event", location: d.location.trim() || null,
- startsAt: d.startsAt, endsAt: Math.max(d.endsAt, d.startsAt + (d.allDay ? 86_400 : 900)),
+ startsAt: d.startsAt, endsAt: Math.max(d.endsAt, (d.allDay ? addDaysIn(ZONE, d.startsAt, 1) : d.startsAt + 900)),
allDay: d.allDay, timezone: d.allDay ? ZONE : (d.timezone ?? ZONE),
url: d.url?.trim() || null, notes: d.notes.trim() || null, etag: null,
}];
@@ -535,7 +537,7 @@ export function CalendarView() {
} : e.guid === d.guid ? {
...e, calendarGuid: d.calendarGuid, title: d.title.trim() || "New Event",
location: d.location.trim() || null, startsAt: d.startsAt,
- endsAt: Math.max(d.endsAt, d.startsAt + (d.allDay ? 86_400 : 900)),
+ endsAt: Math.max(d.endsAt, (d.allDay ? addDaysIn(ZONE, d.startsAt, 1) : d.startsAt + 900)),
allDay: d.allDay, notes: d.notes.trim() || null,
} : e);
});
@@ -553,6 +555,12 @@ export function CalendarView() {
const occurrence = guid.includes("__");
const scope = occurrence ? await whichEvents("delete") : null;
if (occurrence && !scope) return;
+ // Its alerts, for Undo to make it again with them: read before it is gone.
+ const alerts = occurrence
+ ? []
+ : draftRef.current?.guid === guid && draftRef.current.alerts
+ ? draftRef.current.alerts
+ : await api.eventAlerts(guid).catch(() => [] as number[]);
setDraft(null);
// All of a series leaves every one of its days; one, only itself.
const series = guid.split("__")[0];
@@ -565,7 +573,7 @@ export function CalendarView() {
)) {
// Undo makes the event again; for one day out of a series that would be a new event,
// not the day put back, so it is not offered.
- if (!occurrence) setUndo(gone);
+ if (!occurrence && gone) setUndo({ ...gone, alerts });
}
},
[events, write]
@@ -573,7 +581,8 @@ export function CalendarView() {
const takeBack = useCallback(async () => {
const gone = undo;
setUndo(null);
- if (gone) await save({ ...draftOf(gone), guid: null });
+ // Made again as it was, its alerts with it (its guests are not this app's to invite).
+ if (gone) await save({ ...draftOf(gone), guid: null, alerts: gone.alerts, alertsChanged: gone.alerts.length > 0 });
}, [undo, save]);
useEffect(() => {
if (!undo) return undefined;
@@ -1046,7 +1055,9 @@ export function CalendarView() {
onDelete={draft.guid ? () => void remove(draft.guid as string) : undefined}
onNudge={draft.guid ? (by) => {
// Calendar's Control-Option-arrows: the open event moves, stays open, and is saved.
- const moved = { ...draft, startsAt: draft.startsAt + by, endsAt: draft.endsAt + by };
+ const zone = zoneOf(draft);
+ const shift = (t: number) => ("days" in by ? addDaysIn(zone, t, by.days) : t + by.minutes * 60);
+ const moved = { ...draft, startsAt: shift(draft.startsAt), endsAt: shift(draft.endsAt) };
setDraft(moved);
void save(moved);
} : undefined}
@@ -1995,7 +2006,7 @@ function EventPopover({
onClose: () => void;
onSave: () => void;
onDelete?: () => void;
- onNudge?: (bySeconds: number) => void;
+ onNudge?: (by: { days: number } | { minutes: number }) => void;
view?: string;
}) {
const box = useRef<HTMLFormElement | null>(null);
@@ -2026,8 +2037,14 @@ function EventPopover({
if (e.key === "Escape") return onClose();
// Up/Down: fifteen minutes in Day and Week, a week in Month. Left/Right: a day.
if (e.ctrlKey && e.altKey && onNudge && editable && e.key.startsWith("Arrow")) {
- const step = view === "month" || draft.allDay ? 7 * 86_400 : 15 * 60;
- const by = { ArrowUp: -step, ArrowDown: step, ArrowLeft: -86_400, ArrowRight: 86_400 }[e.key];
+ // A day is a calendar day on the event's clock, never a fixed 86,400 seconds.
+ const week = view === "month" || draft.allDay;
+ const by = {
+ ArrowUp: week ? { days: -7 } : { minutes: -15 },
+ ArrowDown: week ? { days: 7 } : { minutes: 15 },
+ ArrowLeft: { days: -1 },
+ ArrowRight: { days: 1 },
+ }[e.key];
if (by) {
e.preventDefault();
onNudge(by);
@@ -2213,7 +2230,8 @@ function EventPopover({
const next = [...(alerts ?? [])];
if (v === "none") next.splice(n, 1);
else next[n] = Number(v);
- set({ alerts: next.slice(0, 2), alertsChanged: true });
+ // Any beyond the two shown (made on a Mac) are kept, never dropped by an edit here.
+ set({ alerts: next, alertsChanged: true });
}}
options={alerts === undefined ? [{ value: "loading", label: "…" }] : options}
/>
diff --git a/src/screens/calendar/model.ts b/src/screens/calendar/model.ts
index 12b1d3e..a3f1942 100644
--- a/src/screens/calendar/model.ts
+++ b/src/screens/calendar/model.ts
@@ -262,3 +262,11 @@ export function zoneName(zone: string, s: number): { city: string; offset: strin
const offset = minutes === 0 ? "GMT" : `GMT${sign}${Math.floor(a / 60)}${a % 60 ? `:${String(a % 60).padStart(2, "0")}` : ""}`;
return { city, offset };
}
+
+/** `s` moved `days` calendar days in `zone`, at the same clock time — never a fixed 86,400
+ * seconds, which landed an hour off (an all-day event on the day before) across a clock change. */
+export function addDaysIn(zone: string, s: number, days: number): number {
+ const w = wallIn(zone, s);
+ const d = new Date(Date.UTC(w.y, w.m - 1, w.d + days));
+ return instantIn(zone, { y: d.getUTCFullYear(), m: d.getUTCMonth() + 1, d: d.getUTCDate(), h: w.h, min: w.min });
+}