@moltenship/calendar 1.0.0-rc.2 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/README.md +27 -6
  2. package/dist/index.d.mts +3 -3
  3. package/dist/index.mjs +2 -2
  4. package/docs/accessibility.md +305 -0
  5. package/docs/agents/changes.md +449 -0
  6. package/docs/agents/coding-agents.md +116 -0
  7. package/docs/agents/connect.md +444 -0
  8. package/docs/agents/deleting.md +296 -0
  9. package/docs/agents/reference.md +511 -0
  10. package/docs/agents/server.md +317 -0
  11. package/docs/agents/webmcp.md +153 -0
  12. package/docs/agents.md +355 -0
  13. package/docs/annotations.md +198 -0
  14. package/docs/api/changes.md +264 -0
  15. package/docs/api/components.md +245 -0
  16. package/docs/api/dnd-kit.md +265 -0
  17. package/docs/api/events.md +153 -0
  18. package/docs/api/primitives.md +218 -0
  19. package/docs/api/store.md +92 -0
  20. package/docs/api.md +57 -0
  21. package/docs/availability.md +576 -0
  22. package/docs/comparison.md +278 -0
  23. package/docs/concepts/anatomy.md +73 -0
  24. package/docs/concepts/events.md +163 -0
  25. package/docs/concepts/how-it-works.md +112 -0
  26. package/docs/concepts/state.md +244 -0
  27. package/docs/concepts/time.md +168 -0
  28. package/docs/customization.md +271 -0
  29. package/docs/frameworks.md +116 -0
  30. package/docs/guides/dnd-kit.md +333 -0
  31. package/docs/guides/google-calendar-sync.md +1246 -0
  32. package/docs/guides/google-calendar.md +367 -0
  33. package/docs/guides/motion.md +414 -0
  34. package/docs/guides/nextjs-app-router.md +630 -0
  35. package/docs/guides/nextjs.md +149 -0
  36. package/docs/guides/performance.md +103 -0
  37. package/docs/guides/tanstack-query.md +485 -0
  38. package/docs/ics/feed.md +484 -0
  39. package/docs/ics/import.md +183 -0
  40. package/docs/ics/reference.md +482 -0
  41. package/docs/ics.md +142 -0
  42. package/docs/index.md +149 -0
  43. package/docs/installation.md +209 -0
  44. package/docs/interactions.md +441 -0
  45. package/docs/llms.txt +99 -0
  46. package/docs/migrating-to-2.md +497 -0
  47. package/docs/quick-start.md +163 -0
  48. package/docs/recurrence/calendar.md +598 -0
  49. package/docs/recurrence/model.md +128 -0
  50. package/docs/recurrence/reference.md +547 -0
  51. package/docs/recurrence.md +122 -0
  52. package/docs/stylex.md +290 -0
  53. package/docs/temporal/daylight-saving-time.md +172 -0
  54. package/docs/temporal/month-grid.md +119 -0
  55. package/docs/temporal/reference.md +167 -0
  56. package/docs/temporal.md +105 -0
  57. package/docs/testing.md +600 -0
  58. package/docs/theme-builder.md +82 -0
  59. package/docs/theming.md +275 -0
  60. package/docs/undo-redo.md +347 -0
  61. package/docs/views/agenda.md +222 -0
  62. package/docs/views/custom-views.md +195 -0
  63. package/docs/views/month.md +110 -0
  64. package/docs/views/resource-columns.md +265 -0
  65. package/docs/views/resource-timeline.md +226 -0
  66. package/docs/views/scrolling.md +193 -0
  67. package/docs/views/week-and-day.md +258 -0
  68. package/docs/views/year.md +138 -0
  69. package/docs/views.md +69 -0
  70. package/package.json +42 -14
  71. package/skills/moltenship-time/SKILL.md +77 -0
  72. package/skills/moltenship-time/references/agent-ready.md +272 -0
  73. package/skills/moltenship-time/references/changes.md +188 -0
  74. package/skills/moltenship-time/references/compose.md +175 -0
  75. package/skills/moltenship-time/references/mistakes.md +100 -0
  76. package/skills/moltenship-time/references/solid.md +213 -0
  77. package/skills/moltenship-time/references/state.md +129 -0
  78. package/skills/moltenship-time/references/testing.md +176 -0
