Native iCloud apps for Windows and Linux, built in Rust. Notes, Reminders, Calendar, Contacts, Drive and Photos, offline and in sync with your iPhone.
Rust apple-notesapple-reminderscloudkitcrdtdesktop-appicloudicloud-calendaricloud-driveicloud-notesicloud-photosiphonelinuxlinux-desktoplocal-firstoffline-firstprivacyrusttauritauri-appwindows
Calendar rebuilt on macOS Calendar's layout
Yashwanth Kamireddie44d2cd64292
diff --git a/.uiverify/calendar-model.test.mjs b/.uiverify/calendar-model.test.mjsnew file mode 100644index 0000000..23b5a0f--- /dev/null+++ b/.uiverify/calendar-model.test.mjs@@ -0,0 +1,87 @@+// The arithmetic Calendar's views are drawn from, checked directly.+import { test } from "node:test";+import assert from "node:assert/strict";+import { placeDay, weekSpans, monthDays, daysOf, snap, clock } from "../src/screens/calendar/model.ts";++const at = (y, m, d, h = 0, min = 0) => Math.floor(new Date(y, m, d, h, min).getTime() / 1000);+const ev = (guid, startsAt, endsAt, allDay = false) =>+ ({ guid, calendarGuid: "c", title: guid, location: null, startsAt, endsAt, allDay, timezone: null, url: null, notes: null, etag: null });++test("a month is six weeks from the Sunday on or before the 1st", () => {+ const days = monthDays(new Date(2026, 8, 15));+ assert.equal(days.length, 42);+ assert.equal(days[0].getDay(), 0);+ assert.deepEqual([days[0].getMonth(), days[0].getDate()], [7, 30]);+});++test("an all-day event ends the day before its end midnight", () => {+ const [first, last] = daysOf(ev("a", at(2026, 9, 2), at(2026, 9, 4), true));+ assert.equal(first.getDate(), 2);+ assert.equal(last.getDate(), 3);+});++test("a trip across a weekend is one bar per week, carrying on across the break", () => {+ const trip = ev("trip", at(2026, 9, 2), at(2026, 9, 6), true); // Fri 2 – Mon 5+ const first = weekSpans([trip], new Date(2026, 8, 27));+ const second = weekSpans([trip], new Date(2026, 9, 4));+ assert.deepEqual([first[0].from, first[0].to, first[0].continuesRight], [5, 6, true]);+ assert.deepEqual([second[0].from, second[0].to, second[0].continuesLeft], [0, 1, true]);+});++test("overlapping bars take separate lanes, and a free lane is reused", () => {+ const week = new Date(2026, 8, 27);+ const spans = weekSpans([+ ev("long", at(2026, 8, 27), at(2026, 9, 1), true),+ ev("mid", at(2026, 8, 28), at(2026, 8, 30), true),+ ev("late", at(2026, 9, 1), at(2026, 9, 3), true),+ ], week);+ const lane = Object.fromEntries(spans.map((s) => [s.event.guid, s.lane]));+ assert.equal(lane.long, 0);+ assert.equal(lane.mid, 1);+ assert.equal(lane.late, 0);+});++test("overlapping meetings sit side by side; a later one gets the width back", () => {+ const day = new Date(2026, 8, 29);+ const placed = placeDay([+ ev("a", at(2026, 8, 29, 9), at(2026, 8, 29, 10)),+ ev("b", at(2026, 8, 29, 9, 30), at(2026, 8, 29, 11)),+ ev("c", at(2026, 8, 29, 14), at(2026, 8, 29, 15)),+ ], day);+ const by = Object.fromEntries(placed.map((p) => [p.event.guid, p]));+ assert.deepEqual([by.a.column, by.a.columns], [0, 2]);+ assert.deepEqual([by.b.column, by.b.columns], [1, 2]);+ assert.deepEqual([by.c.column, by.c.columns], [0, 1]);+ assert.equal(by.a.top, 540);+});++test("a five-minute call is still a quarter hour tall", () => {+ const [p] = placeDay([ev("x", at(2026, 8, 29, 9), at(2026, 8, 29, 9, 5))], new Date(2026, 8, 29));+ assert.equal(p.length, 15);+});++test("an evening that runs past midnight is a block on each day it touches", () => {+ const late = ev("late", at(2026, 8, 29, 23), at(2026, 8, 30, 1));+ const [tue] = placeDay([late], new Date(2026, 8, 29));+ const [wed] = placeDay([late], new Date(2026, 8, 30));+ assert.deepEqual([tue.top, tue.length], [23 * 60, 60]);+ assert.deepEqual([wed.top, wed.length], [0, 60]);+ assert.equal(weekSpans([late], new Date(2026, 8, 27)).length, 0);+});++test("a timed event of a day or more is a bar", () => {+ const conference = ev("conf", at(2026, 8, 29, 9), at(2026, 9, 1, 17));+ assert.equal(placeDay([conference], new Date(2026, 8, 30)).length, 0);+ assert.equal(weekSpans([conference], new Date(2026, 8, 27))[0].to, 4);+});++test("dragging snaps to the quarter hour", () => {+ assert.equal(snap(7), 0);+ assert.equal(snap(8), 15);+ assert.equal(snap(52), 45);+});++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/);+});diff --git a/.uiverify/keyboard.mjs b/.uiverify/keyboard.mjsindex 2412d8e..a38623a 100644--- a/.uiverify/keyboard.mjs+++ b/.uiverify/keyboard.mjs@@ -199,7 +199,9 @@ const focused = (page) =>);check("month grid is ONE tab stop, not forty-two", stops === 1, `${stops} tabbable`);- const day = () => page.locator(".cal-day-panel h2").innerText();+ // The selected day is the grid's one tab stop, and its label names the day — what a+ // screen reader announces as the arrows move.+ const day = () => page.locator('.cal-grid button[tabindex="0"]').getAttribute("aria-label");const before = await day();await page.locator('.cal-grid button[tabindex="0"]').focus();await page.keyboard.press("ArrowDown");diff --git a/check.sh b/check.shindex e3c8475..288ca91 100755--- a/check.sh+++ b/check.sh@@ -19,6 +19,7 @@ step "rust format" cargo fmt --all -- --checkstep "rust lint" cargo clippy --workspace --all-targets -- -D warningsstep "rust tests" cargo test --workspace --quietstep "typescript" npx tsc --noEmit+step "calendar layout" node --test .uiverify/calendar-model.test.mjsstep "frontend build" npm run build# The browser checks need the built bundle served.diff --git a/src/main.tsx b/src/main.tsxindex 43061eb..e8a6da8 100644--- a/src/main.tsx+++ b/src/main.tsx@@ -4,6 +4,7 @@ import App from "./App";import "./styles/tokens.css";import "./styles/app.css";import "./styles/reminders.css";+import "./styles/calendar.css";ReactDOM.createRoot(document.getElementById("root")!).render(<React.StrictMode>diff --git a/src/screens/CalendarView.tsx b/src/screens/CalendarView.tsxdeleted file mode 100644index b456033..0000000--- a/src/screens/CalendarView.tsx+++ /dev/null@@ -1,962 +0,0 @@-import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from "react";-import {- api,- defaultCalendar,- messageOf,- type Calendar,- type CalendarEvent,- type Reminder,-} from "../lib/ipc";-import { useSync } from "../lib/sync";-import { Picker } from "../components/Picker";--const ZONE = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";--/** Local midnight for a date, as unix seconds. */-const startOfDay = (d: Date) =>- Math.floor(new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime() / 1000);--/**- * Local midnight the morning after, as unix seconds.- *- * Not midnight plus 86,400. On the two days a year a clock moves, a day is twenty-three hours- * or twenty-five, so adding a fixed day lands an hour either side of midnight and takes an- * extra evening's events into the view or leaves one out. Asking the calendar for the next- * date is right wherever the viewer is.- */-const startOfNextDay = (d: Date) =>- Math.floor(new Date(d.getFullYear(), d.getMonth(), d.getDate() + 1).getTime() / 1000);--const isoDate = (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())}`;-};--const sameDay = (a: Date, b: Date) =>- a.getFullYear() === b.getFullYear() &&- a.getMonth() === b.getMonth() &&- a.getDate() === b.getDate();--const weekdayNames = () => {- // Locale-correct short weekday names, starting Sunday as Apple's calendar does.- const base = new Date(2024, 8, 1); // a Sunday- return Array.from({ length: 7 }, (_, i) => {- const d = new Date(base);- d.setDate(base.getDate() + i);- return d.toLocaleDateString(undefined, { weekday: "short" });- });-};--const clockTime = (seconds: number) =>- new Date(seconds * 1000)- .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 rows of a day or week grid. Apple shows the full twenty-four. */-const HOURS = Array.from({ length: 24 }, (_, i) => i);--/** How tall one hour is in the day and week grids. */-const HOUR_HEIGHT = 44;--/**- * Where a timed event sits on the hour grid.- *- * The grid has a header row, an all-day row and then one row per hour, so an event is- * placed against the grid's own tracks rather than by measuring pixels — that way it stays- * put when the window resizes.- */-function placement(- event: CalendarEvent,- day: Date,- column: number-): React.CSSProperties {- const dayStart = startOfDay(day);- const dayEnd = startOfNextDay(day);- const from = Math.max(event.startsAt, dayStart);- const to = Math.min(event.endsAt, dayEnd);- const minutesIn = (from - dayStart) / 60;- // A zero-length event still has to be readable, so nothing is thinner than a quarter hour.- const minutesLong = Math.max((to - from) / 60, 15);- return {- gridColumn: column + 2,- // Rows: 1 is the column head, 2 is all-day, so hour zero starts at 3.- gridRow: "3 / -1",- marginTop: `${(minutesIn / 60) * HOUR_HEIGHT}px`,- height: `${(minutesLong / 60) * HOUR_HEIGHT}px`,- };-}--/** Apple's four scopes, in Apple's order. */-const VIEWS = [- { key: "day", label: "Day" },- { key: "week", label: "Week" },- { key: "month", label: "Month" },- { key: "year", label: "Year" },-] as const;--type View = (typeof VIEWS)[number]["key"];--const midnight = (d: Date) => new Date(d.getFullYear(), d.getMonth(), d.getDate());--/** The Sunday on or before `d`, which is where Apple starts a week. */-const startOfWeek = (d: Date) => {- const start = midnight(d);- start.setDate(start.getDate() - start.getDay());- return start;-};--/** Move a date by one unit of `view`. */-function step(from: Date, view: View, by: number): Date {- const d = new Date(from);- if (view === "day") d.setDate(d.getDate() + by);- else if (view === "week") d.setDate(d.getDate() + by * 7);- else if (view === "month") d.setMonth(d.getMonth() + by);- else d.setFullYear(d.getFullYear() + by);- return d;-}--/** 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);- const start = new Date(first);- start.setDate(first.getDate() - first.getDay());- return Array.from({ length: 42 }, (_, i) => {- const d = new Date(start);- d.setDate(start.getDate() + i);- return d;- });-}--export function CalendarView() {- const today = useMemo(() => new Date(), []);- const [anchor, setAnchor] = useState(() => new Date(today.getFullYear(), today.getMonth(), 1));- const [events, setEvents] = useState<CalendarEvent[]>([]);- const [dueReminders, setDueReminders] = useState<Reminder[]>([]);- const [calendars, setCalendars] = useState<Calendar[]>([]);- const [loaded, setLoaded] = useState(false);- const [error, setError] = useState<string | null>(null);- /** 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));- /** Day, week, month or year — the scope everything else follows. */- const [view, setView] = useState<View>("month");- /** 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]);-- /** The seven days of the week `anchor` falls in. */- const weekDays = useMemo(() => {- const start = startOfWeek(anchor);- return Array.from({ length: 7 }, (_, i) => {- const d = new Date(start);- d.setDate(start.getDate() + i);- return d;- });- }, [anchor]);-- // Each view asks Apple for exactly what it shows, so a day view does not fetch a month- // and a year view does not fetch it twelve times over.- const range = useMemo(() => {- if (view === "day") {- return { from: startOfDay(anchor), to: startOfNextDay(anchor) };- }- if (view === "week") {- return { from: startOfDay(weekDays[0]), to: startOfNextDay(weekDays[6]) };- }- if (view === "year") {- return {- from: startOfDay(new Date(anchor.getFullYear(), 0, 1)),- to: startOfNextDay(new Date(anchor.getFullYear(), 11, 31)),- };- }- return { from: startOfDay(days[0]), to: startOfNextDay(days[41]) };- }, [view, anchor, days, weekDays]);-- const read = useCallback(async () => {- // Apple's Calendar shows reminders beside events, which for most people is most of- // what fills a month.- const [found, cals, due] = await Promise.all([- api.calendarEvents(range.from, range.to),- api.calendarList(),- api.remindersDueBetween(range.from, range.to),- ]);- setEvents(Array.isArray(found) ? found : []);- setDueReminders(Array.isArray(due) ? due : []);- setCalendars(Array.isArray(cals) ? cals : []);- setLoaded(true);- }, [range]);-- // The grid always paints from the library: instant, and correct offline. `revision` ticks- // when the shared refresh finishes, which is the only thing that can change what is there.- useEffect(() => {- let cancelled = false;- read().catch((e) => {- if (!cancelled) {- setError(messageOf(e));- setLoaded(true);- }- });- return () => {- cancelled = true;- };- }, [read, revision]);-- // The shared refresh keeps a few months around today warm. Scroll past that and this- // fetches the month being looked at, once — clicking through a year must not mean a- // dozen round trips for months already fetched.- const fetched = useRef(new Set<string>());-- useEffect(() => {- const from = isoDate(range.from);- const to = isoDate(range.to - 1);- const key = `${from}:${to}`;- if (fetched.current.has(key)) return undefined;-- let cancelled = false;- // A short wait so holding down the arrow scrolls through months without fetching each.- const timer = window.setTimeout(() => {- fetched.current.add(key);- setFetchingMonth(true);- api- .calendarSync(from, to, ZONE)- .then(() => {- if (!cancelled) return read();- return undefined;- })- .catch((e) => {- // The library still holds the last good data, so the grid stays usable.- fetched.current.delete(key);- if (!cancelled) setError(messageOf(e));- })- .finally(() => {- if (!cancelled) setFetchingMonth(false);- });- }, 350);-- return () => {- cancelled = true;- window.clearTimeout(timer);- };- }, [range, read]);-- const colours = useMemo(- () => new Map(calendars.map((c) => [c.guid, c.colour])),- [calendars]- );-- /** What a day cell shows: an event, or a reminder due that day. */- type Entry =- | { kind: "event"; event: CalendarEvent }- | { kind: "reminder"; reminder: Reminder };-- /** Entries keyed by local day, so each cell is a lookup rather than a scan. */- const byDay = useMemo(() => {- const map = new Map<string, Entry[]>();- const push = (key: string, entry: Entry) => {- const bucket = map.get(key);- if (bucket) bucket.push(entry);- else map.set(key, [entry]);- };- for (const event of events) {- // An event spanning days belongs in every day it touches.- let cursor = new Date(event.startsAt * 1000);- cursor = new Date(cursor.getFullYear(), cursor.getMonth(), cursor.getDate());- const last = new Date(Math.max(event.endsAt - 1, event.startsAt) * 1000);- let guard = 0;- while (cursor <= last && guard++ < 60) {- push(cursor.toDateString(), { kind: "event", event });- cursor = new Date(cursor.getFullYear(), cursor.getMonth(), cursor.getDate() + 1);- }- }- for (const reminder of dueReminders) {- if (reminder.dueAt === null) continue;- push(new Date(reminder.dueAt * 1000).toDateString(), { kind: "reminder", reminder });- }- // Within a day, order by time so the cell reads like a schedule.- for (const bucket of map.values()) {- bucket.sort((a, b) => {- const at = a.kind === "event" ? a.event.startsAt : (a.reminder.dueAt ?? 0);- const bt = b.kind === "event" ? b.event.startsAt : (b.reminder.dueAt ?? 0);- return at - bt;- });- }- 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]- );-- // The arrows move by whatever is on screen: a day in Day, a week in Week, and so on.- const shift = (by: number) =>- setAnchor((a) => {- const to = step(a, view, by);- // In Day and Week the thing being looked at is also the thing selected.- if (view === "day" || view === "week") setSelected(to);- return to;- });-- /** What the title says, which is different in every view — as it is in Calendar. */- const title = useMemo(() => {- if (view === "day") {- return anchor.toLocaleDateString(undefined, {- weekday: "long",- day: "numeric",- month: "long",- year: "numeric",- });- }- if (view === "week") {- const [first, last] = [weekDays[0], weekDays[6]];- const sameMonth = first.getMonth() === last.getMonth();- const left = first.toLocaleDateString(undefined, { day: "numeric", month: "short" });- const right = last.toLocaleDateString(- undefined,- sameMonth ? { day: "numeric" } : { day: "numeric", month: "short" }- );- return `${left} – ${right} ${last.getFullYear()}`;- }- if (view === "year") return String(anchor.getFullYear());- return anchor.toLocaleDateString(undefined, { month: "long", year: "numeric" });- }, [view, anchor, weekDays]);-- const monthLabel = title;-- return (- <div className="cal">- <header className="cal-bar">- <div className="cal-nav">- <h1>{monthLabel}</h1>- <button className="chev" onClick={() => shift(-1)} aria-label="Previous month">‹</button>- <button- className="today-btn"- onClick={() => setAnchor(new Date(today.getFullYear(), today.getMonth(), 1))}- >- Today- </button>- <button className="chev" onClick={() => shift(1)} aria-label="Next month">›</button>- </div>- <div className="cal-actions">- {fetchingMonth && <span className="badge">Fetching…</span>}- {/* Calendar's own scope control, in Calendar's own order. */}- <div className="segmented" role="group" aria-label="Calendar view">- {VIEWS.map((v) => (- <button- key={v.key}- type="button"- className="segment"- aria-pressed={view === v.key}- onClick={() => {- setView(v.key);- setDraft(null);- // Switching scope keeps you where you were looking.- if (v.key === "day" || v.key === "week") setAnchor(new Date(selected));- }}- >- {v.label}- </button>- ))}- </div>- </div>- </header>-- {error && <p className="error" role="alert">{error}</p>}-- {view === "month" && (- <>- <div className="cal-weekdays" aria-hidden="true">- {weekdayNames().map((name) => (- <span key={name}>{name}</span>- ))}- </div>-- <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) => (- <div className="cal-week" role="row" key={week}>- {days.slice(week * 7, week * 7 + 7).map((day) => {- const outside = day.getMonth() !== anchor.getMonth();- const isToday = sameDay(day, today);- const items = byDay.get(day.toDateString()) ?? [];- const label = day.toLocaleDateString(undefined, {- weekday: "long",- day: "numeric",- month: "long",- });- const isSelected = sameDay(day, selected);- return (- <div- key={day.toISOString()}- className={`cal-day${outside ? " outside" : ""}${isSelected ? " is-selected" : ""}`}- role="gridcell"- 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>- <div className="chips">- {items.slice(0, 3).map((entry) =>- entry.kind === "event" ? (- <span- key={entry.event.guid + day.getDate()}- className={`chip${entry.event.allDay ? " all-day" : ""}`}- style={- entry.event.allDay- ? {- background:- colours.get(entry.event.calendarGuid) || "var(--gold)",- }- : undefined- }- title={entry.event.title}- >- {!entry.event.allDay && (- <span- className="chip-dot"- style={{- background:- colours.get(entry.event.calendarGuid) || "var(--gold)",- }}- />- )}- {!entry.event.allDay && (- <span className="chip-time">- {clockTime(entry.event.startsAt)}- </span>- )}- <span className="chip-title">{entry.event.title}</span>- </span>- ) : (- <span- key={entry.reminder.guid + day.getDate()}- className={`chip reminder${entry.reminder.completedAt ? " is-done" : ""}`}- title={entry.reminder.title}- >- {/* A ring rather than a dot, so a reminder reads as a task. */}- <span className="chip-ring" />- <span className="chip-time">- {clockTime(entry.reminder.dueAt ?? 0)}- </span>- <span className="chip-title">{entry.reminder.title}</span>- </span>- )- )}- {items.length > 3 && (- <span className="chip more">{items.length - 3} more</span>- )}- </div>- </button>- </div>- );- })}- </div>- ))}- </div>-- </>- )}-- {view === "year" && (- <div className="cal-year" role="grid" aria-label={`${anchor.getFullYear()} calendar`}>- {Array.from({ length: 12 }, (_, month) => {- const first = new Date(anchor.getFullYear(), month, 1);- const cells = gridDays(first);- return (- <button- key={month}- type="button"- className="cal-mini"- aria-label={first.toLocaleDateString(undefined, { month: "long", year: "numeric" })}- onClick={() => {- setAnchor(first);- setView("month");- }}- >- <span className="cal-mini-name">- {first.toLocaleDateString(undefined, { month: "long" })}- </span>- <span className="cal-mini-grid" aria-hidden="true">- {weekdayNames().map((name) => (- <span className="cal-mini-weekday" key={name}>- {name.slice(0, 1)}- </span>- ))}- {cells.map((day) => {- const outside = day.getMonth() !== month;- const busyDay = (byDay.get(day.toDateString()) ?? []).length > 0;- return (- <span- key={day.toISOString()}- className={`cal-mini-day${outside ? " outside" : ""}${- sameDay(day, today) ? " is-today" : ""- }${busyDay && !outside ? " has-items" : ""}`}- >- {day.getDate()}- </span>- );- })}- </span>- </button>- );- })}- </div>- )}-- {(view === "day" || view === "week") && (- <div className="cal-hours-wrap">- <div- className={`cal-hours${view === "day" ? " is-day" : ""}`}- role="grid"- aria-label={`${title} schedule`}- >- <span className="cal-hours-corner" aria-hidden="true" />- {(view === "day" ? [anchor] : weekDays).map((day) => (- <button- key={`head-${day.toISOString()}`}- type="button"- className={`cal-col-head${sameDay(day, today) ? " is-today" : ""}${- sameDay(day, selected) ? " is-selected" : ""- }`}- onClick={() => {- setSelected(day);- setDraft(null);- }}- >- <span className="cal-col-weekday">- {day.toLocaleDateString(undefined, { weekday: "short" })}- </span>- <span className="cal-col-daynum">{day.getDate()}</span>- </button>- ))}-- {/* All-day events sit above the hours, as they do in Calendar. */}- <span className="cal-allday-label" aria-hidden="true">- all-day- </span>- {(view === "day" ? [anchor] : weekDays).map((day) => (- <div className="cal-allday" key={`allday-${day.toISOString()}`}>- {(byDay.get(day.toDateString()) ?? [])- .filter((e) => e.kind === "event" && e.event.allDay)- .map((entry) =>- entry.kind === "event" ? (- <button- key={entry.event.guid}- type="button"- className="chip all-day"- style={{- background: colours.get(entry.event.calendarGuid) || "var(--gold)",- }}- onClick={() => {- setSelected(day);- setDraft(draftFrom(entry.event));- }}- >- <span className="chip-title">{entry.event.title}</span>- </button>- ) : null- )}- </div>- ))}-- {HOURS.map((hour) => (- <Fragment key={hour}>- <span className="cal-hour-label">- {hour === 0- ? ""- : new Date(2024, 0, 1, hour).toLocaleTimeString(undefined, {- hour: "numeric",- })}- </span>- {(view === "day" ? [anchor] : weekDays).map((day) => (- <button- key={`${day.toISOString()}-${hour}`}- type="button"- className="cal-hour-cell"- aria-label={`${day.toLocaleDateString(undefined, {- weekday: "long",- day: "numeric",- month: "long",- })} at ${hour}:00`}- onClick={() => {- setSelected(day);- const at = new Date(- day.getFullYear(),- day.getMonth(),- day.getDate(),- hour- );- // An account with no calendars has nowhere to put an event. The New- // event button already knows that; clicking an empty hour has to know- // it too, or it opens a form that cannot be saved.- const target = defaultCalendar(calendars)?.guid;- if (!target) return;- const startsAt = Math.floor(at.getTime() / 1000);- setDraft({- ...blankEvent(day, target),- startsAt,- endsAt: startsAt + 3600,- });- }}- />- ))}- </Fragment>- ))}-- {/* Timed events, laid over the hour grid where they actually fall. */}- {(view === "day" ? [anchor] : weekDays).map((day, column) =>- (byDay.get(day.toDateString()) ?? [])- .filter((e) => e.kind === "event" && !e.event.allDay)- .map((entry) =>- entry.kind === "event" ? (- <button- key={`timed-${entry.event.guid}-${column}`}- type="button"- className="cal-timed"- style={placement(entry.event, day, column)}- onClick={() => {- setSelected(day);- setDraft(draftFrom(entry.event));- }}- >- <span- className="cal-timed-bar"- style={{- background: colours.get(entry.event.calendarGuid) || "var(--gold)",- }}- />- <span className="cal-timed-text">- <span className="cal-timed-title">{entry.event.title}</span>- <span className="cal-timed-when">{clockTime(entry.event.startsAt)}</span>- </span>- </button>- ) : null- )- )}- </div>- </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 || defaultCalendar(calendars) === null}- onClick={() => {- const target = defaultCalendar(calendars)?.guid;- if (target) setDraft(blankEvent(selected, target));- }}- >- 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>- <div className="cal-field">- <span>Calendar</span>- <Picker- label="Calendar"- value={draft.calendarGuid}- onChange={(guid) => setDraft({ ...draft, calendarGuid: guid })}- /* A subscribed feed or a calendar shared for reading only cannot take an- event, so it is not offered as somewhere to put one. The one the event is- already in stays listed either way, or moving it would look impossible. */- options={calendars- .filter((c) => c.writable || c.guid === draft.calendarGuid)- .map((c) => ({ value: c.guid, label: c.title }))}- />- </div>- <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- open instantly and work offline.- </p>- )}- </div>- );-}diff --git a/src/screens/Library.tsx b/src/screens/Library.tsxindex 89c16fa..3bcd405 100644--- a/src/screens/Library.tsx+++ b/src/screens/Library.tsx@@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from "react";import { api, messageOf } from "../lib/ipc";import { SyncProvider } from "../lib/sync";import { SyncStatus } from "../components/SyncStatus";-import { CalendarView } from "./CalendarView";+import { CalendarView } from "./calendar/CalendarView";import { RemindersView } from "./RemindersView";import { NotesView } from "./NotesView";import { ContactsView } from "./ContactsView";diff --git a/src/screens/calendar/CalendarView.tsx b/src/screens/calendar/CalendarView.tsxnew file mode 100644index 0000000..e70ec85--- /dev/null+++ b/src/screens/calendar/CalendarView.tsx@@ -0,0 +1,1251 @@+import { Fragment, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";+import {+ api,+ defaultCalendar,+ messageOf,+ type Calendar,+ type CalendarEvent,+ type Reminder,+} from "../../lib/ipc";+import { useSync } from "../../lib/sync";+import { Picker } from "../../components/Picker";+import {+ addDays,+ clock,+ dateOf,+ dayKey,+ hourLabel,+ midnight,+ monthDays,+ placeDay,+ sameDay,+ seconds,+ snap,+ spansDays,+ startOfWeek,+ weekSpans,+} from "./model";++const ZONE = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";++/** Apple's four scopes, in Apple's order. */+const VIEWS = [+ { key: "day", label: "Day" },+ { key: "week", label: "Week" },+ { key: "month", label: "Month" },+ { key: "year", label: "Year" },+] as const;+type View = (typeof VIEWS)[number]["key"];++/** One hour of the Day and Week grids. */+const HOUR = 48;+/** A bar in the all-day row, and the gap under it. */+const LANE = 20;+/** What a month cell shows before it says "N more". */+const MONTH_ROWS = 4;++/** Calendars the viewer has switched off here, remembered on this computer. */+const HIDDEN_KEY = "quince.calendar.hidden";+const VIEW_KEY = "quince.calendar.view";++const readSet = (key: string) => {+ try {+ return new Set<string>(JSON.parse(window.localStorage.getItem(key) ?? "[]"));+ } catch {+ return new Set<string>();+ }+};++/** An event being written. A guid means it already exists at Apple. */+type Draft = {+ guid: string | null;+ calendarGuid: string;+ title: string;+ location: string;+ startsAt: number;+ endsAt: number;+ allDay: boolean;+ notes: string;+};++const draftOf = (e: CalendarEvent): Draft => ({+ guid: e.guid,+ calendarGuid: e.calendarGuid,+ title: e.title,+ location: e.location ?? "",+ startsAt: e.startsAt,+ endsAt: e.endsAt,+ allDay: e.allDay,+ notes: e.notes ?? "",+});++/** `YYYY-MM-DDTHH:mm` and `YYYY-MM-DD` for the date inputs, in local time. */+const pad = (n: number) => String(n).padStart(2, "0");+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) => d.toLocaleDateString(undefined, { weekday: "short" });++/** The colour a calendar is drawn in, or Apple's blue when it has none. */+const tint = (c: Calendar | undefined) =>+ c?.colour && /^#[0-9a-f]{6}$/i.test(c.colour) ? c.colour : "var(--sys-blue)";++type Anchor = { x: number; y: number };++export function CalendarView() {+ const today = useMemo(() => new Date(), []);+ const [now, setNow] = useState(() => new Date());+ const [view, setViewState] = useState<View>(() => {+ try {+ const saved = window.localStorage.getItem(VIEW_KEY) as View | null;+ return saved && VIEWS.some((v) => v.key === saved) ? saved : "month";+ } catch {+ return "month";+ }+ });+ const setView = (v: View) => {+ setViewState(v);+ try {+ window.localStorage.setItem(VIEW_KEY, v);+ } catch {+ // Remembering the view is a convenience.+ }+ };+ /** The day everything is anchored on: the one selected, and what the views are built around. */+ const [selected, setSelected] = useState<Date>(() => midnight(today));+ const [events, setEvents] = useState<CalendarEvent[]>([]);+ const [due, setDue] = useState<Reminder[]>([]);+ const [calendars, setCalendars] = useState<Calendar[]>([]);+ const [hidden, setHidden] = useState<Set<string>>(() => readSet(HIDDEN_KEY));+ const [loaded, setLoaded] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [busy, setBusy] = useState(false);+ const [draft, setDraft] = useState<Draft | null>(null);+ 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);+ const { revision } = useSync();++ // The current-time line moves once a minute, on the minute — not on a busy timer.+ useEffect(() => {+ let timer = 0;+ const tick = () => {+ setNow(new Date());+ timer = window.setTimeout(tick, 60_000 - (Date.now() % 60_000));+ };+ timer = window.setTimeout(tick, 60_000 - (Date.now() % 60_000));+ return () => window.clearTimeout(timer);+ }, []);++ const week = useMemo(() => {+ const start = startOfWeek(selected);+ return Array.from({ length: 7 }, (_, i) => addDays(start, i));+ }, [selected]);+ const month = useMemo(() => monthDays(selected), [selected]);++ // Each view asks for exactly what it shows.+ const range = useMemo(() => {+ if (view === "day") return { from: seconds(selected), to: seconds(addDays(selected, 1)) };+ if (view === "week") return { from: seconds(week[0]), to: seconds(addDays(week[6], 1)) };+ if (view === "year")+ return {+ from: seconds(new Date(selected.getFullYear(), 0, 1)),+ to: seconds(new Date(selected.getFullYear() + 1, 0, 1)),+ };+ return { from: seconds(month[0]), to: seconds(addDays(month[41], 1)) };+ }, [view, selected, week, month]);++ const read = useCallback(async () => {+ const [found, cals, reminders] = await Promise.all([+ api.calendarEvents(range.from, range.to),+ api.calendarList(),+ api.remindersDueBetween(range.from, range.to),+ ]);+ setEvents(Array.isArray(found) ? found : []);+ setCalendars(Array.isArray(cals) ? cals : []);+ setDue(Array.isArray(reminders) ? reminders : []);+ setLoaded(true);+ }, [range]);++ useEffect(() => {+ let cancelled = false;+ read().catch((e) => {+ if (!cancelled) {+ setError(messageOf(e));+ setLoaded(true);+ }+ });+ return () => {+ cancelled = true;+ };+ }, [read, revision]);++ // Beyond the months the shared refresh keeps warm, fetch what is being looked at — once,+ // and not for every month flicked past on the way.+ const fetched = useRef(new Set<string>());+ useEffect(() => {+ const from = toLocalInput(range.from, true);+ const to = toLocalInput(range.to - 1, true);+ const key = `${from}:${to}`;+ if (fetched.current.has(key)) return undefined;+ let cancelled = false;+ const timer = window.setTimeout(() => {+ fetched.current.add(key);+ api+ .calendarSync(from, to, ZONE)+ .then(() => (cancelled ? undefined : read()))+ .catch((e) => {+ fetched.current.delete(key);+ if (!cancelled) setError(messageOf(e));+ });+ }, 350);+ return () => {+ cancelled = true;+ window.clearTimeout(timer);+ };+ }, [range, read]);++ const byGuid = useMemo(() => new Map(calendars.map((c) => [c.guid, c])), [calendars]);+ const shown = useMemo(+ () => events.filter((e) => !hidden.has(e.calendarGuid)),+ [events, hidden]+ );+ const writable = calendars.filter((c) => c.writable);+ const target = defaultCalendar(calendars);++ const toggleCalendar = (guid: string) =>+ setHidden((was) => {+ const next = new Set(was);+ if (next.has(guid)) next.delete(guid);+ else next.add(guid);+ try {+ window.localStorage.setItem(HIDDEN_KEY, JSON.stringify([...next]));+ } catch {+ // Still hidden for now; forgotten on restart.+ }+ return next;+ });++ /** 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 save = useCallback(+ async (d: Draft) =>+ write(async () => {+ await api.eventSave({+ guid: d.guid,+ 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)),+ allDay: d.allDay,+ timezone: ZONE,+ notes: d.notes.trim() || null,+ url: null,+ });+ }),+ [write]+ );++ /**+ * iCloud keeps no bin for calendar events: deleting one is final at Apple. So the deletion+ * can be taken back here, the way Undo works in Calendar — the event is written again.+ */+ const remove = useCallback(+ async (guid: string) => {+ const gone = events.find((e) => e.guid === guid) ?? null;+ if (await write(() => api.eventDelete(guid))) {+ setDraft(null);+ setUndo(gone);+ }+ },+ [events, write]+ );+ const takeBack = useCallback(async () => {+ const gone = undo;+ setUndo(null);+ if (gone) await save({ ...draftOf(gone), guid: null });+ }, [undo, save]);+ useEffect(() => {+ if (!undo) return undefined;+ const timer = window.setTimeout(() => setUndo(null), 8000);+ return () => window.clearTimeout(timer);+ }, [undo]);++ const openDraft = (d: Draft, at: Anchor) => {+ setDraft(d);+ setAnchor(at);+ };+ const newAt = (startsAt: number, endsAt: number, allDay: boolean, at: Anchor) => {+ if (!target) return;+ openDraft(+ { guid: null, calendarGuid: target.guid, title: "", location: "", startsAt, endsAt, allDay, notes: "" },+ at+ );+ };+ const pointAt = (el: Element | null): Anchor => {+ const r = el?.getBoundingClientRect();+ return r ? { x: r.right, y: r.top } : { x: window.innerWidth / 2, y: 120 };+ };++ /** "New event": the next whole hour on the selected day, for an hour — Apple's default. */+ const newEvent = (e: React.MouseEvent) => {+ const at = new Date(selected);+ at.setHours(now.getHours() + 1, 0, 0, 0);+ newAt(seconds(at), seconds(at) + 3600, false, pointAt(e.currentTarget));+ };++ const shift = (by: number) =>+ setSelected((d) => {+ if (view === "day") return addDays(d, by);+ if (view === "week") return addDays(d, by * 7);+ if (view === "month") return new Date(d.getFullYear(), d.getMonth() + by, 1);+ return new Date(d.getFullYear() + by, d.getMonth(), 1);+ });++ // Keyboard, as in Calendar: ⌘/Ctrl-arrows page, T goes to today, N makes an event.+ useEffect(() => {+ const onKey = (e: KeyboardEvent) => {+ const typing = (e.target as HTMLElement | null)?.closest("input, textarea, select, [contenteditable]");+ if (typing || draft) return;+ if ((e.metaKey || e.ctrlKey) && e.key === "ArrowLeft") shift(-1);+ else if ((e.metaKey || e.ctrlKey) && e.key === "ArrowRight") shift(1);+ else if (e.key === "t" && !e.metaKey && !e.ctrlKey) setSelected(midnight(new Date()));+ else return;+ e.preventDefault();+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ });++ const title = useMemo(() => {+ if (view === "year") return { strong: String(selected.getFullYear()), rest: "" };+ if (view === "day")+ return {+ strong: selected.toLocaleDateString(undefined, { day: "numeric", month: "long" }),+ rest: `${selected.getFullYear()}`,+ };+ const base = view === "week" ? week[6] : selected;+ return {+ strong: base.toLocaleDateString(undefined, { month: "long" }),+ rest: String(base.getFullYear()),+ };+ }, [view, selected, week]);++ /** A day's reminders and timed events for a month cell, in time order. */+ const dayItems = useCallback(+ (day: Date) => {+ const start = seconds(day);+ const end = seconds(addDays(day, 1));+ const timed = shown+ .filter((e) => !spansDays(e) && e.startsAt < end && e.endsAt > start)+ .map((event) => ({ kind: "event" as const, at: Math.max(event.startsAt, start), event }));+ const reminders = due+ .filter((r) => r.dueAt !== null && r.dueAt >= start && r.dueAt < end)+ .map((reminder) => ({ kind: "reminder" as const, at: reminder.dueAt ?? 0, reminder }));+ return [...timed, ...reminders].sort((a, b) => a.at - b.at);+ },+ [shown, due]+ );++ return (+ <div className="cx">+ <aside className="cx-side" aria-label="Calendars">+ <div className="cx-cals">+ {[+ { heading: "iCloud", list: calendars.filter((c) => c.writable) },+ { heading: "Other", list: calendars.filter((c) => !c.writable) },+ ]+ .filter((g) => g.list.length > 0)+ .map((group) => (+ <Fragment key={group.heading}>+ <p className="cx-side-heading">{group.heading}</p>+ {group.list.map((c) => (+ <label className="cx-cal" key={c.guid}>+ <input+ type="checkbox"+ checked={!hidden.has(c.guid)}+ onChange={() => toggleCalendar(c.guid)}+ style={{ "--cal": tint(c) } as React.CSSProperties}+ />+ <span className="cx-cal-name">{c.title}</span>+ </label>+ ))}+ </Fragment>+ ))}+ {loaded && calendars.length === 0 && (+ <p className="cal-empty">There are no calendars on this account yet.</p>+ )}+ </div>+ <MiniMonth+ selected={selected}+ today={now}+ busy={(d) => dayItems(d).length > 0}+ onPick={(d) => setSelected(d)}+ />+ </aside>++ <section className="cx-main">+ <header className="cx-bar">+ <h1 className="cx-title">+ <strong>{title.strong}</strong> {title.rest}+ </h1>+ <div className="segmented" role="group" aria-label="View">+ {VIEWS.map((v) => (+ <button+ key={v.key}+ className="segment"+ aria-pressed={view === v.key}+ onClick={() => setView(v.key)}+ >+ {v.label}+ </button>+ ))}+ </div>+ <div className="cx-tools">+ {writable.length > 0 && (+ <button className="cx-icon" aria-label="New event" title="New Event" onClick={newEvent}>+ ++ </button>+ )}+ <span className="cx-step">+ <button className="cx-icon" aria-label="Previous" onClick={() => shift(-1)}>+ ‹+ </button>+ <button className="cx-today" onClick={() => setSelected(midnight(new Date()))}>+ Today+ </button>+ <button className="cx-icon" aria-label="Next" onClick={() => shift(1)}>+ ›+ </button>+ </span>+ </div>+ </header>++ {error && (+ <p className="cx-error" role="alert">+ {error}+ </p>+ )}++ {view === "month" && (+ <MonthView+ days={month}+ selected={selected}+ today={now}+ events={shown}+ calendars={byGuid}+ items={dayItems}+ onSelect={setSelected}+ onOpen={(e, at) => openDraft(draftOf(e), at)}+ onCreate={(day, at) => {+ const start = new Date(day);+ start.setHours(9, 0, 0, 0);+ newAt(seconds(start), seconds(start) + 3600, false, at);+ }}+ onMore={(day) => {+ setSelected(day);+ setView("day");+ }}+ />+ )}++ {(view === "week" || view === "day") && (+ <TimeGrid+ days={view === "week" ? week : [selected]}+ today={now}+ events={shown}+ reminders={due}+ calendars={byGuid}+ canWrite={(guid) => byGuid.get(guid)?.writable ?? false}+ onOpen={(e, at) => openDraft(draftOf(e), at)}+ onCreate={(startsAt, endsAt, allDay, at) => newAt(startsAt, endsAt, allDay, at)}+ onMove={(e, startsAt, endsAt) => void save({ ...draftOf(e), startsAt, endsAt })}+ onPickDay={(d) => {+ setSelected(d);+ setView("day");+ }}+ />+ )}++ {view === "year" && (+ <YearView+ year={selected.getFullYear()}+ today={now}+ busy={(d) => dayItems(d).length > 0}+ onPick={(d) => {+ setSelected(d);+ setView("day");+ }}+ />+ )}+ </section>++ {draft && anchor && (+ <EventPopover+ draft={draft}+ at={anchor}+ calendars={calendars}+ busy={busy}+ onChange={setDraft}+ onClose={() => setDraft(null)}+ onSave={async () => {+ if (await save(draft)) setDraft(null);+ }}+ onDelete={draft.guid ? () => void remove(draft.guid as string) : undefined}+ />+ )}++ {undo && (+ <div className="cx-toast" role="status">+ Deleted “{undo.title}”+ <button className="cx-toast-undo" onClick={() => void takeBack()}>+ Undo+ </button>+ </div>+ )}+ </div>+ );+}++/* ---- the mini month in the sidebar ------------------------------------------------ */++function MiniMonth({+ selected,+ today,+ busy,+ onPick,+}: {+ selected: Date;+ today: Date;+ busy: (d: Date) => boolean;+ onPick: (d: Date) => void;+}) {+ const [shown, setShown] = useState(() => new Date(selected.getFullYear(), selected.getMonth(), 1));+ useEffect(() => {+ setShown(new Date(selected.getFullYear(), selected.getMonth(), 1));+ }, [selected]);+ const days = monthDays(shown);+ return (+ <div className="cx-minimonth">+ <div className="cx-minimonth-head">+ <span>{shown.toLocaleDateString(undefined, { month: "long", year: "numeric" })}</span>+ <span>+ <button+ className="cx-icon small"+ aria-label="Previous month"+ onClick={() => setShown((m) => new Date(m.getFullYear(), m.getMonth() - 1, 1))}+ >+ ‹+ </button>+ <button+ className="cx-icon small"+ aria-label="Next month"+ onClick={() => setShown((m) => new Date(m.getFullYear(), m.getMonth() + 1, 1))}+ >+ ›+ </button>+ </span>+ </div>+ <div className="cx-minimonth-grid">+ {days.slice(0, 7).map((d) => (+ <span className="cx-minimonth-wd" key={`wd${d.getDay()}`} aria-hidden="true">+ {weekdayShort(d).slice(0, 1)}+ </span>+ ))}+ {days.map((d) => (+ <button+ key={dayKey(d)}+ className={`cx-minimonth-day${d.getMonth() !== shown.getMonth() ? " is-out" : ""}${+ sameDay(d, today) ? " is-today" : ""+ }${sameDay(d, selected) ? " is-selected" : ""}${busy(d) ? " is-busy" : ""}`}+ aria-label={d.toLocaleDateString(undefined, { dateStyle: "full" })}+ onClick={() => onPick(d)}+ >+ {d.getDate()}+ </button>+ ))}+ </div>+ </div>+ );+}++/* ---- month ------------------------------------------------------------------------ */++type Item =+ | { kind: "event"; at: number; event: CalendarEvent }+ | { kind: "reminder"; at: number; reminder: Reminder };++function MonthView({+ days,+ selected,+ today,+ events,+ calendars,+ items,+ onSelect,+ onOpen,+ onCreate,+ onMore,+}: {+ days: Date[];+ selected: Date;+ today: Date;+ events: CalendarEvent[];+ calendars: Map<string, Calendar>;+ items: (d: Date) => Item[];+ onSelect: (d: Date) => void;+ onOpen: (e: CalendarEvent, at: Anchor) => void;+ onCreate: (d: Date, at: Anchor) => void;+ onMore: (d: Date) => void;+}) {+ const cell = useRef<HTMLButtonElement | null>(null);+ const focused = useRef(false);+ const inMonth = selected.getMonth();+ useEffect(() => {+ if (focused.current) cell.current?.focus();+ }, [selected]);++ const onKey = (e: React.KeyboardEvent, day: Date) => {+ const by = { ArrowRight: 1, ArrowLeft: -1, ArrowDown: 7, ArrowUp: -7 }[e.key];+ if (by !== undefined) {+ e.preventDefault();+ focused.current = true;+ onSelect(addDays(day, by));+ } else if (e.key === "Home") {+ e.preventDefault();+ onSelect(addDays(day, -day.getDay()));+ } else if (e.key === "End") {+ e.preventDefault();+ onSelect(addDays(day, 6 - day.getDay()));+ }+ };++ // How many lines a cell has room for, measured rather than assumed: a small window has+ // room for two, a large one for eight, and a fixed guess spilt items out of the cell.+ const grid = useRef<HTMLDivElement | null>(null);+ const [rows, setRows] = useState(MONTH_ROWS);+ useLayoutEffect(() => {+ const el = grid.current;+ if (!el) return undefined;+ const measure = () => {+ const week = el.firstElementChild as HTMLElement | null;+ const height = week?.getBoundingClientRect().height ?? 0;+ setRows(Math.max(1, Math.floor((height - 28) / 18)));+ };+ measure();+ const observer = new ResizeObserver(measure);+ observer.observe(el);+ return () => observer.disconnect();+ }, []);++ const weeks = Array.from({ length: 6 }, (_, w) => days.slice(w * 7, w * 7 + 7));+ return (+ <div className="cx-month">+ <div className="cx-weekdays" aria-hidden="true">+ {days.slice(0, 7).map((d) => (+ <span key={d.getDay()}>{weekdayShort(d)}</span>+ ))}+ </div>+ <div className="cal-grid" role="grid" aria-label="Month" ref={grid}>+ {weeks.map((row) => {+ const spans = weekSpans(events, row[0]);+ const lanes = Math.max(0, ...spans.map((s) => s.lane + 1));+ return (+ <div className="cx-week" role="row" key={dayKey(row[0])}>+ {row.map((day, i) => {+ const list = items(day);+ const lanesHere = spans.filter((s) => s.from <= i && s.to >= i).length;+ const room = Math.max(0, rows - Math.max(lanes, lanesHere));+ // What fits, and when it does not, one line fewer so "N more" has a line too.+ const visible = list.length > room ? list.slice(0, Math.max(0, room - 1)) : list;+ const more = list.length - visible.length;+ const isSelected = sameDay(day, selected);+ return (+ <div+ className={`cx-day${day.getMonth() !== inMonth ? " is-out" : ""}${+ day.getDay() === 0 || day.getDay() === 6 ? " is-weekend" : ""+ }${isSelected ? " is-selected" : ""}`}+ role="gridcell"+ aria-selected={isSelected}+ key={dayKey(day)}+ >+ <button+ ref={isSelected ? cell : undefined}+ className="cx-day-hit"+ tabIndex={isSelected ? 0 : -1}+ aria-label={`${day.toLocaleDateString(undefined, { dateStyle: "full" })}${+ list.length ? `, ${list.length} item${list.length === 1 ? "" : "s"}` : ""+ }`}+ onClick={() => onSelect(day)}+ onDoubleClick={(e) => onCreate(day, { x: e.clientX, y: e.clientY })}+ onKeyDown={(e) => onKey(e, day)}+ onBlur={() => (focused.current = false)}+ />+ <span className={`cx-daynum${sameDay(day, today) ? " is-today" : ""}`}>+ {day.getDate() === 1 && day.getMonth() !== inMonth+ ? day.toLocaleDateString(undefined, { month: "short", day: "numeric" })+ : day.getDate()}+ </span>+ <ul className="cx-items" style={{ marginTop: `${lanes * LANE}px` }}>+ {visible.map((item) =>+ item.kind === "event" ? (+ <li key={item.event.guid}>+ <button+ className="cx-item"+ style={{ "--cal": tint(calendars.get(item.event.calendarGuid)) } as React.CSSProperties}+ onClick={(e) => onOpen(item.event, { x: e.clientX, y: e.clientY })}+ >+ <span className="cx-dot" aria-hidden="true" />+ <span className="cx-item-title">{item.event.title}</span>+ <span className="cx-item-time">{clock(item.event.startsAt)}</span>+ </button>+ </li>+ ) : (+ <li key={item.reminder.guid}>+ <span className={`cx-item is-reminder${item.reminder.completedAt ? " is-done" : ""}`}>+ <span className="cx-ring" aria-hidden="true" />+ <span className="cx-item-title">{item.reminder.title}</span>+ <span className="cx-item-time">{clock(item.at)}</span>+ </span>+ </li>+ )+ )}+ {more > 0 && (+ <li>+ <button className="cx-more" onClick={() => onMore(day)}>+ {more} more+ </button>+ </li>+ )}+ </ul>+ </div>+ );+ })}+ {spans.map((s) => (+ <button+ key={`${s.event.guid}-${dayKey(row[0])}`}+ className={`cx-bar-event${s.continuesLeft ? " from-before" : ""}${+ s.continuesRight ? " to-after" : ""+ }`}+ style={+ {+ "--cal": tint(calendars.get(s.event.calendarGuid)),+ left: `calc(${(s.from / 7) * 100}% + 3px)`,+ width: `calc(${((s.to - s.from + 1) / 7) * 100}% - 6px)`,+ top: `${26 + s.lane * LANE}px`,+ } as React.CSSProperties+ }+ onClick={(e) => onOpen(s.event, { x: e.clientX, y: e.clientY })}+ >+ {s.event.title}+ </button>+ ))}+ </div>+ );+ })}+ </div>+ </div>+ );+}++/* ---- week and day ------------------------------------------------------------------- */++type Drag =+ | { kind: "create"; day: Date; column: number; from: number; to: number }+ | { kind: "move"; event: CalendarEvent; startX: number; startY: number; dx: number; dMinutes: number };++function TimeGrid({+ days,+ today,+ events,+ reminders,+ calendars,+ canWrite,+ onOpen,+ onCreate,+ onMove,+ onPickDay,+}: {+ days: Date[];+ today: Date;+ events: CalendarEvent[];+ reminders: Reminder[];+ calendars: Map<string, Calendar>;+ canWrite: (calendarGuid: string) => boolean;+ onOpen: (e: CalendarEvent, at: Anchor) => void;+ onCreate: (startsAt: number, endsAt: number, allDay: boolean, at: Anchor) => void;+ onMove: (e: CalendarEvent, startsAt: number, endsAt: number) => void;+ onPickDay: (d: Date) => void;+}) {+ const scroller = useRef<HTMLDivElement | null>(null);+ const columnsEl = useRef<HTMLDivElement | null>(null);+ const [drag, setDrag] = useState<Drag | null>(null);+ const spans = weekSpans(events, days[0]).filter((s) => s.from < days.length);+ const lanes = Math.max(1, ...spans.map((s) => s.lane + 1));++ // Opened, it shows the working day rather than midnight — as Calendar does.+ useLayoutEffect(() => {+ const el = scroller.current;+ if (!el) return;+ const showsToday = days.some((d) => sameDay(d, new Date()));+ const hour = showsToday ? Math.max(0, new Date().getHours() - 2) : 7;+ el.scrollTop = hour * HOUR;+ // Only when the days change, never under someone's scrolling.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [days.map((d) => dayKey(d)).join()]);++ /** Minutes since midnight under the pointer, in the column it is over. */+ const where = (clientX: number, clientY: number) => {+ const el = columnsEl.current;+ if (!el) return null;+ const r = el.getBoundingClientRect();+ const column = Math.min(days.length - 1, Math.max(0, Math.floor(((clientX - r.left) / r.width) * days.length)));+ const minutes = Math.min(24 * 60, Math.max(0, ((clientY - r.top) / HOUR) * 60));+ return { column, minutes };+ };++ const onColumnDown = (e: React.PointerEvent) => {+ if (e.button !== 0 || (e.target as HTMLElement).closest(".cx-block")) return;+ const at = where(e.clientX, e.clientY);+ if (!at) return;+ const from = snap(at.minutes) - (snap(at.minutes) === 24 * 60 ? 15 : 0);+ (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);+ setDrag({ kind: "create", day: days[at.column], column: at.column, from, to: from + 15 });+ };++ const onPointerMove = (e: React.PointerEvent) => {+ if (!drag) return;+ const at = where(e.clientX, e.clientY);+ if (!at) return;+ if (drag.kind === "create") {+ setDrag({ ...drag, to: Math.max(drag.from + 15, snap(at.minutes)) });+ } else {+ const el = columnsEl.current;+ const width = el ? el.getBoundingClientRect().width / days.length : 1;+ setDrag({+ ...drag,+ dx: Math.round((e.clientX - drag.startX) / width),+ dMinutes: snap(((e.clientY - drag.startY) / HOUR) * 60),+ });+ }+ };++ const onPointerUp = (e: React.PointerEvent) => {+ if (!drag) return;+ const done = drag;+ setDrag(null);+ if (done.kind === "create") {+ const base = seconds(done.day);+ // A click without a drag is an hour, like double-clicking in Calendar.+ const to = done.to - done.from <= 15 ? done.from + 60 : done.to;+ onCreate(base + done.from * 60, base + to * 60, false, { x: e.clientX, y: e.clientY });+ } else if (done.dx !== 0 || done.dMinutes !== 0) {+ const shift = done.dMinutes * 60;+ const moved = (s: number) => {+ const d = dateOf(s + shift);+ return seconds(new Date(d.getFullYear(), d.getMonth(), d.getDate() + done.dx, d.getHours(), d.getMinutes()));+ };+ onMove(done.event, moved(done.event.startsAt), moved(done.event.endsAt));+ } else {+ onOpen(done.event, { x: e.clientX, y: e.clientY });+ }+ };++ const nowMinutes = today.getHours() * 60 + today.getMinutes();+ const todayColumn = days.findIndex((d) => sameDay(d, today));++ return (+ <div className={`cal-hours${days.length === 1 ? " is-day" : ""}`}>+ <div className="cx-grid-head" style={{ "--cols": days.length } as React.CSSProperties}>+ <span className="cx-gutter" aria-hidden="true" />+ {days.map((d) => (+ <button+ className={`cal-col-head${sameDay(d, today) ? " is-today" : ""}`}+ key={dayKey(d)}+ onClick={() => onPickDay(d)}+ aria-label={d.toLocaleDateString(undefined, { dateStyle: "full" })}+ >+ <span className="cx-col-weekday">{weekdayShort(d)}</span>+ <span className="cx-col-num">{d.getDate()}</span>+ </button>+ ))}+ </div>++ <div className="cx-allday" style={{ "--cols": days.length, height: `${lanes * LANE + 8}px` } as React.CSSProperties}>+ <span className="cx-gutter cx-allday-label">all-day</span>+ <div className="cx-allday-lanes">+ {spans.map((s) => (+ <button+ key={s.event.guid}+ className={`cx-bar-event${s.continuesLeft ? " from-before" : ""}${s.continuesRight ? " to-after" : ""}`}+ style={+ {+ "--cal": tint(calendars.get(s.event.calendarGuid)),+ left: `calc(${(s.from / days.length) * 100}% + 2px)`,+ width: `calc(${((Math.min(s.to, days.length - 1) - s.from + 1) / days.length) * 100}% - 4px)`,+ top: `${4 + s.lane * LANE}px`,+ } as React.CSSProperties+ }+ onClick={(e) => onOpen(s.event, { x: e.clientX, y: e.clientY })}+ >+ {s.event.title}+ </button>+ ))}+ </div>+ </div>++ <div className="cx-scroll" ref={scroller}>+ <div className="cx-hours-body" style={{ height: `${24 * HOUR}px` }}>+ <div className="cx-gutter cx-hour-labels" aria-hidden="true">+ {Array.from({ length: 24 }, (_, h) =>+ h === 0 ? null : (+ <span key={h} style={{ top: `${h * HOUR}px` }}>+ {hourLabel(h)}+ </span>+ )+ )}+ {todayColumn >= 0 && (+ <span className="cx-now-label" style={{ top: `${(nowMinutes / 60) * HOUR}px` }}>+ {clock(seconds(today))}+ </span>+ )}+ </div>+ <div+ className="cx-columns"+ ref={columnsEl}+ style={{ "--cols": days.length } as React.CSSProperties}+ onPointerDown={onColumnDown}+ onPointerMove={onPointerMove}+ onPointerUp={onPointerUp}+ onPointerCancel={() => setDrag(null)}+ >+ {days.map((d, column) => (+ <div className={`cx-column${d.getDay() === 0 || d.getDay() === 6 ? " is-weekend" : ""}`} key={dayKey(d)}>+ {placeDay(events, d).map((p) => {+ const moving = drag?.kind === "move" && drag.event.guid === p.event.guid ? drag : null;+ const c = calendars.get(p.event.calendarGuid);+ return (+ <button+ key={p.event.guid}+ className={`cx-block${moving ? " is-moving" : ""}`}+ style={+ {+ "--cal": tint(c),+ top: `${((p.top + (moving?.dMinutes ?? 0)) / 60) * HOUR}px`,+ height: `${Math.max((p.length / 60) * HOUR - 2, 18)}px`,+ left: `calc(${(p.column / p.columns) * 100}% + ${(moving?.dx ?? 0) * 100}%)`,+ width: `calc(${100 / p.columns}% - 3px)`,+ } as React.CSSProperties+ }+ onPointerDown={(e) => {+ if (e.button !== 0) return;+ e.stopPropagation();+ (e.currentTarget.closest(".cx-columns") as HTMLElement | null)?.setPointerCapture(e.pointerId);+ if (canWrite(p.event.calendarGuid)) {+ setDrag({ kind: "move", event: p.event, startX: e.clientX, startY: e.clientY, dx: 0, dMinutes: 0 });+ } else {+ onOpen(p.event, { x: e.clientX, y: e.clientY });+ }+ }}+ onKeyDown={(e) => {+ if (e.key === "Enter" || e.key === " ") {+ e.preventDefault();+ onOpen(p.event, pointOf(e.currentTarget));+ }+ }}+ >+ <span className="cx-block-title">{p.event.title}</span>+ <span className="cx-block-time">{clock(p.event.startsAt)}</span>+ {p.event.location && <span className="cx-block-where">{p.event.location}</span>}+ </button>+ );+ })}+ {reminders+ .filter((r) => r.dueAt !== null && sameDay(dateOf(r.dueAt), d))+ .map((r) => (+ <span+ key={r.guid}+ className={`cx-reminder${r.completedAt ? " is-done" : ""}`}+ style={{ top: `${(((dateOf(r.dueAt ?? 0).getHours() * 60 + dateOf(r.dueAt ?? 0).getMinutes()) / 60) * HOUR)}px` }}+ >+ <span className="cx-ring" aria-hidden="true" />+ {r.title}+ </span>+ ))}+ {drag?.kind === "create" && drag.column === column && (+ <span+ className="cx-block is-draft"+ style={{ top: `${(drag.from / 60) * HOUR}px`, height: `${((drag.to - drag.from) / 60) * HOUR}px` }}+ >+ <span className="cx-block-title">New Event</span>+ </span>+ )}+ </div>+ ))}+ {todayColumn >= 0 && (+ <span+ className="cx-now"+ aria-hidden="true"+ style={{+ top: `${(nowMinutes / 60) * HOUR}px`,+ left: `${(todayColumn / days.length) * 100}%`,+ width: `${100 / days.length}%`,+ }}+ />+ )}+ </div>+ </div>+ </div>+ </div>+ );+}++const pointOf = (el: Element): Anchor => {+ const r = el.getBoundingClientRect();+ return { x: r.right, y: r.top };+};++/* ---- year --------------------------------------------------------------------------- */++function YearView({+ year,+ today,+ busy,+ onPick,+}: {+ year: number;+ today: Date;+ busy: (d: Date) => boolean;+ onPick: (d: Date) => void;+}) {+ return (+ <div className="cal-year" role="grid" aria-label={`${year}`}>+ {Array.from({ length: 12 }, (_, m) => {+ const first = new Date(year, m, 1);+ const days = monthDays(first);+ const current = today.getFullYear() === year && today.getMonth() === m;+ return (+ <section className="cal-mini" key={m} aria-label={first.toLocaleDateString(undefined, { month: "long" })}>+ <h2 className={`cx-year-month${current ? " is-current" : ""}`}>+ {first.toLocaleDateString(undefined, { month: "long" })}+ </h2>+ <div className="cx-minimonth-grid">+ {days.slice(0, 7).map((d) => (+ <span className="cx-minimonth-wd" key={`wd${d.getDay()}`} aria-hidden="true">+ {weekdayShort(d).slice(0, 1)}+ </span>+ ))}+ {days.map((d) =>+ d.getMonth() !== m ? (+ <span key={dayKey(d)} className="cx-minimonth-day is-blank" aria-hidden="true" />+ ) : (+ <button+ key={dayKey(d)}+ className={`cx-minimonth-day${sameDay(d, today) ? " is-today" : ""}${busy(d) ? " is-busy" : ""}`}+ aria-label={d.toLocaleDateString(undefined, { dateStyle: "full" })}+ onClick={() => onPick(d)}+ >+ {d.getDate()}+ </button>+ )+ )}+ </div>+ </section>+ );+ })}+ </div>+ );+}++/* ---- the event popover ---------------------------------------------------------------- */++function EventPopover({+ draft,+ at,+ calendars,+ busy,+ onChange,+ onClose,+ onSave,+ onDelete,+}: {+ draft: Draft;+ at: Anchor;+ calendars: Calendar[];+ busy: boolean;+ onChange: (d: Draft) => void;+ onClose: () => void;+ onSave: () => void;+ onDelete?: () => void;+}) {+ const box = useRef<HTMLFormElement | null>(null);+ const [pos, setPos] = useState<{ left: number; top: number }>({ left: at.x, top: at.y });+ const calendar = calendars.find((c) => c.guid === draft.calendarGuid);+ const editable = !draft.guid || (calendar?.writable ?? false);+ const choices = calendars.filter((c) => c.writable || c.guid === draft.calendarGuid);++ // Beside what was clicked, and always wholly on screen.+ useLayoutEffect(() => {+ const el = box.current;+ if (!el) return;+ const { width, height } = el.getBoundingClientRect();+ const gap = 12;+ let left = at.x + gap;+ if (left + width > window.innerWidth - 8) left = Math.max(8, at.x - width - gap);+ const top = Math.min(Math.max(8, at.y - 24), window.innerHeight - height - 8);+ setPos({ left, top });+ }, [at]);++ useEffect(() => {+ const onKey = (e: KeyboardEvent) => e.key === "Escape" && onClose();+ const onDown = (e: MouseEvent) => {+ if (box.current && !box.current.contains(e.target as Node)) onClose();+ };+ window.addEventListener("keydown", onKey);+ window.addEventListener("mousedown", onDown);+ return () => {+ window.removeEventListener("keydown", onKey);+ window.removeEventListener("mousedown", onDown);+ };+ }, [onClose]);++ const set = (patch: Partial<Draft>) => onChange({ ...draft, ...patch });+ return (+ <form+ ref={box}+ className="cx-popover"+ role="dialog"+ aria-label={draft.guid ? draft.title || "Event" : "New event"}+ style={{ left: pos.left, top: pos.top, "--cal": tint(calendar) } as React.CSSProperties}+ onSubmit={(e) => {+ e.preventDefault();+ if (editable) onSave();+ }}+ >+ <input+ className="cx-pop-title"+ value={draft.title}+ placeholder="New Event"+ aria-label="Title"+ autoFocus+ readOnly={!editable}+ onChange={(e) => set({ title: e.target.value })}+ />+ <input+ className="cx-pop-line"+ value={draft.location}+ placeholder="Add Location"+ aria-label="Location"+ readOnly={!editable}+ onChange={(e) => set({ location: e.target.value })}+ />+ <div className="cx-pop-rows">+ <label className="cx-pop-row">+ <span>all-day</span>+ <input+ type="checkbox"+ checked={draft.allDay}+ disabled={!editable}+ onChange={(e) => {+ const allDay = e.target.checked;+ const day = midnight(dateOf(draft.startsAt));+ set(+ allDay+ ? { allDay, startsAt: seconds(day), endsAt: seconds(addDays(day, 1)) }+ : { allDay, startsAt: seconds(day) + 9 * 3600, endsAt: seconds(day) + 10 * 3600 }+ );+ }}+ />+ </label>+ <label className="cx-pop-row">+ <span>starts</span>+ <input+ type={draft.allDay ? "date" : "datetime-local"}+ value={toLocalInput(draft.startsAt, draft.allDay)}+ readOnly={!editable}+ onChange={(e) => {+ if (!e.target.value) return;+ const startsAt = fromLocalInput(e.target.value);+ // Moving the start keeps the length, as Calendar does.+ set({ startsAt, endsAt: startsAt + (draft.endsAt - draft.startsAt) });+ }}+ />+ </label>+ <label className="cx-pop-row">+ <span>ends</span>+ <input+ type={draft.allDay ? "date" : "datetime-local"}+ value={toLocalInput(draft.allDay ? draft.endsAt - 1 : draft.endsAt, draft.allDay)}+ readOnly={!editable}+ onChange={(e) => {+ if (!e.target.value) return;+ const end = fromLocalInput(e.target.value);+ set({ endsAt: draft.allDay ? seconds(addDays(dateOf(end), 1)) : end });+ }}+ />+ </label>+ <div className="cx-pop-row cal-field">+ <span>calendar</span>+ <Picker+ label="Calendar"+ value={draft.calendarGuid}+ disabled={!editable || choices.length < 2}+ onChange={(guid) => set({ calendarGuid: guid })}+ options={choices.map((c) => ({ value: c.guid, label: c.title }))}+ />+ </div>+ </div>+ <textarea+ className="cx-pop-notes"+ value={draft.notes}+ placeholder="Add Notes"+ aria-label="Notes"+ rows={2}+ readOnly={!editable}+ onChange={(e) => set({ notes: e.target.value })}+ />+ <div className="cx-pop-actions">+ {onDelete && editable ? (+ <button type="button" className="cx-pop-delete" onClick={onDelete} disabled={busy}>+ Delete+ </button>+ ) : (+ <span />+ )}+ <span>+ <button type="button" className="quiet" onClick={onClose}>+ {editable ? "Cancel" : "Close"}+ </button>+ {editable && (+ <button type="submit" className="primary" disabled={busy}>+ {draft.guid ? "Save" : "Add"}+ </button>+ )}+ </span>+ </div>+ {!editable && <p className="cx-pop-note">This calendar can be read here but not changed.</p>}+ </form>+ );+}diff --git a/src/screens/calendar/model.ts b/src/screens/calendar/model.tsnew file mode 100644index 0000000..3b45775--- /dev/null+++ b/src/screens/calendar/model.ts@@ -0,0 +1,165 @@+/**+ * The arithmetic behind Calendar's views, kept apart from drawing them so it can be tested.+ *+ * Every date here is local: a calendar is read in the viewer's own time, and a day is from+ * one local midnight to the next — twenty-three or twenty-five hours on the two days a clock+ * moves, which is why nothing here adds a fixed 86,400 seconds.+ */+import type { CalendarEvent } from "../../lib/ipc";++export const midnight = (d: Date) => new Date(d.getFullYear(), d.getMonth(), d.getDate());+export const addDays = (d: Date, n: number) =>+ new Date(d.getFullYear(), d.getMonth(), d.getDate() + n);+export const seconds = (d: Date) => Math.floor(d.getTime() / 1000);+export const dateOf = (s: number) => new Date(s * 1000);+export const sameDay = (a: Date, b: Date) =>+ a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();+export const dayKey = (d: Date) => `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`;++/** The Sunday on or before `d`, where Apple starts a week. */+export const startOfWeek = (d: Date) => addDays(midnight(d), -d.getDay());++/** The six weeks a month shows: from the week holding the 1st, forty-two days. */+export function monthDays(anchor: Date): Date[] {+ const start = startOfWeek(new Date(anchor.getFullYear(), anchor.getMonth(), 1));+ return Array.from({ length: 42 }, (_, i) => addDays(start, i));+}++/** An event's first and last local day, the last being the day holding its final moment. */+export function daysOf(event: CalendarEvent): [Date, Date] {+ const first = midnight(dateOf(event.startsAt));+ // An all-day event ends at the next midnight, and one that ends exactly at midnight+ // does not reach into the day after.+ const last = midnight(dateOf(Math.max(event.endsAt - 1, event.startsAt)));+ return [first, last];+}++/**+ * Whether an event is drawn as a bar in the all-day row rather than as a block of time.+ *+ * All-day events, and timed ones of a day or more. An overnight event — eleven to one — is+ * a block on each of the two days it touches, which is how Calendar draws it.+ */+export const spansDays = (event: CalendarEvent) =>+ event.allDay || event.endsAt - event.startsAt >= 24 * 3600;++/** One bar in a week row: the columns it covers and the lane it sits in. */+export type Span = {+ event: CalendarEvent;+ /** 0–6, the first and last column it covers in this week. */+ from: number;+ to: number;+ lane: number;+ /** Whether it carries on from the week before, or into the week after. */+ continuesLeft: boolean;+ continuesRight: boolean;+};++/**+ * The bars of one week: each all-day or multi-day event, cut to the week, stacked into the+ * lowest lane where it collides with nothing — so a three-day trip is one bar, not three.+ */+export function weekSpans(events: CalendarEvent[], weekStart: Date): Span[] {+ const weekEnd = addDays(weekStart, 6);+ const within = events+ .filter(spansDays)+ .map((event) => {+ const [first, last] = daysOf(event);+ return { event, first, last };+ })+ .filter(({ first, last }) => last >= weekStart && first <= weekEnd)+ // Longest first, then earliest: how Apple stacks them.+ .sort(+ (a, b) =>+ b.last.getTime() - b.first.getTime() - (a.last.getTime() - a.first.getTime()) ||+ a.first.getTime() - b.first.getTime() ||+ a.event.title.localeCompare(b.event.title)+ );+ const lanes: boolean[][] = [];+ const out: Span[] = [];+ for (const { event, first, last } of within) {+ const from = Math.max(0, Math.round((midnight(first).getTime() - weekStart.getTime()) / 864e5));+ const to = Math.min(6, Math.round((midnight(last).getTime() - weekStart.getTime()) / 864e5));+ let lane = 0;+ while (lanes[lane]?.slice(from, to + 1).some(Boolean)) lane++;+ (lanes[lane] ??= Array(7).fill(false));+ for (let c = from; c <= to; c++) lanes[lane][c] = true;+ out.push({+ event,+ from,+ to,+ lane,+ continuesLeft: first < weekStart,+ continuesRight: last > weekEnd,+ });+ }+ return out;+}++/** A timed event placed on a day's hour grid. */+export type Placed = {+ event: CalendarEvent;+ /** Minutes from the day's midnight to where the block starts, and how long it is. */+ top: number;+ length: number;+ /** Side-by-side columns for events that overlap, as Apple lays them out. */+ column: number;+ columns: number;+};++/**+ * The timed events of one day, placed and set side by side where they overlap.+ *+ * Events that overlap, directly or through a chain, form a cluster; each takes the first+ * column free at its start, and the whole cluster shares one column count so the blocks line+ * up. A block is never shorter than a quarter hour, or a five-minute call would be unreadable.+ */+export function placeDay(events: CalendarEvent[], day: Date): Placed[] {+ const start = seconds(midnight(day));+ const end = seconds(addDays(day, 1));+ const timed = events+ .filter((e) => !spansDays(e) && e.endsAt > start && e.startsAt < end)+ .map((event) => {+ const from = Math.max(event.startsAt, start);+ const to = Math.min(Math.max(event.endsAt, event.startsAt), end);+ const top = (from - start) / 60;+ return { event, top, length: Math.max((to - from) / 60, 15) };+ })+ .sort((a, b) => a.top - b.top || b.length - a.length);++ const out: Placed[] = [];+ let cluster: Placed[] = [];+ let clusterEnd = -1;+ const close = () => {+ const columns = Math.max(1, ...cluster.map((p) => p.column + 1));+ for (const p of cluster) p.columns = columns;+ out.push(...cluster);+ cluster = [];+ };+ for (const item of timed) {+ if (item.top >= clusterEnd && cluster.length) close();+ const busy = cluster.filter((p) => p.top + p.length > item.top).map((p) => p.column);+ let column = 0;+ while (busy.includes(column)) column++;+ cluster.push({ ...item, column, columns: 1 });+ clusterEnd = Math.max(clusterEnd, item.top + item.length);+ }+ if (cluster.length) close();+ return out;+}++/** Snap a number of minutes to the nearest quarter hour, as dragging in Calendar does. */+export const snap = (minutes: number, step = 15) => Math.round(minutes / step) * step;++/** "9 AM", "Noon", "3 PM" — the hour labels in the viewer's own clock. */+export function hourLabel(hour: number): string {+ if (hour === 12) return "Noon";+ const d = new Date(2024, 0, 1, hour);+ return d.toLocaleTimeString(undefined, { hour: "numeric" });+}++/** "9:30 AM", with ":00" left off, as Calendar writes a time. */+export const clock = (s: number) =>+ dateOf(s)+ .toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" })+ .replace(/:00(?=\D|$)/, "");diff --git a/src/styles/app.css b/src/styles/app.cssindex 6cd1c5b..3910e2e 100644--- a/src/styles/app.css+++ b/src/styles/app.css@@ -531,81 +531,6 @@.cal-actions { display: flex; align-items: center; gap: 12px; }-.cal-weekdays {- display: grid;- grid-template-columns: repeat(7, 1fr);- border-bottom: 1px solid var(--separator);- padding-bottom: 5px;- margin-bottom: 1px;-}--.cal-weekdays span {- font-size: var(--t-11);- font-weight: 600;- color: var(--text-3);- text-align: center;-}--.cal-grid {- flex: 1;- min-height: 0;- display: grid;- grid-template-columns: repeat(7, 1fr);- grid-auto-rows: minmax(84px, 1fr);- /* Hairlines drawn by the gap, so cells stay a single element each. */- gap: 1px;- background: var(--separator);- border: 1px solid var(--separator);- border-radius: var(--r-plateau);- overflow: hidden;-}--/* Rows exist for assistive technology; the grid still lays the cells out. */-.cal-week { display: contents; }--.cal-day {- background: var(--bg);- 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 {align-self: flex-start;font-size: var(--t-11);@@ -1276,123 +1201,6 @@ textarea.note-text:disabled {.rem-list.add { color: var(--text-3); }.rem-list.add:hover { color: var(--text-2); }-/* 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 {- min-width: 0;- overflow: hidden;- text-overflow: ellipsis;- white-space: nowrap;-}--/* Beside what it labels, not at the far end of the pane. */-.cal-day-item .badge { margin-left: 4px; }--/* 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,-.cal-form .cal-field {- 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;@@ -1532,217 +1340,6 @@ button.cal-day-item:hover { background: color-mix(in srgb, var(--sheet) 92%, var.segment:focus-visible { outline: 3px solid var(--gold-ring); outline-offset: 1px; }-/* ── Day and week ───────────────────────────────────────────────────────────────────────- An hour grid: a gutter of times down the left, a column per day, all-day events in their- own row above the hours. Events are placed on the grid's tracks rather than by pixel, so- they stay put when the window changes size. */-.cal-hours-wrap {- flex: 1;- min-height: 0;- overflow-y: auto;- border: 1px solid var(--separator);- border-radius: var(--r-plateau);- background: var(--bg);-}--.cal-hours {- display: grid;- grid-template-columns: 52px repeat(7, minmax(0, 1fr));- grid-auto-rows: 44px;- /* The head and the all-day row size to their contents; the hours are fixed. */- grid-template-rows: auto auto;- position: relative;-}--.cal-hours.is-day { grid-template-columns: 52px minmax(0, 1fr); }--.cal-hours-corner,-.cal-allday-label {- position: sticky;- left: 0;- background: var(--bg);- border-right: 1px solid var(--separator);-}--.cal-allday-label {- font-size: var(--t-11);- color: var(--text-3);- padding: 4px 6px;- text-align: right;- border-bottom: 1px solid var(--separator);-}--.cal-col-head {- position: sticky;- top: 0;- z-index: 3;- display: flex;- flex-direction: column;- align-items: center;- gap: 1px;- padding: 6px 4px 5px;- border: 0;- border-left: 1px solid var(--separator);- background: var(--bg);- font: inherit;- color: var(--text-2);- cursor: pointer;-}--.cal-col-weekday { font-size: var(--t-11); text-transform: uppercase; letter-spacing: 0.4px; }--.cal-col-daynum {- font-size: var(--t-17);- font-weight: 590;- color: var(--text);- font-variant-numeric: tabular-nums;- min-width: 26px;- height: 26px;- line-height: 26px;- border-radius: var(--r-pill);- text-align: center;-}--.cal-col-head.is-today .cal-col-daynum { background: var(--gold); color: #fff; }-.cal-col-head.is-selected { box-shadow: inset 0 -2px 0 var(--gold); }-.cal-col-head:focus-visible { outline: 2px solid var(--gold); outline-offset: -2px; }--.cal-allday {- display: flex;- flex-direction: column;- gap: 2px;- min-height: 22px;- padding: 2px 3px;- border-left: 1px solid var(--separator);- border-bottom: 1px solid var(--separator);-}--.cal-hour-label {- position: sticky;- left: 0;- background: var(--bg);- border-right: 1px solid var(--separator);- font-size: var(--t-11);- color: var(--text-3);- text-align: right;- padding: 0 6px;- /* Sits against the line it names, as a ruler does. */- transform: translateY(-7px);- font-variant-numeric: tabular-nums;-}--.cal-hour-cell {- border: 0;- border-left: 1px solid var(--separator);- border-top: 1px solid var(--separator);- background: none;- padding: 0;- cursor: pointer;-}--.cal-hour-cell:hover { background: color-mix(in srgb, var(--text) 4%, transparent); }-.cal-hour-cell:focus-visible { outline: 2px solid var(--gold); outline-offset: -2px; }--.cal-timed {- display: flex;- align-items: stretch;- gap: 5px;- align-self: start;- z-index: 2;- margin-inline: 3px;- padding: 2px 4px 2px 0;- border: 0;- border-radius: 5px;- background: var(--sheet);- box-shadow: 0 1px 2px rgba(0, 0, 0, 0.16), 0 0 0 0.5px var(--glass-edge);- font: inherit;- text-align: left;- overflow: hidden;- cursor: pointer;-}--.cal-timed-bar { flex: none; width: 3px; border-radius: var(--r-pill); }--.cal-timed-text {- display: flex;- flex-direction: column;- min-width: 0;- line-height: 1.25;- padding-top: 1px;-}--.cal-timed-title {- font-size: var(--t-11);- font-weight: 550;- overflow: hidden;- text-overflow: ellipsis;- white-space: nowrap;-}--.cal-timed-when { font-size: var(--t-11); color: var(--text-2); }--/* ── Year ───────────────────────────────────────────────────────────────────────────────- Twelve months at a glance, each one clickable. A day with something on it is marked, so- the year reads as a heat map of where the work is. */-.cal-year {- flex: 1;- min-height: 0;- overflow-y: auto;- display: grid;- grid-template-columns: repeat(auto-fit, minmax(168px, 1fr));- gap: 14px;- padding: 4px 2px;-}--.cal-mini {- display: flex;- flex-direction: column;- gap: 5px;- border: 0;- background: none;- font: inherit;- color: inherit;- text-align: left;- padding: 6px;- border-radius: var(--r-plateau);- cursor: pointer;-}--.cal-mini:hover { background: color-mix(in srgb, var(--text) 4%, transparent); }-.cal-mini:focus-visible { outline: 3px solid var(--gold-ring); outline-offset: -1px; }--.cal-mini-name {- font-size: var(--t-13);- font-weight: 600;- color: var(--gold-strong);-}--.cal-mini-grid {- display: grid;- grid-template-columns: repeat(7, 1fr);- gap: 1px 0;-}--.cal-mini-weekday {- font-size: 9px;- color: var(--text-3);- text-align: center;- padding-bottom: 2px;-}--.cal-mini-day {- font-size: var(--t-11);- text-align: center;- line-height: 18px;- border-radius: var(--r-pill);- font-variant-numeric: tabular-nums;-}--.cal-mini-day.outside { color: transparent; }-.cal-mini-day.is-today { background: var(--gold); color: #fff; font-weight: 600; }-.cal-mini-day.has-items { font-weight: 620; color: var(--gold-strong); }-.cal-mini-day.is-today.has-items { color: #fff; }-/* ── Editing a contact ──────────────────────────────────────────────────────────────────The card and the editor are the same surface: the same measure, the same rhythm, sopressing Edit changes what you can do rather than where you are. */diff --git a/src/styles/calendar.css b/src/styles/calendar.cssnew file mode 100644index 0000000..6b514ee--- /dev/null+++ b/src/styles/calendar.css@@ -0,0 +1,551 @@+/* Calendar, laid out the way macOS Calendar is. Scoped under `.cx`. */++.content:has(.cx) { display: flex; flex-direction: column; overflow: hidden; padding-top: 18px; }++.cx {+ flex: 1;+ min-height: 0;+ display: grid;+ grid-template-columns: 216px minmax(0, 1fr);+ gap: 0;+}++/* ---- sidebar: the calendars, and the month in miniature ------------------------ */++.cx-side {+ display: flex;+ flex-direction: column;+ justify-content: space-between;+ min-height: 0;+ padding: 4px 14px 10px;+ border-right: 1px solid var(--separator);+ overflow-y: auto;+}+.cx-cals { display: flex; flex-direction: column; gap: 2px; }+.cx-side-heading {+ margin: 10px 0 4px;+ color: var(--text-3);+ font-size: var(--t-11);+ font-weight: 600;+}+.cx-side-heading:first-child { margin-top: 0; }++.cx-cal {+ display: flex;+ align-items: center;+ gap: 8px;+ height: 26px;+ padding: 0 6px;+ border-radius: 6px;+ font-size: var(--t-13);+ cursor: default;+}+.cx-cal:hover { background: color-mix(in srgb, var(--text) 6%, transparent); }+.cx-cal-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }++/* Apple's calendar checkbox: a rounded square in the calendar's own colour. */+.cx-cal input {+ appearance: none;+ flex: none;+ display: grid;+ place-items: center;+ width: 14px;+ height: 14px;+ margin: 0;+ border: 1.5px solid var(--cal);+ border-radius: 4px;+ background: transparent;+}+.cx-cal input:checked { background: var(--cal); }+.cx-cal input:checked::after {+ content: "";+ width: 7px;+ height: 4px;+ margin-top: -2px;+ border-left: 1.6px solid #fff;+ border-bottom: 1.6px solid #fff;+ transform: rotate(-45deg);+}+.cx-cal input:focus-visible { outline: 3px solid color-mix(in srgb, var(--cal) 40%, transparent); outline-offset: 1px; }++.cx-minimonth { padding-top: 12px; }+.cx-minimonth-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ margin-bottom: 4px;+ font-size: var(--t-13);+ font-weight: 600;+}+.cx-minimonth-head > span:last-child { display: inline-flex; gap: 2px; }+.cx-minimonth-grid { display: grid; grid-template-columns: repeat(7, 1fr); row-gap: 1px; }+.cx-minimonth-wd { color: var(--text-3); font-size: 10px; font-weight: 600; text-align: center; line-height: 20px; }+.cx-minimonth-day {+ position: relative;+ justify-self: center;+ width: 23px;+ height: 23px;+ padding: 0;+ border: 0;+ border-radius: 50%;+ background: none;+ color: var(--text);+ font: inherit;+ font-size: 11px;+ font-variant-numeric: tabular-nums;+ cursor: default;+}+.cx-minimonth-day:hover { background: color-mix(in srgb, var(--text) 8%, transparent); }+.cx-minimonth-day.is-out { color: var(--text-3); }+.cx-minimonth-day.is-selected { background: color-mix(in srgb, var(--text) 16%, transparent); font-weight: 600; }+.cx-minimonth-day.is-today { background: var(--sys-red); color: #fff; font-weight: 700; }+.cx-minimonth-day.is-busy::after {+ content: "";+ position: absolute;+ left: 50%;+ bottom: 1px;+ width: 3px;+ height: 3px;+ margin-left: -1.5px;+ border-radius: 50%;+ background: var(--text-3);+}+.cx-minimonth-day.is-today.is-busy::after { background: #fff; }+.cx-minimonth-day.is-blank { visibility: hidden; }+.cx-minimonth-day:focus-visible { outline: 2px solid var(--sys-blue); outline-offset: 1px; }++/* ---- toolbar -------------------------------------------------------------------- */++.cx-main { display: flex; flex-direction: column; min-width: 0; min-height: 0; }+/* Title, then the scopes, then stepping — wrapping onto a second line in a narrow window+ rather than running into each other. */+.cx-bar {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 10px 16px;+ padding: 0 18px 12px;+}+.cx-title {+ flex: 1 1 auto;+ min-width: 0;+ margin: 0;+ font-size: 22px;+ font-weight: 400;+ letter-spacing: -0.02em;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}+.cx-title strong { font-weight: 700; }+.cx-tools { display: flex; justify-content: flex-end; align-items: center; gap: 10px; }+.cx-step { display: inline-flex; align-items: center; gap: 2px; }++.cx-icon {+ display: grid;+ place-items: center;+ min-width: 28px;+ height: 26px;+ padding: 0 6px;+ border: 0;+ border-radius: 6px;+ background: none;+ color: var(--text-2);+ font: inherit;+ font-size: 18px;+ line-height: 1;+ cursor: default;+}+.cx-icon.small { min-width: 22px; height: 22px; font-size: 15px; }+.cx-icon:hover { background: color-mix(in srgb, var(--text) 8%, transparent); color: var(--text); }+.cx-today {+ height: 24px;+ padding: 0 10px;+ border: 1px solid var(--field-edge);+ border-radius: 6px;+ background: var(--field);+ color: var(--text);+ font: inherit;+ font-size: var(--t-13);+ cursor: default;+}+.cx-icon:focus-visible, .cx-today:focus-visible { outline: 3px solid color-mix(in srgb, var(--sys-blue) 40%, transparent); }++.cx-error { margin: 0 18px 8px; color: var(--danger); font-size: var(--t-13); }++/* ---- month ---------------------------------------------------------------------- */++.cx-month { flex: 1; display: flex; flex-direction: column; min-height: 0; }+.cx-weekdays {+ display: grid;+ grid-template-columns: repeat(7, 1fr);+ border-bottom: 1px solid var(--separator);+}+/* Weekday names on the right of each column, over the day numbers, as Apple sets them. */+.cx-weekdays span { padding: 0 10px 6px; color: var(--text-2); font-size: var(--t-13); text-align: right; }++.cal-grid { flex: 1; display: grid; grid-template-rows: repeat(6, minmax(0, 1fr)); min-height: 0; }+.cx-week {+ position: relative;+ display: grid;+ grid-template-columns: repeat(7, minmax(0, 1fr));+ border-bottom: 1px solid var(--separator);+ min-height: 0;+}+.cx-week:last-child { border-bottom: 0; }+.cx-day {+ container-type: inline-size;+ position: relative;+ min-width: 0;+ min-height: 0;+ padding: 26px 3px 2px;+ border-right: 1px solid var(--separator);+ overflow: hidden;+}+.cx-day:last-child { border-right: 0; }+.cx-day.is-weekend { background: color-mix(in srgb, var(--text) 2.5%, transparent); }+.cx-day.is-selected { background: color-mix(in srgb, var(--sys-blue) 7%, transparent); }+.cx-day-hit {+ position: absolute;+ inset: 0;+ z-index: 0;+ padding: 0;+ border: 0;+ background: none;+ cursor: default;+}+.cx-day-hit:focus-visible { outline: 2px solid var(--sys-blue); outline-offset: -2px; }++.cx-daynum {+ position: absolute;+ top: 4px;+ right: 6px;+ z-index: 1;+ min-width: 22px;+ height: 22px;+ padding: 0 5px;+ border-radius: 11px;+ font-size: var(--t-13);+ font-variant-numeric: tabular-nums;+ line-height: 22px;+ text-align: center;+ pointer-events: none;+}+.cx-day.is-out .cx-daynum { color: var(--text-3); }+.cx-daynum.is-today { background: var(--sys-red); color: #fff; font-weight: 700; }++.cx-items { position: relative; z-index: 1; margin: 0; padding: 0; list-style: none; pointer-events: none; }+.cx-items li { pointer-events: auto; }+.cx-item {+ display: grid;+ grid-template-columns: 8px minmax(0, 1fr) auto;+ align-items: center;+ gap: 5px;+ width: 100%;+ height: 18px;+ padding: 0 4px;+ border: 0;+ border-radius: 4px;+ background: none;+ color: var(--text);+ font: inherit;+ font-size: var(--t-11);+ text-align: left;+ cursor: default;+}+.cx-item:hover { background: color-mix(in srgb, var(--cal, var(--text)) 14%, transparent); }+.cx-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--cal); }+.cx-ring { width: 8px; height: 8px; border: 1.3px solid var(--text-3); border-radius: 50%; box-sizing: border-box; }+.cx-item-title { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.cx-item-time { color: var(--text-3); font-variant-numeric: tabular-nums; }+/* In a narrow cell the title matters more than the time, which Apple drops first. */+@container (max-width: 130px) {+ .cx-item { grid-template-columns: 8px minmax(0, 1fr); }+ .cx-item-time { display: none; }+}+.cx-item.is-reminder.is-done .cx-item-title { color: var(--text-3); text-decoration: line-through; }+.cx-more {+ padding: 0 6px;+ border: 0;+ background: none;+ color: var(--text-2);+ font: inherit;+ font-size: var(--t-11);+ font-weight: 600;+ cursor: default;+}+.cx-more:hover { color: var(--text); }++/* An all-day or multi-day event: one tinted bar across the days it covers. */+.cx-bar-event {+ position: absolute;+ z-index: 2;+ height: 18px;+ padding: 0 7px;+ border: 0;+ border-radius: 4px;+ background: color-mix(in srgb, var(--cal) 24%, transparent);+ color: var(--text);+ font: inherit;+ font-size: var(--t-11);+ font-weight: 600;+ text-align: left;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ cursor: default;+}+.cx-bar-event::before {+ content: "";+ position: absolute;+ inset: 0 auto 0 0;+ width: 3px;+ background: var(--cal);+}+.cx-bar-event.from-before { border-top-left-radius: 0; border-bottom-left-radius: 0; }+.cx-bar-event.from-before::before { display: none; }+.cx-bar-event.to-after { border-top-right-radius: 0; border-bottom-right-radius: 0; }+.cx-bar-event:hover { background: color-mix(in srgb, var(--cal) 34%, transparent); }+.cx-bar-event:focus-visible, .cx-item:focus-visible { outline: 2px solid var(--sys-blue); outline-offset: 0; }++/* ---- week and day ------------------------------------------------------------------ */++.cal-hours { flex: 1; display: flex; flex-direction: column; min-height: 0; }+.cx-gutter { width: 56px; flex: none; }+.cx-grid-head,+.cx-allday { display: flex; border-bottom: 1px solid var(--separator); }+.cx-grid-head > .cal-col-head { flex: 1; }+.cal-col-head {+ display: flex;+ align-items: baseline;+ justify-content: center;+ gap: 6px;+ min-width: 0;+ padding: 0 0 8px;+ border: 0;+ background: none;+ color: var(--text-2);+ font: inherit;+ font-size: var(--t-13);+ cursor: default;+}+.cx-col-num { font-size: 20px; font-weight: 400; color: var(--text); font-variant-numeric: tabular-nums; }+.cal-col-head.is-today .cx-col-num {+ min-width: 28px;+ padding: 0 6px;+ border-radius: 14px;+ background: var(--sys-red);+ color: #fff;+ font-weight: 600;+}+.cal-col-head.is-today .cx-col-weekday { color: var(--sys-red); font-weight: 600; }+.cal-col-head:focus-visible { outline: 2px solid var(--sys-blue); outline-offset: -2px; }++.cx-allday { position: relative; min-height: 28px; }+.cx-allday-label {+ padding: 5px 8px 0 0;+ color: var(--text-3);+ font-size: var(--t-11);+ text-align: right;+}+.cx-allday-lanes { position: relative; flex: 1; }++.cx-scroll { flex: 1; min-height: 0; overflow-y: auto; }+.cx-hours-body { position: relative; display: flex; }+.cx-hour-labels { position: relative; }+.cx-hour-labels span {+ position: absolute;+ right: 8px;+ transform: translateY(-50%);+ color: var(--text-3);+ font-size: var(--t-11);+ font-variant-numeric: tabular-nums;+ white-space: nowrap;+}+.cx-hour-labels .cx-now-label { z-index: 2; padding: 0 2px; background: var(--bg); color: var(--sys-red); font-weight: 600; }++.cx-columns {+ position: relative;+ flex: 1;+ display: grid;+ grid-template-columns: repeat(var(--cols), minmax(0, 1fr));+ background-image: linear-gradient(to bottom, var(--separator) 1px, transparent 1px);+ background-size: 100% 48px;+ touch-action: none;+}+.cx-column { position: relative; border-left: 1px solid var(--separator); }+.cx-column.is-weekend { background: color-mix(in srgb, var(--text) 2.5%, transparent); }++/* A timed event: a tinted block with a stripe of its calendar's colour down the left. */+.cx-block {+ position: absolute;+ z-index: 1;+ display: flex;+ flex-direction: column;+ align-items: flex-start;+ gap: 1px;+ margin-left: 2px;+ padding: 3px 6px 3px 8px;+ border: 0;+ border-radius: 5px;+ background: color-mix(in srgb, var(--cal) 22%, var(--bg));+ color: var(--text);+ font: inherit;+ text-align: left;+ overflow: hidden;+ cursor: default;+ transition: box-shadow 120ms var(--ease);+}+.cx-block::before {+ content: "";+ position: absolute;+ inset: 0 auto 0 0;+ width: 3px;+ background: var(--cal);+}+.cx-block:hover { background: color-mix(in srgb, var(--cal) 32%, var(--bg)); }+.cx-block:focus-visible { outline: 2px solid var(--sys-blue); outline-offset: 0; }+.cx-block.is-moving { z-index: 3; box-shadow: 0 6px 20px rgba(0, 0, 0, 0.28); opacity: 0.94; }+.cx-block.is-draft {+ --cal: var(--sys-blue);+ left: 0;+ right: 3px;+ width: auto;+ background: color-mix(in srgb, var(--sys-blue) 26%, var(--bg));+ pointer-events: none;+}+.cx-block-title { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: var(--t-11); font-weight: 600; }+.cx-block-time,+.cx-block-where { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--text-2); font-size: 10.5px; }++.cx-reminder {+ position: absolute;+ left: 4px;+ right: 4px;+ z-index: 1;+ display: flex;+ align-items: center;+ gap: 5px;+ height: 18px;+ font-size: var(--t-11);+ overflow: hidden;+ white-space: nowrap;+ text-overflow: ellipsis;+ pointer-events: none;+}+.cx-reminder.is-done { color: var(--text-3); text-decoration: line-through; }++/* Now: a red line across today with a dot at its start. */+.cx-now {+ position: absolute;+ z-index: 2;+ height: 2px;+ margin-top: -1px;+ background: var(--sys-red);+ pointer-events: none;+}+.cx-now::before {+ content: "";+ position: absolute;+ left: -4px;+ top: -3px;+ width: 8px;+ height: 8px;+ border-radius: 50%;+ background: var(--sys-red);+}++/* ---- year --------------------------------------------------------------------------- */++.cal-year {+ flex: 1;+ display: grid;+ grid-template-columns: repeat(4, minmax(0, 1fr));+ gap: 22px 28px;+ padding: 6px 18px 18px;+ overflow-y: auto;+}+.cx-year-month { margin: 0 0 6px; color: var(--text); font-size: var(--t-15); font-weight: 700; }+.cx-year-month.is-current { color: var(--sys-red); }++@media (max-width: 1100px) { .cal-year { grid-template-columns: repeat(3, minmax(0, 1fr)); } }+@media (max-width: 820px) {+ .cx { grid-template-columns: 1fr; }+ .cx-side { display: none; }+ .cal-year { grid-template-columns: repeat(2, minmax(0, 1fr)); }+ .cx-bar { grid-template-columns: 1fr; justify-items: start; }+}++/* ---- the event popover --------------------------------------------------------------- */++.cx-popover {+ position: fixed;+ z-index: 40;+ display: flex;+ flex-direction: column;+ gap: 8px;+ width: 300px;+ padding: 14px 14px 12px;+ border: 1px solid var(--glass-edge);+ border-radius: 12px;+ background: var(--sheet);+ box-shadow: var(--shadow-sheet);+ animation: cx-pop 160ms var(--ease) both;+}+@keyframes cx-pop { from { opacity: 0; transform: scale(0.97); } to { opacity: 1; transform: none; } }+.cx-popover input,+.cx-popover textarea {+ border: 0;+ background: none;+ color: var(--text);+ font: inherit;+ outline: none;+}+.cx-pop-title { padding: 0; font-size: var(--t-17); font-weight: 700; }+.cx-pop-title::placeholder, .cx-pop-line::placeholder, .cx-pop-notes::placeholder { color: var(--text-3); }+.cx-pop-line { padding: 0; font-size: var(--t-13); }+.cx-pop-rows { display: flex; flex-direction: column; gap: 6px; padding: 8px 0; border-top: 1px solid var(--separator); border-bottom: 1px solid var(--separator); }+.cx-pop-row { display: grid; grid-template-columns: 64px minmax(0, 1fr); align-items: center; gap: 8px; font-size: var(--t-13); }+.cx-pop-row > span:first-child { color: var(--text-2); text-align: right; }+.cx-pop-row input[type="datetime-local"],+.cx-pop-row input[type="date"] {+ padding: 3px 6px;+ border: 1px solid var(--field-edge);+ border-radius: 6px;+ background: var(--field);+ font-size: var(--t-13);+ color-scheme: light dark;+}+.cx-pop-row input[type="checkbox"] { justify-self: start; width: 16px; height: 16px; accent-color: var(--sys-blue); }+.cx-pop-notes { padding: 0; font-size: var(--t-13); resize: vertical; }+.cx-pop-actions { display: flex; align-items: center; justify-content: space-between; gap: 8px; }+.cx-pop-actions > span { display: flex; gap: 6px; }+.cx-pop-delete { padding: 4px 6px; border: 0; background: none; color: var(--sys-red); font: inherit; font-size: var(--t-13); cursor: default; }+.cx-pop-note { margin: 0; color: var(--text-3); font-size: var(--t-11); }++.cx-toast {+ position: fixed;+ left: 50%;+ bottom: 24px;+ z-index: 45;+ display: flex;+ align-items: center;+ gap: 14px;+ padding: 9px 10px 9px 16px;+ transform: translateX(-50%);+ border: 1px solid var(--glass-edge);+ border-radius: 12px;+ background: var(--sheet);+ box-shadow: var(--shadow-sheet);+ font-size: var(--t-13);+}+.cx-toast-undo {+ padding: 3px 10px;+ border: 0;+ border-radius: 6px;+ background: color-mix(in srgb, var(--sys-blue) 16%, transparent);+ color: var(--sys-blue);+ font: inherit;+ font-weight: 600;+ cursor: default;+}