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 event's time zone, set as Calendar sets one

Yashwanth Kamireddi59fb564c384d
diff --git a/.uiverify/calendar-model.test.mjs b/.uiverify/calendar-model.test.mjs
index 9ca6e52..558ede8 100644
--- a/.uiverify/calendar-model.test.mjs
+++ b/.uiverify/calendar-model.test.mjs
@@ -95,3 +95,25 @@ test("a time on the hour leaves off the minutes", () => {
assert.doesNotMatch(clock(at(2026, 8, 29, 15)), /:00/);
assert.match(clock(at(2026, 8, 29, 15, 30)), /30/);
});
+
+import { wallIn, instantIn, sameClockIn, zoneName } from "../src/screens/calendar/model.ts";
+const Z = (y, m, d, h, min) => Date.UTC(y, m - 1, d, h, min) / 1000;
+test("a clock reading in any zone, and back", () => {
+ assert.deepEqual(wallIn("America/New_York", Z(2026, 10, 21, 13, 0)), { y: 2026, m: 10, d: 21, h: 9, min: 0 });
+ assert.equal(instantIn("America/New_York", { y: 2026, m: 10, d: 21, h: 9, min: 0 }), Z(2026, 10, 21, 13, 0));
+ assert.equal(instantIn("Asia/Kolkata", { y: 2026, m: 10, d: 21, h: 9, min: 0 }), Z(2026, 10, 21, 3, 30));
+});
+test("a zone changed keeps the clock: 9:00 in Kolkata becomes 9:00 in New York", () => {
+ assert.equal(sameClockIn("Asia/Kolkata", "America/New_York", Z(2026, 10, 21, 3, 30)), Z(2026, 10, 21, 13, 0));
+});
+test("across a clock change: a skipped time an hour on, a doubled one the first time", () => {
+ // 2:30 on 8 March 2026 never shows in New York: 3:30 EDT.
+ assert.equal(instantIn("America/New_York", { y: 2026, m: 3, d: 8, h: 2, min: 30 }), Z(2026, 3, 8, 7, 30));
+ // 1:30 on 1 November 2026 shows twice: the first, still EDT.
+ assert.equal(instantIn("America/New_York", { y: 2026, m: 11, d: 1, h: 1, min: 30 }), Z(2026, 11, 1, 5, 30));
+});
+test("a zone named as Calendar names it", () => {
+ assert.deepEqual(zoneName("Asia/Kolkata", Z(2026, 10, 21, 0, 0)), { city: "Kolkata", offset: "GMT+5:30" });
+ 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");
+});
diff --git a/.uiverify/calendar-zone.mjs b/.uiverify/calendar-zone.mjs
new file mode 100644
index 0000000..ec4135a
--- /dev/null
+++ b/.uiverify/calendar-zone.mjs
@@ -0,0 +1,62 @@
+// An event's time zone, as Calendar sets one: the popover shows its city and offset, and its
+// times on that zone's clock; a zone found by typing a city replaces it and keeps the clock
+// time (10:00 in Kolkata becomes 10:00 in New York, nine and a half hours later), and the save
+// carries the zone and the moved instants to Apple. An all-day event has no zone row.
+import { engine } from "./engine.mjs";
+import { SERVICES, installStub, openScreen } from "./stub.mjs";
+const b = await engine.launch();
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };
+for (const scheme of ["light", "dark"]) {
+ const ctx = await b.newContext({ viewport: { width: 1300, height: 850 }, colorScheme: scheme, timezoneId: "Asia/Kolkata" });
+ await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, calendarFixture: true });
+ const page = await ctx.newPage();
+ page.on("pageerror", (e) => { console.log(`FAIL page error: ${e.message}`); process.exitCode = 1; });
+ await page.goto("http://localhost:4173", { waitUntil: "networkidle" });
+ await openScreen(page, "Calendar");
+ await page.keyboard.press("Control+2");
+ await page.waitForTimeout(300);
+ await page.locator(".cx-block", { hasText: "Design review" }).first().click();
+ await page.waitForTimeout(300);
+ const zone = page.getByRole("button", { name: /^Time zone:/ });
+ ok(/Kolkata, GMT\+5:30/.test(await zone.getAttribute("aria-label")), `${scheme}: the event's zone is shown (${await zone.getAttribute("aria-label")})`);
+ const time = () => page.getByRole("group", { name: "Starts time" }).or(page.getByLabel("Starts time")).first().innerText().catch(() => "");
+ const before = await page.evaluate(() => [...document.querySelectorAll(".cx-popover .cx-when")][0]?.innerText ?? "");
+ await zone.click();
+ await page.keyboard.type("new york");
+ await page.waitForTimeout(150);
+ // Cities that begin with what is typed come first: "lon" is London before Blanc-Sablon.
+ await page.keyboard.press("Control+a");
+ await page.keyboard.type("lon");
+ await page.waitForTimeout(150);
+ ok(/^London/.test((await page.getByRole("option").first().innerText()) ?? ""), `${scheme}: "lon" finds London first ${JSON.stringify(await page.getByRole("option").allInnerTexts())}`);
+ await page.keyboard.press("Control+a");
+ await page.keyboard.type("new york");
+ await page.waitForTimeout(150);
+ const options = await page.getByRole("option").allInnerTexts();
+ ok(options.some((o) => /New York/.test(o) && /GMT−4/.test(o)), `${scheme}: typing a city finds its zone ${JSON.stringify(options.slice(0, 3))}`);
+ await page.keyboard.press("Enter");
+ await page.waitForTimeout(150);
+ ok(/New York, GMT−4/.test(await zone.getAttribute("aria-label")), `${scheme}: chosen, the zone is New York`);
+ const timesNow = await page.evaluate(() => [...document.querySelectorAll(".cx-popover .cx-when")].map((w) => [...w.querySelectorAll("input, [role=spinbutton]")].map((i) => i.value ?? i.textContent).join(" ")));
+ await page.locator('input[placeholder="New Event"]').first().press("Enter");
+ await page.waitForTimeout(300);
+ const sent = await page.evaluate(() => window.__eventSaves?.at(-1));
+ const was = await page.evaluate(() => {
+ const base = Math.floor(new Date(new Date().setHours(0, 0, 0, 0)).getTime() / 1000) + 9 * 3600;
+ return base + 3600;
+ });
+ ok(sent?.timezone === "America/New_York" && sent.startsAt - was === 9.5 * 3600 && sent.endsAt - sent.startsAt === 3600,
+ `${scheme}: saved in New York at the same clock time, an hour long (${sent?.timezone}, moved ${(sent?.startsAt - was) / 3600} h) ${JSON.stringify(timesNow)}`);
+ // All day: a date, not an instant — no zone to set.
+ await page.locator(".cx-block", { hasText: "Dentist" }).first().click();
+ await page.waitForTimeout(300);
+ ok((await page.getByRole("button", { name: /^Time zone:/ }).count()) === 1, `${scheme}: a timed event has a zone row`);
+ await page.locator(".cx-popover").getByRole("checkbox").first().check();
+ await page.waitForTimeout(150);
+ ok((await page.getByRole("button", { name: /^Time zone:/ }).count()) === 0, `${scheme}: made all-day, it has none`);
+ await page.keyboard.press("Escape");
+ await ctx.close();
+}
+await b.close();
+process.exitCode = failures ? 1 : 0;
diff --git a/src/screens/calendar/CalendarView.tsx b/src/screens/calendar/CalendarView.tsx
index 44eadd1..b9c94f1 100644
--- a/src/screens/calendar/CalendarView.tsx
+++ b/src/screens/calendar/CalendarView.tsx
@@ -18,19 +18,24 @@ import { Picker } from "../../components/Picker";
import { RowMenu } from "../../components/RowMenu";
import {
addDays,
+ allZones,
clock,
dateOf,
dayKey,
hourLabel,
+ instantIn,
midnight,
monthDays,
placeDayWith,
+ sameClockIn,
sameDay,
seconds,
snap,
spansDays,
startOfWeek,
+ wallIn,
weekSpans,
+ zoneName,
} from "./model";
import { dateText, timeText } from "../../lib/when";
import { useReveal } from "../../lib/reveal";
@@ -186,12 +191,14 @@ const draftOf = (e: CalendarEvent): Draft => ({
/** `YYYY-MM-DDTHH:mm` and `YYYY-MM-DD` for the date inputs, in local time. */
const pad = (n: number) => String(n).padStart(2, "0");
+/** The zone an event's times are read in: its own, or this computer's (all-day events are
+ * dates, not instants, and read here). */
+const zoneOf = (d: { allDay: boolean; timezone: string | null }) => (d.allDay || !d.timezone ? ZONE : d.timezone);
const toLocalInput = (s: number, dateOnly: boolean) => {
const d = dateOf(s);
const day = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
return dateOnly ? day : `${day}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
};
-const fromLocalInput = (value: string) => seconds(new Date(value.length === 10 ? `${value}T00:00` : value));
const weekdayShort = (d: Date) => dateText(d, { weekday: "short" });
@@ -1833,23 +1840,29 @@ function YearView({
/* ---- the event popover ---------------------------------------------------------------- */
-/** A date and, unless it is all day, a time — two compact fields, as Calendar lays them out. */
+/** A date and, unless it is all day, a time — two compact fields, as Calendar lays them out —
+ * read on a clock in `zone`, the event's own. */
function When({
at,
allDay,
editable,
label,
+ zone,
onChange,
}: {
at: number;
allDay: boolean;
editable: boolean;
label: string;
+ zone: string;
onChange: (s: number) => void;
}) {
- const d = dateOf(at);
- const day = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
- const time = `${pad(d.getHours())}:${pad(d.getMinutes())}`;
+ const w = wallIn(zone, at);
+ const day = `${w.y}-${pad(w.m)}-${pad(w.d)}`;
+ const at_ = (date: string, h: number, min: number) => {
+ const [y, m, d] = date.split("-").map(Number);
+ return instantIn(zone, { y, m, d, h, min });
+ };
return (
<span className="cx-when">
<input
@@ -1857,21 +1870,113 @@ function When({
aria-label={`${label} date`}
value={day}
readOnly={!editable}
- onChange={(e) => e.target.value && onChange(fromLocalInput(`${e.target.value}T${time}`))}
+ onChange={(e) => e.target.value && onChange(at_(e.target.value, allDay ? 0 : w.h, allDay ? 0 : w.min))}
/>
{!allDay && (
<TimeField
label={`${label} time`}
- hours={d.getHours()}
- minutes={d.getMinutes()}
+ hours={w.h}
+ minutes={w.min}
disabled={!editable}
- onChange={(h, m) => onChange(fromLocalInput(`${day}T${pad(h)}:${pad(m)}`))}
+ onChange={(h, m) => onChange(at_(day, h, m))}
/>
)}
</span>
);
}
+/**
+ * An event's time zone, as Calendar sets one: its city and offset shown, and a field that
+ * finds any zone by city or region as it is typed. A zone chosen keeps the event's clock time
+ * (9:00 stays 9:00, now in that zone), as Calendar does.
+ */
+function ZoneField({ zone, at, editable, onChange }: { zone: string; at: number; editable: boolean; onChange: (z: string) => void }) {
+ const [query, setQuery] = useState<string | null>(null);
+ const [lit, setLit] = useState(0);
+ const named = zoneName(zone, at);
+ const found = useMemo(() => {
+ if (query === null) return [];
+ const q = query.trim().toLowerCase().replace(/\s+/g, "_");
+ const all = allZones();
+ if (!q) return [ZONE, ...all.filter((z) => z !== ZONE)].slice(0, 8);
+ // Cities that begin with what is typed first, then a word in one that does, then the rest.
+ const rank = (z: string) => {
+ const city = (z.split("/").pop() ?? z).toLowerCase();
+ if (city.startsWith(q)) return 0;
+ if (city.split(/[_-]/).some((w) => w.startsWith(q))) return 1;
+ return z.toLowerCase().includes(q) ? 2 : 3;
+ };
+ return all
+ .map((z) => [z, rank(z)] as const)
+ .filter(([, r]) => r < 3)
+ .sort((a, b) => a[1] - b[1] || (a[0].split("/").pop() ?? "").localeCompare(b[0].split("/").pop() ?? ""))
+ .map(([z]) => z)
+ .slice(0, 8);
+ }, [query]);
+ const choose = (z: string) => {
+ setQuery(null);
+ if (z !== zone) onChange(z);
+ };
+ if (query === null) {
+ return (
+ <button
+ type="button"
+ className="cx-zone"
+ aria-label={`Time zone: ${named.city}, ${named.offset}`}
+ disabled={!editable}
+ onClick={() => { setQuery(""); setLit(0); }}
+ >
+ <span>{named.city}</span>
+ <span className="cx-zone-offset">{named.offset}</span>
+ </button>
+ );
+ }
+ return (
+ <span className="cx-zone-find">
+ <input
+ autoFocus
+ type="search"
+ role="combobox"
+ aria-label="Find a time zone"
+ aria-expanded={found.length > 0}
+ aria-controls="cx-zones"
+ placeholder="City or region"
+ value={query}
+ onChange={(e) => { setQuery(e.target.value); setLit(0); }}
+ onBlur={() => setQuery(null)}
+ onKeyDown={(e) => {
+ if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); setQuery(null); }
+ else if (e.key === "ArrowDown") { e.preventDefault(); setLit((i) => Math.min(found.length - 1, i + 1)); }
+ else if (e.key === "ArrowUp") { e.preventDefault(); setLit((i) => Math.max(0, i - 1)); }
+ else if (e.key === "Enter" && found[lit]) { e.preventDefault(); choose(found[lit]); }
+ }}
+ />
+ {found.length > 0 && (
+ <span className="cx-zones" id="cx-zones" role="listbox" aria-label="Time zones">
+ {found.map((z, i) => {
+ const n = zoneName(z, at);
+ return (
+ <span
+ key={z}
+ role="option"
+ aria-selected={i === lit}
+ className={`cx-zone-option${i === lit ? " is-lit" : ""}`}
+ // Chosen before the field loses focus and closes the list.
+ onMouseDown={(e) => { e.preventDefault(); choose(z); }}
+ onMouseMove={() => setLit(i)}
+ >
+ <span>{n.city}</span>
+ <span className="cx-zone-region">{z.includes("/") ? z.split("/")[0].replace(/_/g, " ") : ""}</span>
+ <span className="cx-zone-offset">{n.offset}</span>
+ </span>
+ );
+ })}
+ </span>
+ )}
+ </span>
+ );
+}
+
function EventPopover({
draft,
at,
@@ -2042,6 +2147,7 @@ function EventPopover({
allDay={draft.allDay}
editable={editable}
label="Starts"
+ zone={zoneOf(draft)}
// Moving the start keeps the length, as Calendar does.
onChange={(startsAt) => set({ startsAt, endsAt: startsAt + (draft.endsAt - draft.startsAt) })}
/>
@@ -2053,11 +2159,26 @@ function EventPopover({
allDay={draft.allDay}
editable={editable}
label="Ends"
+ zone={zoneOf(draft)}
onChange={(end) =>
set({ endsAt: draft.allDay ? seconds(addDays(midnight(dateOf(end)), 1)) : Math.max(end, draft.startsAt + 300) })
}
/>
</div>
+ {!draft.allDay && (
+ <div className="cx-pop-row cal-field">
+ <span>time zone</span>
+ <ZoneField
+ zone={zoneOf(draft)}
+ at={draft.startsAt}
+ editable={editable}
+ onChange={(z) => {
+ const from = zoneOf(draft);
+ set({ timezone: z, startsAt: sameClockIn(from, z, draft.startsAt), endsAt: sameClockIn(from, z, draft.endsAt) });
+ }}
+ />
+ </div>
+ )}
<div className="cx-pop-row cal-field">
<span>calendar</span>
<Picker
diff --git a/src/screens/calendar/model.ts b/src/screens/calendar/model.ts
index af0e61c..12b1d3e 100644
--- a/src/screens/calendar/model.ts
+++ b/src/screens/calendar/model.ts
@@ -192,3 +192,73 @@ export function hourLabel(hour: number): string {
export const clock = (s: number) =>
timeText(dateOf(s), { hour: "numeric", minute: "2-digit" })
.replace(/:00(?=\D|$)/, "");
+
+/* ---- time zones ------------------------------------------------------------------------ */
+
+/** A clock reading: what a wall clock in some zone shows. */
+export type Wall = { y: number; m: number; d: number; h: number; min: number };
+
+const clocks = new Map<string, Intl.DateTimeFormat>();
+function clockIn(zone: string): Intl.DateTimeFormat {
+ let f = clocks.get(zone);
+ if (!f) {
+ f = new Intl.DateTimeFormat("en-US", {
+ timeZone: zone, hourCycle: "h23",
+ year: "numeric", month: "numeric", day: "numeric", hour: "numeric", minute: "numeric",
+ });
+ clocks.set(zone, f);
+ }
+ return f;
+}
+
+/** What a clock in `zone` shows at the instant `s` (seconds). */
+export function wallIn(zone: string, s: number): Wall {
+ const parts: Record<string, number> = {};
+ for (const p of clockIn(zone).formatToParts(new Date(s * 1000))) {
+ if (p.type !== "literal") parts[p.type] = Number(p.value);
+ }
+ return { y: parts.year, m: parts.month, d: parts.day, h: parts.hour % 24, min: parts.minute };
+}
+
+/**
+ * The instant a clock in `zone` shows `w`. A reading a clock skips (the hour lost in spring)
+ * comes out an hour on, as Calendar moves one; one a clock shows twice, the first time.
+ */
+export function instantIn(zone: string, w: Wall): number {
+ const asUtc = Date.UTC(w.y, w.m - 1, w.d, w.h, w.min) / 1000;
+ const offsetAt = (s: number) => {
+ const c = wallIn(zone, s);
+ return Date.UTC(c.y, c.m - 1, c.d, c.h, c.min) / 1000 - s;
+ };
+ // The two offsets either side of any clock change near it: a reading shown under both is
+ // taken the first time; one shown under neither (skipped) is taken an hour on.
+ const tries = [asUtc - offsetAt(asUtc - 86400), asUtc - offsetAt(asUtc + 86400)];
+ const same = (s: number) => {
+ const c = wallIn(zone, s);
+ return c.y === w.y && c.m === w.m && c.d === w.d && c.h === w.h && c.min === w.min;
+ };
+ const shown = tries.filter(same);
+ return shown.length ? Math.min(...shown) : Math.max(...tries);
+}
+
+/** An instant's clock reading moved to another zone: 9:00 in one is 9:00 in the other. */
+export function sameClockIn(from: string, to: string, s: number): number {
+ return instantIn(to, wallIn(from, s));
+}
+
+/** Every zone this computer knows, by its IANA name. */
+export function allZones(): string[] {
+ const known = (Intl as { supportedValuesOf?: (k: string) => string[] }).supportedValuesOf?.("timeZone") ?? [];
+ return known.length ? known : ["UTC"];
+}
+
+/** A zone as Calendar names one: its city, and how far from GMT it is at `s`. */
+export function zoneName(zone: string, s: number): { city: string; offset: string } {
+ const city = (zone.split("/").pop() ?? zone).replace(/_/g, " ");
+ const w = wallIn(zone, s);
+ const minutes = Math.round((Date.UTC(w.y, w.m - 1, w.d, w.h, w.min) / 1000 - Math.floor(s / 60) * 60) / 60);
+ const sign = minutes < 0 ? "−" : "+";
+ const a = Math.abs(minutes);
+ const offset = minutes === 0 ? "GMT" : `GMT${sign}${Math.floor(a / 60)}${a % 60 ? `:${String(a % 60).padStart(2, "0")}` : ""}`;
+ return { city, offset };
+}
diff --git a/src/styles/calendar.css b/src/styles/calendar.css
index 567d996..dc3810c 100644
--- a/src/styles/calendar.css
+++ b/src/styles/calendar.css
@@ -827,3 +827,32 @@
width: 100%; height: 26px; margin: 0; padding: 0 6px;
border-radius: 6px; font: inherit; font-size: var(--t-13);
}
+
+/* An event's time zone: its city, with the offset quieter beside it; a field that finds one. */
+.cx-zone {
+ display: flex; align-items: baseline; gap: 6px; min-height: 26px; padding: 3px 8px; border: 0;
+ border-radius: 8px; background: color-mix(in srgb, var(--text) 6%, transparent); box-shadow: none;
+ color: var(--text); font: inherit; font-size: var(--t-13); text-align: start; cursor: default;
+}
+.cx-zone:hover:not(:disabled) { background: color-mix(in srgb, var(--text) 10%, transparent); }
+.cx-zone:focus-visible { box-shadow: 0 0 0 3px var(--accent-ring); outline: none; }
+.cx-zone:disabled { background: none; padding-inline: 0; }
+.cx-zone-offset { color: var(--text-3); font-variant-numeric: tabular-nums; }
+.cx-zone-find { position: relative; display: block; min-width: 0; }
+.cx-popover .cx-zone-find input {
+ width: 100%; min-height: 26px; padding: 3px 8px; border-radius: 8px;
+ background: color-mix(in srgb, var(--text) 6%, transparent); box-shadow: 0 0 0 3px var(--accent-ring);
+ font-size: var(--t-13);
+}
+.cx-zones {
+ position: absolute; z-index: 5; inset-inline: 0; top: calc(100% + 4px); display: flex; flex-direction: column;
+ padding: 4px; border-radius: 10px; background: var(--sheet, var(--bg)); box-shadow: var(--glass-float), 0 0 0 0.5px var(--separator);
+}
+.cx-zone-option {
+ display: grid; grid-template-columns: minmax(0, 1fr) auto auto; align-items: baseline; gap: 8px;
+ padding: 4px 8px; border-radius: 6px; font-size: var(--t-13); cursor: default;
+}
+.cx-zone-option > span:first-child { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.cx-zone-region { color: var(--text-3); font-size: var(--t-11); }
+.cx-zone-option.is-lit { background: var(--accent); color: var(--on-accent, #fff); }
+.cx-zone-option.is-lit .cx-zone-region, .cx-zone-option.is-lit .cx-zone-offset { color: inherit; opacity: 0.8; }