@@ -0,0 +1,485 @@
1
+ # Load events with TanStack Query
2
+
3
+ Fetch the dates the calendar shows with useQuery, and save its changes with useMutation and optimistic updates.
4
+
5
+ Source: https://time.molten.sh/docs/react/guides/tanstack-query
6
+
7
+ > Live example: see it at https://time.molten.sh/docs/react/guides/tanstack-query
8
+
9
+ These events come from a pretend server that takes 0.7 seconds to answer. Go to another week or
10
+ month and the calendar keeps its events on screen while the next ones load. Drag an event and it
11
+ moves at once, then saves. Tick "Make requests fail" to see the error and the rollback.
12
+
13
+ Time never fetches or saves events. It tells you which dates it shows through
14
+ `onVisibleRangeChange`, and proposes changes through `onEventChange`. This guide connects both to
15
+ [TanStack Query](https://tanstack.com/query): one query per window of months, and a mutation that
16
+ shows a change before it's saved and undoes it if the save fails.
17
+
18
+ ## Install
19
+
20
+ **pnpm**
21
+
22
+ ```bash
23
+ pnpm add @tanstack/react-query
24
+ ```
25
+
26
+ **npm**
27
+
28
+ ```bash
29
+ npm install @tanstack/react-query
30
+ ```
31
+
32
+ **yarn**
33
+
34
+ ```bash
35
+ yarn add @tanstack/react-query
36
+ ```
37
+
38
+ **bun**
39
+
40
+ ```bash
41
+ bun add @tanstack/react-query
42
+ ```
43
+
44
+ Put a `QueryClientProvider` above the calendar, as TanStack Query's
45
+ [quick start](https://tanstack.com/query/latest/docs/framework/react/quick-start) does.
46
+
47
+ ## The API
48
+
49
+ The example talks to an API with four requests. Its events are JSON, with ISO strings for times:
50
+
51
+ ```ts title="query-api.ts"
52
+ import type { CalendarEventColor } from "@/components/calendar/event-colors";
53
+
54
+ /** An event as the API sends it: JSON, with ISO strings for its times. */
55
+ export interface ApiEvent {
56
+ readonly id: string;
57
+ readonly title: string;
58
+ readonly color: CalendarEventColor;
59
+ /** Dates such as `2026-10-12` when `allDay`, otherwise instants such as `2026-10-12T07:30:00Z`. */
60
+ readonly start: string;
61
+ /** Exclusive, as the calendar's ends are. */
62
+ readonly end: string;
63
+ readonly allDay: boolean;
64
+ /** Goes up with every saved change. */
65
+ readonly version: number;
66
+ }
67
+
68
+ /** The dates one query loads, from `start` up to `end`, in a time zone. */
69
+ export interface EventsWindow {
70
+ readonly start: string;
71
+ readonly end: string;
72
+ readonly timeZone: string;
73
+ }
74
+
75
+ export interface EventsApi {
76
+ /** The events that overlap the window, also those that start before it or end after it. */
77
+ listEvents(dates: EventsWindow, signal?: AbortSignal): Promise<ApiEvent[]>;
78
+ createEvent(event: ApiEvent): Promise<ApiEvent>;
79
+ updateEvent(event: ApiEvent): Promise<ApiEvent>;
80
+ deleteEvent(id: string): Promise<void>;
81
+ }
82
+ ```
83
+
84
+ `listEvents` returns the events that overlap the dates, not only those that start in them, so a
85
+ trip that started on Friday still shows on Monday. A timed event overlaps when it starts before the
86
+ window's last midnight and ends after its first, in the window's time zone. An all-day event is
87
+ compared by its dates:
88
+
89
+ ```ts title="query-api.ts"
90
+ /**
91
+ * Whether an event overlaps the window. Timed events are compared as instants, between the
92
+ * window's first and last midnight in its time zone; all-day events as dates.
93
+ */
94
+ export function overlapsWindow(event: ApiEvent, { end, start, timeZone }: EventsWindow): boolean {
95
+ if (event.allDay) {
96
+ return (
97
+ Temporal.PlainDate.compare(event.start, end) < 0 &&
98
+ Temporal.PlainDate.compare(start, event.end) < 0
99
+ );
100
+ }
101
+ const from = Temporal.PlainDate.from(start).toZonedDateTime(timeZone).toInstant();
102
+ const to = Temporal.PlainDate.from(end).toZonedDateTime(timeZone).toInstant();
103
+ return (
104
+ Temporal.Instant.compare(event.start, to) < 0 && Temporal.Instant.compare(from, event.end) < 0
105
+ );
106
+ }
107
+ ```
108
+
109
+ The preview's server is `createFakeEventsApi`, in the same file. It keeps events in memory and
110
+ answers after a delay. In your app, these four functions call your server.
111
+
112
+ ## Read the records as they are
113
+
114
+ The cache keeps events as the API sends them, and the event adapter reads their times:
115
+
116
+ ```tsx title="query-calendar.tsx"
117
+ import { createCalendar, defineEventAdapter, weekRange } from "@moltenship/calendar";
118
+ import { keepPreviousData, usePrefetchQuery, useQuery } from "@tanstack/react-query";
119
+ import { useMemo, useState } from "react";
120
+
121
+ import { calendarAnnouncements } from "@/components/calendar/announcements";
122
+ import { CalendarToolbar } from "@/components/calendar/calendar-toolbar";
123
+ import { createMonthView } from "@/components/calendar/month-view/month-view";
124
+ import { createDayView, createWeekView } from "@/components/calendar/time-grid-view/time-grid-view";
125
+ import { ViewSwitcher } from "@/components/calendar/view-switcher";
126
+ import { Button } from "@/components/ui/button";
127
+
128
+ import type { ApiEvent, EventsApi } from "./query-api";
129
+ import { eventsQuery, eventsWindow, shiftWindow, useSaveEvent, writeOf } from "./query-events";
130
+
131
+ /** Reads the API's records as they are, so the cache can keep plain JSON. */
132
+ export const eventAdapter = defineEventAdapter<ApiEvent>()({
133
+ getId: (event) => event.id,
134
+ getTitle: (event) => event.title,
135
+ getInterval: (event) =>
136
+ event.allDay
137
+ ? {
138
+ kind: "all-day",
139
+ start: Temporal.PlainDate.from(event.start),
140
+ end: Temporal.PlainDate.from(event.end),
141
+ }
142
+ : {
143
+ kind: "timed",
144
+ start: Temporal.Instant.from(event.start),
145
+ end: Temporal.Instant.from(event.end),
146
+ },
147
+ getResourceIds: () => [],
148
+ });
149
+
150
+ const getEventColor = (event: ApiEvent) => event.color;
151
+
152
+ export const Calendar = createCalendar<ApiEvent>()({
153
+ eventAdapter,
154
+ views: [
155
+ createWeekView<ApiEvent>({ dayView: "day", getEventColor }),
156
+ createDayView<ApiEvent>({ getEventColor }),
157
+ createMonthView<ApiEvent>({ getEventColor }),
158
+ ],
159
+ });
160
+ ```
161
+
162
+ - **Plain JSON in the cache.** When a reload brings nothing new, TanStack Query's structural
163
+ sharing keeps the same array, so the calendar has nothing to redo. JSON also survives
164
+ dehydration, for [server rendering](#server-rendering).
165
+ - **No `getRevision`.** A change shown before it's saved keeps the record's old `version`. The
166
+ calendar skips a record whose revision it has seen, so it would keep the old times.
167
+
168
+ ## Key the query by the dates
169
+
170
+ `onVisibleRangeChange` reports the dates the view shows, `range`, and the dates to have events
171
+ for, `loadRange`. Keep `loadRange` in state, and turn it into the window a query loads:
172
+
173
+ ```ts title="query-events.ts"
174
+ /** Whole months from one date's month to another's. */
175
+ const monthsBetween = (from: Temporal.PlainDate, to: Temporal.PlainDate) =>
176
+ from.with({ day: 1 }).until(to.with({ day: 1 }), { largestUnit: "months" }).months;
177
+
178
+ /**
179
+ * The window to load for the calendar's `loadRange`: the month holding its middle day, with whole
180
+ * months either side, at least one and as many as the load range reaches.
181
+ */
182
+ export function eventsWindow(loadRange: PlainDateInterval, timeZone: string): EventsWindow {
183
+ const { end, start } = loadRange;
184
+ const middle = start.add({ days: Math.floor(start.until(end).days / 2) }).with({ day: 1 });
185
+ const months = Math.max(
186
+ 1,
187
+ monthsBetween(start, middle),
188
+ monthsBetween(middle, end.subtract({ days: 1 })),
189
+ );
190
+ return {
191
+ end: middle.add({ months: months + 1 }).toString(),
192
+ start: middle.subtract({ months }).toString(),
193
+ timeZone,
194
+ };
195
+ }
196
+
197
+ /** The window `months` later, or earlier when negative. */
198
+ export function shiftWindow({ end, start, timeZone }: EventsWindow, months: number): EventsWindow {
199
+ return {
200
+ end: Temporal.PlainDate.from(end).add({ months }).toString(),
201
+ start: Temporal.PlainDate.from(start).add({ months }).toString(),
202
+ timeZone,
203
+ };
204
+ }
205
+ ```
206
+
207
+ ```ts title="query-events.ts"
208
+ /** The start of every events query's key, so changes can find them all. */
209
+ export const eventsKey = ["events"] as const;
210
+
211
+ export function eventsQuery(api: EventsApi, dates: EventsWindow) {
212
+ return queryOptions({
213
+ queryKey: [...eventsKey, dates],
214
+ queryFn: ({ signal }) => api.listEvents(dates, signal),
215
+ // Going back to dates seen in the last minute shows them without asking again.
216
+ staleTime: 60_000,
217
+ });
218
+ }
219
+ ```
220
+
221
+ - **Whole months.** The calendar's dates change with each step. A key made of them would load
222
+ again on every step, and cache each week apart. The window is the month that holds the middle of
223
+ the load range, with a month on either side, so the weeks of a month share one query, and so do
224
+ a month view's six weeks.
225
+ - **One month on.** When the next week or month moves the middle into the next month, the window
226
+ moves by exactly one month, so `shiftWindow` names the windows to
227
+ [prefetch](#prefetch-the-next-window).
228
+ - **Long load ranges.** A [scrolling view](../views/scrolling.md) loads a page on either side of
229
+ what it shows. The window grows to hold its load range, such as a scrolling month's eighteen weeks.
230
+ - **ISO strings and the time zone.** The key is JSON, which TanStack Query hashes. The same dates
231
+ are other instants in another time zone, so the zone is part of the key.
232
+
233
+ ## Show what's loading
234
+
235
+ ```tsx title="query-calendar.tsx"
236
+ const weekRules = { firstDay: 1, minimalDays: 4, weekend: [6, 7] } as const;
237
+ const noEvents: readonly ApiEvent[] = [];
238
+
239
+ export interface EventsCalendarProps {
240
+ readonly api: EventsApi;
241
+ readonly timeZone: string;
242
+ }
243
+
244
+ export function EventsCalendar({ api, timeZone }: EventsCalendarProps) {
245
+ const [today] = useState(() => Temporal.Now.plainDateISO(timeZone));
246
+ // The calendar reports its dates after its first render, so start from the week it opens on.
247
+ const [loadRange, setLoadRange] = useState(() =>
248
+ weekRange(today, { weekStartsOn: weekRules.firstDay }),
249
+ );
250
+ const dates = useMemo(() => eventsWindow(loadRange, timeZone), [loadRange, timeZone]);
251
+
252
+ // Until the next window loads, keep the last one's events on screen.
253
+ const events = useQuery({ ...eventsQuery(api, dates), placeholderData: keepPreviousData });
254
+ // Load the windows either side too, so the next or previous month shows at once.
255
+ usePrefetchQuery(eventsQuery(api, shiftWindow(dates, -1)));
256
+ usePrefetchQuery(eventsQuery(api, shiftWindow(dates, 1)));
257
+ const saveEvent = useSaveEvent(api);
258
+
259
+ return (
260
+ <Calendar.Root
261
+ events={events.data ?? noEvents}
262
+ onVisibleRangeChange={(range) => setLoadRange(range.loadRange)}
263
+ // The change shows as pending until the save settles, and rolls back if it fails.
264
+ onEventChange={async (change) => {
265
+ await saveEvent.mutateAsync(writeOf(change));
266
+ }}
267
+ defaultAnchorDate={today}
268
+ timeZone={timeZone}
269
+ locale="en-US"
270
+ weekRules={weekRules}
271
+ >
272
+ <Calendar.Frame className="flex h-full flex-col">
273
+ <CalendarToolbar calendar={Calendar} className="border-b">
274
+ <LoadingIndicator loading={events.isFetching} />
275
+ <CalendarViewSwitcher />
276
+ </CalendarToolbar>
277
+ {saveEvent.isError ? (
278
+ // No live role: the calendar's announcer already says the change was undone.
279
+ <div className="flex items-center gap-3 border-b px-4 py-2 text-sm">
280
+ Couldn't save the change, so it was undone.
281
+ <Button className="ms-auto" onClick={saveEvent.reset} size="sm" variant="outline">
282
+ Dismiss
283
+ </Button>
284
+ </div>
285
+ ) : events.isError ? (
286
+ <div className="flex items-center gap-3 border-b px-4 py-2 text-sm" role="alert">
287
+ Couldn't load events.
288
+ <Button className="ms-auto" onClick={() => void events.refetch()} size="sm">
289
+ Try again
290
+ </Button>
291
+ </div>
292
+ ) : null}
293
+ <Calendar.Viewport aria-busy={events.isFetching} className="min-h-0 flex-1">
294
+ <Calendar.ActiveView />
295
+ </Calendar.Viewport>
296
+ <Calendar.Announcer messages={calendarAnnouncements} />
297
+ </Calendar.Frame>
298
+ </Calendar.Root>
299
+ );
300
+ }
301
+ ```
302
+
303
+ `LoadingIndicator` and `CalendarViewSwitcher` are small components in the same file: a spinner, and
304
+ the registry's view switcher.
305
+
306
+ - **The first render.** The calendar reports its dates after it renders, and never on the server,
307
+ so the state starts from the week it opens on, from `weekRange`. The window rounds both to the
308
+ same months, so the first load is the one the calendar asks for. If it opens on a month view,
309
+ start from its grid instead.
310
+ - **`placeholderData: keepPreviousData`.** While the next window loads, `data` keeps the last
311
+ window's events, and the dates that both windows hold keep theirs. Without it, the grid would
312
+ empty for every load.
313
+ - **Loading.** `isFetching` turns on the spinner in the toolbar, and `aria-busy` on the viewport,
314
+ for every load of the window on screen, also a reload after a save.
315
+ - **Errors.** TanStack Query retries a failed load three times by default before `isError` shows
316
+ the message; the preview retries once. "Try again" calls `refetch`. A window that fails to load
317
+ has no events to keep, so the grid behind the message is empty. A failed save shows its own
318
+ message first, since it answers what the user just did, and the calendar announces it.
319
+ - **Strict Mode.** `onVisibleRangeChange` reports each change once, also when Strict Mode runs
320
+ effects twice. Setting the same range again would do nothing anyway.
321
+
322
+ ### Prefetch the next window
323
+
324
+ `usePrefetchQuery` starts loading the windows a month before and after the one on screen, while
325
+ the calendar renders. It skips windows the cache already has, so it doesn't load them on every
326
+ render. Stepping into the next month then shows its events at once.
327
+
328
+ ## Save changes
329
+
330
+ The calendar proposes changes and your app commits them. `onEventChange` above hands each change
331
+ to a mutation and waits for it. Until the save settles, the change shows as pending; if it fails,
332
+ the change rolls back. A change becomes a write: the event's record before and after it:
333
+
334
+ ```ts title="query-events.ts"
335
+ export type ApiEventChange = CalendarEventChange<ApiEvent, string, never>;
336
+
337
+ /** What a change writes: the event's record before and after it, or `null` where there's none. */
338
+ export interface EventWrite {
339
+ readonly id: string;
340
+ readonly before: ApiEvent | null;
341
+ readonly after: ApiEvent | null;
342
+ }
343
+
344
+ /** `event` at the placement the calendar proposes. */
345
+ function placed(
346
+ event: Omit<ApiEvent, "allDay" | "end" | "start">,
347
+ placement: CalendarEventPlacement<never>,
348
+ ): ApiEvent {
349
+ if (placement.kind === "floating") throw new Error("Events need a time zone.");
350
+ return {
351
+ ...event,
352
+ allDay: placement.kind === "all-day",
353
+ end: placement.end.toString(),
354
+ start: placement.start.toString(),
355
+ };
356
+ }
357
+
358
+ export function writeOf(change: ApiEventChange): EventWrite {
359
+ switch (change.cause) {
360
+ case "create": {
361
+ // Picked here, so the event shown while it saves and the saved one share it.
362
+ const id = crypto.randomUUID();
363
+ const event = { color: "blue", id, title: "New event", version: 0 } as const;
364
+ return { after: placed(event, change.proposed), before: null, id };
365
+ }
366
+ case "delete":
367
+ return { after: null, before: change.event, id: change.eventId };
368
+ default:
369
+ return {
370
+ after: placed(change.event, change.proposed),
371
+ before: change.event,
372
+ id: change.eventId,
373
+ };
374
+ }
375
+ }
376
+ ```
377
+
378
+ A new event gets its ID here, so the event shown while it saves and the saved one are the same
379
+ event, with no temporary ID to swap. The calendar keeps no pending copy of a new event: it shows
380
+ once it's in the cache. The record goes into every cached window it overlaps:
381
+
382
+ ```ts title="query-events.ts"
383
+ /**
384
+ * Puts `event` in every cached window it overlaps, in place of the event with this `id`, and takes
385
+ * that event out of the others. `null` takes it out everywhere.
386
+ */
387
+ export function putEvent(queryClient: QueryClient, id: string, event: ApiEvent | null): void {
388
+ const cached = queryClient.getQueriesData<ApiEvent[]>({ queryKey: eventsKey });
389
+ for (const [queryKey, events] of cached) {
390
+ if (events === undefined) continue;
391
+ // Keys come from `eventsQuery`: the window follows `eventsKey`.
392
+ const dates = queryKey[eventsKey.length] as EventsWindow;
393
+ const index = events.findIndex((candidate) => candidate.id === id);
394
+ let next = events;
395
+ if (event !== null && overlapsWindow(event, dates)) {
396
+ next = index === -1 ? [...events, event] : events.with(index, event);
397
+ } else if (index !== -1) {
398
+ next = events.toSpliced(index, 1);
399
+ }
400
+ if (next !== events) queryClient.setQueryData(queryKey, next);
401
+ }
402
+ }
403
+ ```
404
+
405
+ And the mutation updates the cache before the save, and puts it back if the save fails:
406
+
407
+ ```ts title="query-events.ts"
408
+ /**
409
+ * Reloads the events after the last save. Loads still on their way read before it, so they're
410
+ * cancelled first, and windows off screen that never loaded go, to be prefetched again.
411
+ */
412
+ async function reloadEvents(queryClient: QueryClient): Promise<void> {
413
+ await queryClient.cancelQueries({ queryKey: eventsKey });
414
+ queryClient.removeQueries({
415
+ queryKey: eventsKey,
416
+ predicate: (query) => query.state.data === undefined,
417
+ type: "inactive",
418
+ });
419
+ await queryClient.invalidateQueries({ queryKey: eventsKey });
420
+ }
421
+
422
+ export function useSaveEvent(api: EventsApi) {
423
+ const queryClient = useQueryClient();
424
+
425
+ return useMutation({
426
+ mutationKey: eventsKey,
427
+ // Saves reach the server one at a time, in the order they were made. Each shows at once.
428
+ scope: { id: "events" },
429
+ mutationFn: async ({ after, before, id }: EventWrite) => {
430
+ if (after === null) await api.deleteEvent(id);
431
+ else if (before === null) await api.createEvent(after);
432
+ else await api.updateEvent(after);
433
+ },
434
+ onMutate: async ({ after, id }) => {
435
+ // A reload on its way could bring back what it read before the change. Loads with nothing
436
+ // cached yet carry on, and the reload after the save replaces them.
437
+ await queryClient.cancelQueries({
438
+ queryKey: eventsKey,
439
+ predicate: (query) => query.state.data !== undefined,
440
+ });
441
+ putEvent(queryClient, id, after);
442
+ },
443
+ // Put the event back as it was, in every window. Other changes that are saving stay.
444
+ onError: (_error, { before, id }) => putEvent(queryClient, id, before),
445
+ onSettled: (_data, error) => {
446
+ // Reload once the last save settles, so a reload between two saves can't undo the second.
447
+ if (queryClient.isMutating({ mutationKey: eventsKey }) !== 1) return;
448
+ const reload = reloadEvents(queryClient);
449
+ // A saved change stays pending until the reload shows it; a failed one rolls back now.
450
+ return error === null ? reload : undefined;
451
+ },
452
+ });
453
+ }
454
+ ```
455
+
456
+ 1. **`scope`** sends the saves one at a time, in the order they were made, so a server never
457
+ applies an older move after a newer one. `onMutate` still runs at once for each.
458
+ 2. **`onMutate`** cancels reloads on their way, which could bring back what they read before the
459
+ change, and puts the new record in the cache. A move from October to December leaves the
460
+ windows that held October and shows in those that hold December, before it's saved. Loads of
461
+ windows with nothing cached yet carry on, so prefetches aren't lost.
462
+ 3. **`onError`** puts the old record back the same way. It writes only this event, rather than a
463
+ copy of the whole cache from before the change, so another change that's still saving stays.
464
+ 4. **`onSettled`** reloads the events once the last save has settled. A reload between two saves
465
+ would show the first without the second. Loads still on their way read before the save, so
466
+ `reloadEvents` cancels them, drops windows off screen that never loaded (the ones next to the
467
+ window on screen are prefetched again), and then marks every events query stale, which reloads
468
+ the ones on screen. After a save,
469
+ returning the reload's promise keeps the change pending until the reload shows it. After a
470
+ failure, it returns nothing, so the change rolls back at once.
471
+
472
+ If two changes to one event both fail, the second puts back the record the first one left, which
473
+ the server never had. The next load that succeeds shows what the server has.
474
+
475
+ `mutateAsync` rejects when the save fails, after `onError` has put the old record back, so
476
+ `onEventChange` rejects too and the calendar rolls back the change.
477
+
478
+ ## Server rendering
479
+
480
+ The [Next.js guide](./nextjs.md) explains how to render the calendar on the server. With
481
+ TanStack Query, prefetch the first window on the server under the same key, and pass the cache to
482
+ the browser with TanStack Query's
483
+ [`HydrationBoundary`](https://tanstack.com/query/latest/docs/framework/react/guides/advanced-ssr).
484
+ The cache holds JSON, not Temporal objects, so it serializes as it is. Start from the same dates on
485
+ both sides, so the keys match.