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: Ctrl+Z takes back the last move, edit or deletion
Yashwanth Kamireddic41ed1b92e1b
diff --git a/.uiverify/calendar-undo.mjs b/.uiverify/calendar-undo.mjsnew file mode 100644index 0000000..3b79749--- /dev/null+++ b/.uiverify/calendar-undo.mjs@@ -0,0 +1,117 @@+// Week and Day as Calendar keeps them: the hours scrolled to stay put from one week to the+// next; the all-day row makes an all-day event on a double-click and carries a bar to another+// day; Ctrl+Z takes back the last move or deletion; and an event that ends as it starts is+// saved that way, not lengthened.+import { engine } from "./engine.mjs";+import { SERVICES, installStub, openScreen } from "./stub.mjs";+const BASE = process.env.BASE ?? "http://localhost:4173";+const b = await engine.launch();+const ctx = await b.newContext({ viewport: { width: 1300, height: 850 } });+await ctx.addInitScript(installStub, {+ screen: "library", services: SERVICES, twoFactor: null, calendarFixture: true,+ extraEvents: [+ // Today, all day: from this midnight (9 AM less nine hours) to the next.+ { guid: "ad1", title: "Offsite", hour: -9, length: 24, allDay: true },+ // A deadline: no length at all, as an invitation can send one.+ { guid: "dl1", title: "Forms due", hour: 8, length: 0 },+ ],+});+const page = await ctx.newPage();+await page.goto(BASE, { waitUntil: "networkidle" });+await openScreen(page, "Calendar");+await page.keyboard.press("Control+2");+await page.locator(".cx-scroll").waitFor();+let failures = 0;+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };+const saves = () => page.evaluate(() => window.__eventSaves ?? []);+const savesReach = (n) => page.waitForFunction((n) => (window.__eventSaves ?? []).length >= n, n, { timeout: 3000 }).catch(() => {});+const midnightIn = (n) => page.evaluate((n) => { const d = new Date(); d.setHours(0, 0, 0, 0); d.setDate(d.getDate() + n); return d.getTime() / 1000; }, n);++// The evening scrolled to stays in view on the next week, and on the way back.+const scroller = page.locator(".cx-scroll");+await scroller.evaluate((el) => { el.scrollTop = 18 * 48; });+const before = await scroller.evaluate((el) => el.scrollTop);+const title = await page.locator(".cx-title").getAttribute("aria-label");+await page.keyboard.press("ArrowRight");+await page.waitForFunction((t) => document.querySelector(".cx-title")?.getAttribute("aria-label") !== t, title);+ok(await scroller.evaluate((el) => el.scrollTop) === before, "the next week keeps the hours scrolled to");+await page.keyboard.press("ArrowLeft");+await page.waitForFunction((t) => document.querySelector(".cx-title")?.getAttribute("aria-label") === t, title);+ok(await scroller.evaluate((el) => el.scrollTop) === before, "and so does the week before");++// A double-click on a free part of the all-day row: an all-day event on that day.+const lanes = page.locator(".cx-allday-lanes");+const box = await lanes.boundingBox();+const today = await page.evaluate(() => [...document.querySelectorAll(".cal-col-head")].findIndex((h) => h.classList.contains("is-today")));+const other = today === 6 ? 5 : 6;+const colWidth = box.width / 7;+await page.mouse.dblclick(box.x + colWidth * other + colWidth / 2, box.y + box.height - 3);+const made = page.getByRole("dialog", { name: "New event" });+await made.waitFor({ timeout: 2000 }).catch(() => {});+ok(await made.isVisible(), "a double-click on the all-day row starts a new event");+ok(await made.getByRole("checkbox", { name: "all-day" }).isChecked().catch(() => false), "and it is all-day");+await page.keyboard.press("Escape");+await made.waitFor({ state: "detached" });++// The all-day bar carried one day on.+const bar = page.locator(".cx-allday .cx-bar-event", { hasText: "Offsite" });+const by = today === 6 ? -1 : 1;+const at = await bar.boundingBox();+await page.mouse.move(at.x + 10, at.y + at.height / 2);+await page.mouse.down();+await page.mouse.move(at.x + 10 + (by * colWidth) / 2, at.y + at.height / 2, { steps: 3 });+await page.mouse.move(at.x + 10 + by * colWidth, at.y + at.height / 2, { steps: 4 });+const moved = await bar.boundingBox();+ok(Math.abs(moved.x - at.x - by * colWidth) < 4, `the bar follows the pointer [${Math.round(moved.x - at.x)}]`);+await page.mouse.up();+await savesReach(1);+let s = await saves();+const start = await midnightIn(0);+ok(s.length === 1 && s[0].guid === "ad1" && s[0].allDay && s[0].startsAt === (await midnightIn(by)) && s[0].endsAt === (await midnightIn(by + 1)),+ `the bar is moved a day ${JSON.stringify(s[0] && { g: s[0].guid, d: (s[0].startsAt - start) / 3600 })}`);+ok(await page.getByRole("dialog").count() === 0, "a carried bar does not open");++// Ctrl+Z: the move taken back.+await page.keyboard.press("Control+z");+await savesReach(2);+s = await saves();+ok(s.length === 2 && s[1].guid === "ad1" && s[1].startsAt === start && s[1].endsAt === (await midnightIn(1)), `Ctrl+Z puts it back ${JSON.stringify(s[1] && { g: s[1].guid, d: (s[1].startsAt - start) / 3600 })}`);+await page.keyboard.press("Control+z");+await page.waitForTimeout(300);+ok((await saves()).length === 2, "a second Ctrl+Z has nothing more to take back");++// A held-still press on the bar opens it.+await bar.click();+const opened = page.getByRole("dialog", { name: "Offsite" });+await opened.waitFor({ timeout: 2000 }).catch(() => {});+ok(await opened.isVisible(), "a click on the bar opens it");+await page.keyboard.press("Escape");+await opened.waitFor({ state: "detached" });++// Deleted from the keyboard, then Ctrl+Z makes it again.+await page.locator(".cx-block", { hasText: "Dentist" }).click();+await page.getByRole("dialog", { name: "Dentist" }).waitFor();+await page.keyboard.press("Escape");+await page.keyboard.press("Delete");+await page.getByRole("button", { name: "Delete", exact: true }).click();+await page.waitForFunction(() => (window.__eventDeletes ?? []).length === 1);+await page.keyboard.press("Control+z");+await savesReach(3);+s = await saves();+ok(s.length === 3 && s[2].guid === null && s[2].title === "Dentist" && JSON.stringify(s[2].alerts) === "[15]",+ `Ctrl+Z makes the deleted event again, its alert with it ${JSON.stringify(s[2] && { g: s[2].guid, t: s[2].title, a: s[2].alerts })}`);++// An event that ends as it starts keeps no length when its title is changed.+await page.locator(".cx-block", { hasText: "Forms due" }).click();+const deadline = page.getByRole("dialog", { name: "Forms due" });+await deadline.waitFor();+await deadline.getByLabel("Title").fill("Forms in");+// Named by its title, the dialog is "Forms in" now.+await page.getByRole("dialog", { name: "Forms in" }).getByRole("button", { name: "Save" }).click();+await savesReach(4);+s = await saves();+ok(s.length === 4 && s[3].guid === "dl1" && s[3].endsAt === s[3].startsAt, `a deadline stays a moment ${JSON.stringify(s[3] && { g: s[3].guid, len: s[3].endsAt - s[3].startsAt })}`);++await b.close();+console.log(failures ? `${failures} failed` : "all passed");+process.exitCode = failures ? 1 : 0;diff --git a/src/screens/calendar/CalendarView.tsx b/src/screens/calendar/CalendarView.tsxindex 3fe97af..f6ff114 100644--- a/src/screens/calendar/CalendarView.tsx+++ b/src/screens/calendar/CalendarView.tsx@@ -351,6 +351,11 @@ const draftOf = (e: CalendarEvent): Draft => ({timezone: e.timezone,});+/** Where a saved event ends: an all-day one at least a day on, a timed one never before its+ * start. A timed event may end as it starts — a deadline sent in an invitation does — and+ * lengthening it to a quarter hour changed it on every device whenever its title was edited. */+const endOf = (d: Draft) => Math.max(d.endsAt, d.allDay ? addDaysIn(ZONE, d.startsAt, 1) : d.startsAt);+/** `YYYY-MM-DDTHH:mm` and `YYYY-MM-DD` for the date inputs, in local time. */const pad = (n: number) => String(n).padStart(2, "0");/** The zone an event's times are read in: its own, or this computer's (all-day events are@@ -769,8 +774,16 @@ export function CalendarView() {const whichEvents = (verb: "change" | "delete") =>new Promise<EventScope | null>((answer) => setAsking({ verb, answer: (scope) => { setAsking(null); answer(scope); } }));+ /**+ * What ⌘Z (Ctrl+Z here) takes back, as Edit ▸ Undo does in Calendar: the last event deleted,+ * or the last change to one — a drag, a resize, a nudge, an edit — put back as it was. One+ * step, and only for an event of its own: one day of a repeating event, or a change of its+ * alerts or repeat, is not something putting the old fields back would undo.+ */+ const lastAct = useRef<{ kind: "delete"; gone: CalendarEvent & { alerts: Promise<number[]> } } | { kind: "change"; before: Draft } | null>(null);+const save = useCallback(- async (d: Draft, close = false) => {+ async (d: Draft, close = false, undoing = false) => {const occurrence = Boolean(d.guid && d.guid.includes("__"));// A repeat belongs to the series, so changing it is a change to all of it.const scope = occurrence ? (d.repeatChanged ? "all" : await whichEvents("change")) : null;@@ -778,7 +791,17 @@ export function CalendarView() {// Closed the moment it is saved, drawn as saved, never waiting on Apple: kept open until// Apple answered, the popover hung for a second or two on every Done.if (close) setDraft(null);- return write(async () => {+ const was = d.guid ? events.find((e) => e.guid === d.guid) : undefined;+ const undoable = !undoing && !occurrence && !d.alertsChanged && !d.repeatChanged && was &&+ !was.guid.startsWith("quince:") && !was.guid.startsWith("pending:") && (+ was.startsAt !== d.startsAt || was.endsAt !== endOf(d) || was.title !== (d.title.trim() || "New Event") ||+ (was.location ?? "") !== d.location.trim() || (was.notes ?? "") !== d.notes.trim() ||+ was.allDay !== d.allDay || was.calendarGuid !== d.calendarGuid || (was.url ?? "") !== (d.url?.trim() ?? "") ||+ (!d.allDay && was.timezone !== d.timezone));+ const step = undoable ? { kind: "change" as const, before: draftOf(was) } : null;+ if (step) lastAct.current = step;+ else if (undoing) lastAct.current = null;+ const saved = await write(async () => {await api.eventSave({...(scope ? { scope } : {}),guid: d.guid,@@ -786,7 +809,7 @@ export function CalendarView() {title: d.title.trim() || "New Event",location: d.location.trim() || null,startsAt: d.startsAt,- endsAt: Math.max(d.endsAt, (d.allDay ? addDaysIn(ZONE, d.startsAt, 1) : d.startsAt + 900)),+ endsAt: endOf(d),allDay: d.allDay,timezone: d.allDay ? ZONE : (d.timezone ?? ZONE),notes: d.notes.trim() || null,@@ -800,7 +823,7 @@ export function CalendarView() {return [...rows, {guid: `pending:${d.startsAt}:${d.title}`, calendarGuid: d.calendarGuid,title: d.title.trim() || "New Event", location: d.location.trim() || null,- startsAt: d.startsAt, endsAt: Math.max(d.endsAt, (d.allDay ? addDaysIn(ZONE, d.startsAt, 1) : d.startsAt + 900)),+ startsAt: d.startsAt, endsAt: endOf(d),allDay: d.allDay, timezone: d.allDay ? ZONE : (d.timezone ?? ZONE),url: d.url?.trim() || null, notes: d.notes.trim() || null, etag: null,}];@@ -817,10 +840,13 @@ export function CalendarView() {} : e.guid === d.guid ? {...e, calendarGuid: d.calendarGuid, title: d.title.trim() || "New Event",location: d.location.trim() || null, startsAt: d.startsAt,- endsAt: Math.max(d.endsAt, (d.allDay ? addDaysIn(ZONE, d.startsAt, 1) : d.startsAt + 900)),+ endsAt: endOf(d),allDay: d.allDay, notes: d.notes.trim() || null,} : e);});+ // Turned down, there is nothing of it to take back.+ if (!saved && step && lastAct.current === step) lastAct.current = null;+ return saved;},[write, events]);@@ -861,19 +887,26 @@ export function CalendarView() {)) {// Undo makes the event again; for one day out of a series that would be a new event,// not the day put back, so it is not offered.- if (!occurrence && gone) setUndo({ ...gone, alerts });+ if (!occurrence && gone) {+ setUndo({ ...gone, alerts });+ lastAct.current = { kind: "delete", gone: { ...gone, alerts } };+ }}},[events, write]);+ /** A deleted event made again as it was, its alerts with it (its guests are not this app's+ * to invite). */+ const restore = useCallback(async (gone: CalendarEvent & { alerts: Promise<number[]> }) => {+ if (lastAct.current?.kind === "delete" && lastAct.current.gone.guid === gone.guid) lastAct.current = null;+ const alerts = await gone.alerts;+ await save({ ...draftOf(gone), guid: null, alerts, alertsChanged: alerts.length > 0 }, false, true);+ }, [save]);const takeBack = useCallback(async () => {const gone = undo;setUndo(null);- // Made again as it was, its alerts with it (its guests are not this app's to invite).- if (!gone) return;- const alerts = await gone.alerts;- await save({ ...draftOf(gone), guid: null, alerts, alertsChanged: alerts.length > 0 });- }, [undo, save]);+ if (gone) await restore(gone);+ }, [undo, restore]);const moveEvent = useCallback((e: CalendarEvent, startsAt: number, endsAt: number) => void save({ ...draftOf(e), startsAt, endsAt }),[save]@@ -1211,6 +1244,17 @@ export function CalendarView() {if (plain && e.key === "Escape") { setPicked(null); return; }}if (command && k === "v" && clip && !inMenuNow) { e.preventDefault(); paste(clip); return; }+ // ⌘Z: the last deletion or change taken back (fields have their own undo, above).+ if (command && k === "z" && !inMenuNow) {+ e.preventDefault();+ const last = lastAct.current;+ lastAct.current = null;+ if (last?.kind === "delete") {+ if (undo?.guid === last.gone.guid) setUndo(null);+ void restore(last.gone);+ } else if (last) void save(last.before, false, true);+ return;+ }// ⇧⌘T, Go to Date…, as in Calendar's View menu.if ((e.metaKey || e.ctrlKey) && e.shiftKey && !e.altKey && k === "t") {e.preventDefault();