Skip to content

Native iCloud apps for Windows and Linux, built in Rust. Notes, Reminders, Calendar, Contacts, Drive and Photos, offline and in sync with your iPhone.

Calendar: stepping months and days shows what is there at once

Yashwanth Kamireddi0a913a09c264
diff --git a/.uiverify/calendar-monthstep.mjs b/.uiverify/calendar-monthstep.mjs
new file mode 100644
index 0000000..b53decb
--- /dev/null
+++ b/.uiverify/calendar-monthstep.mjs
@@ -0,0 +1,45 @@
+// Stepping Month to the next month and back shows its events at once, from what is already
+// read, never an empty month that fills in a moment later. The library read is made slow here
+// so a month drawn only once its own read came back would show empty.
+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 });
+// The 15th of next month and of last month, at noon: never in this month's six weeks, always
+// in theirs.
+await ctx.addInitScript(() => {
+ const at = (by) => { const d = new Date(); d.setDate(1); d.setMonth(d.getMonth() + by); d.setDate(15); d.setHours(12, 0, 0, 0); return d.getTime() / 1000; };
+ window.__fixedEvents = [
+ { guid: "next1", calendarGuid: "work", title: "Board meeting", location: null, startsAt: at(1), endsAt: at(1) + 3600, allDay: false, timezone: null, url: null, notes: null, etag: null },
+ { guid: "last1", calendarGuid: "work", title: "Quarter review", location: null, startsAt: at(-1), endsAt: at(-1) + 3600, allDay: false, timezone: null, url: null, notes: null, etag: null },
+ ];
+});
+const page = await ctx.newPage();
+await page.goto(BASE, { waitUntil: "networkidle" });
+await openScreen(page, "Calendar");
+await page.keyboard.press("Control+3");
+await page.locator(".cal-grid").waitFor();
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };
+// Everything this month asked for is in; from here on every read takes a second and a half.
+await page.waitForFunction(() => (window.__eventReads ?? 0) >= 1);
+await page.waitForTimeout(500);
+await page.evaluate(() => { window.__eventsSlow = 1500; });
+
+const title = () => page.locator(".cx-title").getAttribute("aria-label");
+const was = await title();
+await page.keyboard.press("ArrowRight");
+await page.waitForFunction((t) => document.querySelector(".cx-title")?.getAttribute("aria-label") !== t, was);
+await page.waitForTimeout(200);
+ok(await page.locator(".cx-item", { hasText: "Board meeting" }).count() === 1, "next month shows its events at once");
+
+await page.keyboard.press("ArrowLeft");
+await page.keyboard.press("ArrowLeft");
+await page.waitForTimeout(200);
+ok(await page.locator(".cx-item", { hasText: "Quarter review" }).count() === 1, "and so does last month");
+
+await b.close();
+console.log(failures ? `${failures} failed` : "all passed");
+process.exitCode = failures ? 1 : 0;
diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjs
index 12a4e50..6837770 100644
--- a/.uiverify/stub.mjs
+++ b/.uiverify/stub.mjs
@@ -176,8 +176,12 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
{ guid: `quince:sub:${x.id}:m2:1`, calendarGuid: `quince:sub:${x.id}`, title: "Liverpool v Spurs", location: null,
startsAt: base + 2 * DAY + 8 * HOUR, endsAt: base + 2 * DAY + 10 * HOUR, allDay: false, timezone: "Europe/London", url: null, notes: null, etag: null },
]);
- // A suite's own events at fixed moments (`window.__fixedEvents`), for a given day.
- const fixed = window.__fixedEvents ?? [];
+ // A suite's own events at fixed moments (`window.__fixedEvents`), for a given day —
+ // and, with `__eventsSlow` set, only those inside the range asked for, answered that
+ // many milliseconds late, as a library read over a range is.
+ const slow = window.__eventsSlow ?? 0;
+ if (slow) await new Promise((r) => setTimeout(r, slow));
+ const fixed = (window.__fixedEvents ?? []).filter((e) => !slow || (e.endsAt > args.from && e.startsAt < args.to));
if (!n) return [...events, ...subbed, ...fixed];
const extra = (window.__extra ??= Array.from({ length: n }, (_, i) => ({
guid: `many${i}`, calendarGuid: i % 2 ? "work" : "home", title: `Event ${i}`, location: null,
diff --git a/src/screens/calendar/CalendarView.tsx b/src/screens/calendar/CalendarView.tsx
index 083ddf2..f889191 100644
--- a/src/screens/calendar/CalendarView.tsx
+++ b/src/screens/calendar/CalendarView.tsx
@@ -601,27 +601,42 @@ export function CalendarView() {
// month either side: asked for one day at a time, stepping to the next day showed the last
// day's data — none of it on the new day — until the read came back, and the day's list
// flickered empty and full. Read from this computer, three months cost nothing, and moving
- // through them waits on nothing.
- const rawRange = useMemo(() => {
- if (view === "day" || view === "week")
- return {
- from: seconds(addDays(month[0] < week[0] ? month[0] : week[0], -35)),
- to: seconds(addDays(month[41] > week[6] ? month[41] : week[6], 36)),
- };
- if (view === "year")
- return {
+ // through them waits on nothing. Month reads a month either side too: read alone, the next
+ // month came up empty and filled in a moment later on every step.
+ //
+ // And the range read is kept while what is on screen, and a step either way, is inside it:
+ // a day stepped into the next month, or a week across one, asks for nothing again.
+ const heldRange = useRef<{ from: number; to: number; year: boolean } | null>(null);
+ const range = useMemo(() => {
+ if (view === "year") {
+ const year = {
from: seconds(new Date(selected.getFullYear(), 0, 1)),
to: seconds(new Date(selected.getFullYear() + 1, 0, 1)),
+ year: true,
};
- return { from: seconds(month[0]), to: seconds(addDays(month[41], 1)) };
+ const h = heldRange.current;
+ return (heldRange.current = h && h.year && h.from === year.from ? h : year);
+ }
+ // On screen, and a step on either side: a week in Day and Week, a month's grid in Month.
+ const need = view === "month"
+ ? { from: seconds(monthDays(addDays(month[0], -1))[0]), to: seconds(addDays(monthDays(addDays(month[41], 1))[41], 1)) }
+ : { from: seconds(addDays(week[0], -7)), to: seconds(addDays(week[6], 8)) };
+ const h = heldRange.current;
+ if (h && !h.year && h.from <= need.from && h.to >= need.to) return h;
+ return (heldRange.current = {
+ from: Math.min(need.from, seconds(addDays(month[0] < week[0] ? month[0] : week[0], -35))),
+ to: Math.max(need.to, seconds(addDays(month[41] > week[6] ? month[41] : week[6], 36))),
+ year: false,
+ });
}, [view, selected, week, month]);
- // The same bounds are the same read: stepping a day inside them asks for nothing again.
- const rangeKey = `${rawRange.from}-${rawRange.to}`;
- // eslint-disable-next-line react-hooks/exhaustive-deps
- const range = useMemo(() => rawRange, [rangeKey]);
const { hold, over } = usePending<CalendarEvent>();
+ // Reads in the order they were asked: one answered after a later one — a month stepped
+ // past, a slow read under a quick one — is let go, never drawn over what is newer.
+ const asked = useRef(0);
+ const shownRead = useRef(0);
const read = useCallback(async () => {
+ const turn = ++asked.current;
const [found, cals, reminders, lists, feeds] = await Promise.all([
api.calendarEvents(range.from, range.to),
api.calendarList(),
@@ -632,6 +647,8 @@ export function CalendarView() {
api.reminderLists().catch(() => []),
calendarFeedsApi.list().catch(() => [] as CalendarSubscription[]),
]);
+ if (turn < shownRead.current) return;
+ shownRead.current = turn;
// What reads the same as before is kept as it was, so a read that found nothing new —
// after every save, every sync, every month stepped into — draws nothing again.
setSubs((was) => same(was, Array.isArray(feeds) ? feeds : []));
@@ -667,10 +684,14 @@ export function CalendarView() {
// 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.
+ // What Month fetches is the month on screen: the months either side are read only from
+ // what is here, and fetched when they are looked at.
const fetched = useRef(new Set<string>());
+ const fetchFrom = view === "month" ? seconds(month[0]) : range.from;
+ const fetchTo = view === "month" ? seconds(addDays(month[41], 1)) : range.to;
useEffect(() => {
- const from = toLocalInput(range.from, true);
- const to = toLocalInput(range.to - 1, true);
+ const from = toLocalInput(fetchFrom, true);
+ const to = toLocalInput(fetchTo - 1, true);
const key = `${from}:${to}`;
if (fetched.current.has(key)) return undefined;
let cancelled = false;
@@ -688,7 +709,7 @@ export function CalendarView() {
cancelled = true;
window.clearTimeout(timer);
};
- }, [range, read]);
+ }, [fetchFrom, fetchTo, read]);
const byGuid = useMemo(() => new Map(calendars.map((c) => [c.guid, c])), [calendars]);
const shown = useMemo(