@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,1246 @@
1
+ # Sync with Google Calendar
2
+
3
+ Load a Google calendar from the dates on screen, keep it current with sync tokens, and write changes back with etags.
4
+
5
+ Source: https://time.molten.sh/docs/react/guides/google-calendar-sync
6
+
7
+ > Live example: see it at https://time.molten.sh/docs/react/guides/google-calendar-sync
8
+
9
+ This calendar syncs with a Google calendar. There are no Google credentials on this page, so it
10
+ talks to a fake Calendar API that runs in your browser. It answers with API v3's JSON, pages, sync
11
+ tokens, etags and errors. Drag an event, or delete one, and it's written back. The buttons change
12
+ events as someone else would in Google, expire the sync token and rate-limit requests. The log
13
+ shows each request.
14
+
15
+ This guide builds it. The code is what a real app runs. The demo hands it a fake `fetch` instead
16
+ of your route, and a shorter retry delay.
17
+
18
+ | File | What it does |
19
+ | -------------------------------------------- | -------------------------------------------------------------------------------------------------- |
20
+ | `lib/google-calendar-api.ts` | A small client for the API's events, over `fetch` |
21
+ | `app/api/google-calendar/[...path]/route.ts` | Sends the browser's requests to Google with the user's token |
22
+ | `lib/google-calendar.ts` | Maps Google events to calendar events, from [Google Calendar events](./google-calendar.md) |
23
+ | `lib/google-calendar-sync.ts` | The events loaded so far: loads, syncs and writes |
24
+ | `components/google-calendar-view.tsx` | The calendar |
25
+
26
+ None of it is in the calendar's packages. They don't depend on Google, and this guide doesn't add
27
+ a Google SDK either.
28
+
29
+ ## Sign-in is up to you
30
+
31
+ The Calendar API needs an OAuth 2.0 access token for the user. Ask for the
32
+ `https://www.googleapis.com/auth/calendar.events` scope to read and write events, or
33
+ `calendar.events.readonly` to only read them. Your auth library, such as Auth.js or Better Auth,
34
+ runs the sign-in on your server and keeps the tokens there. Ask Google for offline access, so you
35
+ get a refresh token, and refresh the access token when it expires, as your library's docs show.
36
+ This guide starts once you have one.
37
+
38
+ Keep the tokens on the server. The browser calls your own route, and the route adds the token.
39
+
40
+ ## Call the API
41
+
42
+ The client covers the calls the calendar needs: list events, read one occurrence of a series, and
43
+ insert, patch, replace and delete:
44
+
45
+ ```ts title="lib/google-calendar-api.ts"
46
+ // lib/google-calendar-api.ts
47
+ import type { GoogleEvent } from "./google-calendar";
48
+
49
+ export interface GoogleCalendarApiOptions {
50
+ /**
51
+ * `https://www.googleapis.com/calendar/v3` on your server, with `headers` adding the user's
52
+ * access token. In the browser, your own route that adds it.
53
+ */
54
+ readonly baseUrl: string;
55
+ /** "primary", or a calendar's ID from `calendarList.list`. */
56
+ readonly calendarId?: string;
57
+ readonly fetch?: typeof fetch;
58
+ /** Headers for every request, such as `Authorization: Bearer <access token>`. */
59
+ readonly headers?: () => HeadersInit | Promise<HeadersInit>;
60
+ /** How often to retry a rate-limited or failed request before giving up. */
61
+ readonly retries?: number;
62
+ /** How long to wait before retry `attempt`, from 0, when Google doesn't say. */
63
+ readonly retryDelay?: (attempt: number) => number;
64
+ }
65
+
66
+ /** A request Google refused: its status, and the reason its error body gives. */
67
+ export class GoogleApiError extends Error {
68
+ override readonly name = "GoogleApiError";
69
+ readonly reason: string | undefined;
70
+ readonly status: number;
71
+
72
+ constructor(status: number, reason: string | undefined, message: string) {
73
+ super(message);
74
+ this.reason = reason;
75
+ this.status = status;
76
+ }
77
+ }
78
+
79
+ /**
80
+ * The events that end after `timeMin` and start before `timeMax`, if given, or the changes since a
81
+ * sync token. Google doesn't take both at once.
82
+ */
83
+ export type GoogleEventsQuery =
84
+ | { readonly timeMax?: Temporal.Instant; readonly timeMin: Temporal.Instant }
85
+ | { readonly syncToken: string };
86
+
87
+ export interface GoogleEventTimeWrite {
88
+ readonly date?: string | null;
89
+ readonly dateTime?: string | null;
90
+ readonly timeZone?: string | null;
91
+ }
92
+
93
+ /**
94
+ * What a write sends: these fields, and any other of the Event resource. In a patch, `null` clears a
95
+ * field, as a move between all-day and timed needs.
96
+ */
97
+ export interface GoogleEventWrite {
98
+ readonly colorId?: string;
99
+ readonly end?: GoogleEventTimeWrite;
100
+ /** Insert only: lowercase a–v and digits, 5 to 1024 of them, so you can pick it up front. */
101
+ readonly id?: string;
102
+ readonly originalStartTime?: GoogleEventTimeWrite;
103
+ readonly recurrence?: readonly string[];
104
+ readonly recurringEventId?: string;
105
+ readonly start?: GoogleEventTimeWrite;
106
+ readonly status?: "confirmed" | "tentative";
107
+ readonly summary?: string;
108
+ readonly transparency?: "opaque" | "transparent";
109
+ }
110
+
111
+ interface GoogleEventsPage {
112
+ readonly items?: readonly GoogleEvent[];
113
+ readonly nextPageToken?: string;
114
+ readonly nextSyncToken?: string;
115
+ }
116
+
117
+ const rateLimits = new Set(["rateLimitExceeded", "userRateLimitExceeded"]);
118
+
119
+ /** 1, 2, 4… seconds, up to 32, plus up to a second at random, so clients don't retry in step. */
120
+ const backoff = (attempt: number) => Math.min(2 ** attempt, 32) * 1000 + Math.random() * 1000;
121
+
122
+ /** The Calendar API's events, over `fetch`. */
123
+ export function createGoogleCalendarApi({
124
+ baseUrl,
125
+ calendarId = "primary",
126
+ fetch: send = fetch,
127
+ headers,
128
+ retries = 5,
129
+ retryDelay = backoff,
130
+ }: GoogleCalendarApiOptions) {
131
+ const events = `${baseUrl}/calendars/${encodeURIComponent(calendarId)}/events`;
132
+
133
+ async function request<T>(
134
+ method: "DELETE" | "GET" | "PATCH" | "POST" | "PUT",
135
+ url: string,
136
+ { body, etag }: { readonly body?: GoogleEventWrite; readonly etag?: string | undefined } = {},
137
+ ): Promise<T> {
138
+ const sent = new Headers(await headers?.());
139
+ if (body !== undefined) sent.set("Content-Type", "application/json");
140
+ // Google writes only over the version you read, and answers 412 if it has changed since.
141
+ if (etag !== undefined) sent.set("If-Match", etag);
142
+
143
+ for (let attempt = 0; ; attempt++) {
144
+ const response = await send(url, {
145
+ body: body === undefined ? null : JSON.stringify(body),
146
+ headers: sent,
147
+ method,
148
+ });
149
+ if (response.ok) return (response.status === 204 ? undefined : await response.json()) as T;
150
+
151
+ const error = await errorOf(response);
152
+ const rateLimited =
153
+ error.status === 429 || (error.status === 403 && rateLimits.has(error.reason ?? ""));
154
+ if (attempt >= retries || !(rateLimited || error.status >= 500)) throw error;
155
+ const retryAfter = Number(response.headers.get("Retry-After"));
156
+ await sleep(retryAfter > 0 ? retryAfter * 1000 : retryDelay(attempt));
157
+ }
158
+ }
159
+
160
+ return {
161
+ /**
162
+ * Every page of `events.list`. Series come as their masters, with their changed and cancelled
163
+ * occurrences, since `singleEvents` stays off. The sync token is on the last page.
164
+ */
165
+ async list(query: GoogleEventsQuery) {
166
+ const items: GoogleEvent[] = [];
167
+ let pageToken: string | undefined;
168
+ for (;;) {
169
+ const params = new URLSearchParams(
170
+ "syncToken" in query
171
+ ? { syncToken: query.syncToken }
172
+ : { timeMin: query.timeMin.toString() },
173
+ );
174
+ if ("timeMax" in query && query.timeMax !== undefined) {
175
+ params.set("timeMax", query.timeMax.toString());
176
+ }
177
+ if (pageToken !== undefined) params.set("pageToken", pageToken);
178
+ const page = await request<GoogleEventsPage>("GET", `${events}?${params}`);
179
+ items.push(...(page.items ?? []));
180
+ pageToken = page.nextPageToken;
181
+ if (pageToken === undefined) return { items, nextSyncToken: page.nextSyncToken };
182
+ }
183
+ },
184
+
185
+ /**
186
+ * The occurrence a series' rule puts at `originalStart`, with its own ID and etag, cancelled
187
+ * or not.
188
+ */
189
+ async instance(seriesId: string, originalStart: string) {
190
+ const params = new URLSearchParams({ originalStart, showDeleted: "true" });
191
+ for (;;) {
192
+ const page = await request<GoogleEventsPage>(
193
+ "GET",
194
+ `${events}/${encodeURIComponent(seriesId)}/instances?${params}`,
195
+ );
196
+ const [instance] = page.items ?? [];
197
+ if (instance !== undefined) return instance;
198
+ // A page may be empty and still have more.
199
+ if (page.nextPageToken === undefined) break;
200
+ params.set("pageToken", page.nextPageToken);
201
+ }
202
+ throw new GoogleApiError(
203
+ 404,
204
+ "notFound",
205
+ `${seriesId} has no occurrence at ${originalStart}`,
206
+ );
207
+ },
208
+
209
+ insert: (event: GoogleEventWrite) => request<GoogleEvent>("POST", events, { body: event }),
210
+
211
+ patch: (id: string, fields: GoogleEventWrite, etag: string | undefined) =>
212
+ request<GoogleEvent>("PATCH", `${events}/${encodeURIComponent(id)}`, { body: fields, etag }),
213
+
214
+ remove: (id: string, etag: string | undefined) =>
215
+ request<void>("DELETE", `${events}/${encodeURIComponent(id)}`, { etag }),
216
+
217
+ /** Replaces the whole event: a field the write leaves out is cleared. */
218
+ update: (id: string, event: GoogleEventWrite, etag: string | undefined) =>
219
+ request<GoogleEvent>("PUT", `${events}/${encodeURIComponent(id)}`, { body: event, etag }),
220
+ };
221
+ }
222
+
223
+ export type GoogleCalendarApi = ReturnType<typeof createGoogleCalendarApi>;
224
+
225
+ /** Google's error body: `{ error: { code, message, errors: [{ reason }] } }`. */
226
+ async function errorOf(response: Response): Promise<GoogleApiError> {
227
+ const body = (await response.json().catch(() => undefined)) as
228
+ | { error?: { errors?: { reason?: string }[]; message?: string } }
229
+ | undefined;
230
+ return new GoogleApiError(
231
+ response.status,
232
+ body?.error?.errors?.[0]?.reason,
233
+ body?.error?.message ?? response.statusText,
234
+ );
235
+ }
236
+
237
+ const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
238
+ ```
239
+
240
+ - **Where it runs.** On your server, `baseUrl` is Google's and `headers` adds the access token. In
241
+ the browser, `baseUrl` is your route, below, and the cookie your auth library set signs the
242
+ request. The rest of the guide runs in the browser.
243
+ - **Pages.** `list` follows `nextPageToken` until the last page, which has `nextSyncToken`
244
+ instead. Google may send fewer events than `maxResults`, or none, and still have more.
245
+ - **Rate limits.** A 429, a 403 with `rateLimitExceeded` or `userRateLimitExceeded`, and a 5xx
246
+ are retried after 1, 2, 4… seconds, up to 32, plus a random part so that clients don't retry
247
+ together. A `Retry-After` header wins. Other errors throw a `GoogleApiError` at once: a 410 or a
248
+ 412 means something, and retrying won't change it.
249
+ - **`googleapis`.** On a Node.js server you can use Google's SDK instead.
250
+ `calendar.events.list({ calendarId, timeMin, timeMax, pageToken, syncToken })` takes the same
251
+ parameters. Wrap its calls so their errors become `GoogleApiError`s with the status and reason,
252
+ which the store reads. Plain `fetch` also runs in the browser and on edge runtimes, and adds no
253
+ dependency.
254
+
255
+ ### The route
256
+
257
+ A Route Handler sends the browser's requests on to Google with the user's access token:
258
+
259
+ ```ts title="app/api/google-calendar/[...path]/route.ts"
260
+ // app/api/google-calendar/[...path]/route.ts
261
+ import type { NextRequest } from "next/server";
262
+
263
+ /**
264
+ * The signed-in user's Google access token, from your auth library, with the
265
+ * `https://www.googleapis.com/auth/calendar.events` scope. `null` when they aren't signed in.
266
+ */
267
+ declare function googleAccessToken(request: NextRequest): Promise<string | null>;
268
+
269
+ const calendarApi = "https://www.googleapis.com/calendar/v3";
270
+
271
+ /** The query parameters the client sends. */
272
+ const parameters = new Set([
273
+ "originalStart",
274
+ "pageToken",
275
+ "showDeleted",
276
+ "syncToken",
277
+ "timeMax",
278
+ "timeMin",
279
+ ]);
280
+
281
+ /** Which calls go through: the methods each path takes, below `calendars/primary/events`. */
282
+ function allowed(method: string, event: readonly string[]): boolean {
283
+ const [id, instances, ...rest] = event;
284
+ if (id === undefined) return method === "GET" || method === "POST"; // list, insert
285
+ if (id === "." || id === ".." || rest.length > 0) return false;
286
+ if (instances !== undefined) return instances === "instances" && method === "GET";
287
+ return method === "PATCH" || method === "PUT" || method === "DELETE";
288
+ }
289
+
290
+ /**
291
+ * Sends the browser's Calendar API requests on to Google with the user's access token, which never
292
+ * reaches the browser. Only the calls the client makes, on the user's own events.
293
+ */
294
+ async function forward(request: NextRequest, { params }: { params: Promise<{ path: string[] }> }) {
295
+ // Only your own pages: browsers mark a request from another site.
296
+ if (request.headers.get("Sec-Fetch-Site") === "cross-site") {
297
+ return Response.json({ error: { code: 403, message: "Forbidden" } }, { status: 403 });
298
+ }
299
+ const { path } = await params;
300
+ const [calendars, calendarId, events, ...event] = path;
301
+ const { searchParams } = request.nextUrl;
302
+ if (
303
+ calendars !== "calendars" ||
304
+ calendarId !== "primary" ||
305
+ events !== "events" ||
306
+ !allowed(request.method, event) ||
307
+ [...searchParams.keys()].some((name) => !parameters.has(name))
308
+ ) {
309
+ return Response.json({ error: { code: 404, message: "Not found" } }, { status: 404 });
310
+ }
311
+
312
+ const token = await googleAccessToken(request);
313
+ if (token === null) {
314
+ return Response.json({ error: { code: 401, message: "Sign in again" } }, { status: 401 });
315
+ }
316
+
317
+ const url = new URL(`${calendarApi}/${path.map(encodeURIComponent).join("/")}`);
318
+ url.search = searchParams.toString();
319
+ const headers = new Headers({ Authorization: `Bearer ${token}` });
320
+ for (const name of ["Content-Type", "If-Match"]) {
321
+ const value = request.headers.get(name);
322
+ if (value !== null) headers.set(name, value);
323
+ }
324
+ const response = await fetch(url, {
325
+ body: request.method === "GET" || request.method === "DELETE" ? null : await request.text(),
326
+ headers,
327
+ method: request.method,
328
+ });
329
+
330
+ // The status, Retry-After and Google's error body pass through, so the browser handles 410, 412
331
+ // and 429 itself.
332
+ const passed = new Headers();
333
+ for (const name of ["Content-Type", "Retry-After"]) {
334
+ const value = response.headers.get(name);
335
+ if (value !== null) passed.set(name, value);
336
+ }
337
+ return new Response(response.body, { headers: passed, status: response.status });
338
+ }
339
+
340
+ export const GET = forward;
341
+ export const POST = forward;
342
+ export const PATCH = forward;
343
+ export const PUT = forward;
344
+ export const DELETE = forward;
345
+ ```
346
+
347
+ - **Only what the client calls.** It forwards the calls above, on the user's primary calendar's
348
+ events, with the query parameters the client sends. Anything else gets a 404, so the route can't
349
+ be used to reach the rest of their Google account.
350
+ - **Only your pages.** Browsers mark a request another site makes with
351
+ `Sec-Fetch-Site: cross-site`, and the route refuses it.
352
+ - **Errors pass through.** The status, `Retry-After` and Google's error body reach the browser, so
353
+ the client there handles 410, 412 and 429 as it would on the server.
354
+
355
+ ## Map the events
356
+
357
+ `fromGoogleEvents`, from [Google Calendar events](./google-calendar.md), maps the
358
+ [Event resource](https://developers.google.com/workspace/calendar/api/v3/reference/events) to the
359
+ calendar's events, and keeps the Google event as each one's `data`:
360
+
361
+ | Google | Calendar |
362
+ | ----------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
363
+ | `start.dateTime`, `end.dateTime` | A timed event. RFC 3339; without an offset, the time is read in `timeZone`. `start.timeZone` becomes `sourceTimeZone`, the clock a series repeats on. |
364
+ | `start.date`, `end.date` | An all-day event. Google's `end.date` is the day after the last, which is what the calendar's [exclusive end](../concepts/time.md#end-times-are-exclusive) means, so it maps as it is. |
365
+ | `status: "cancelled"` | Deleted. A cancelled occurrence of a series hides that occurrence. |
366
+ | `recurrence`, `recurringEventId`, `originalStartTime` | A series' master, and its changed and cancelled occurrences. See [Series](#series-masters-not-instances). |
367
+ | `colorId` | One of Google's 11 event colors. Read by `getEventColor`. |
368
+ | `transparency` | `"transparent"` is "Show as: Free". Read by `isBusy`. |
369
+
370
+ The calendar's adapters read color and busy from `data`:
371
+
372
+ ```tsx title="components/google-calendar-view.tsx"
373
+ "use client";
374
+
375
+ import {
376
+ createCalendar,
377
+ eventIdOf,
378
+ weekRange,
379
+ type CalendarEventChange,
380
+ type CalendarFocus,
381
+ type CalendarSelection,
382
+ type CalendarVisibleRange,
383
+ type EventId,
384
+ } from "@moltenship/calendar";
385
+ import {
386
+ createCanonicalRecurrenceAdapter,
387
+ createOccurrenceAdapter,
388
+ createOccurrenceExpander,
389
+ isRecurringChange,
390
+ recurrenceEditScopes,
391
+ resolveRecurrenceEdit,
392
+ type RecurrenceAdapters,
393
+ type RecurrenceEditScope,
394
+ type RecurrenceOccurrence,
395
+ } from "@moltenship/calendar-recurrence";
396
+ import { useEffect, useMemo, useState, useSyncExternalStore, type MouseEvent } from "react";
397
+
398
+ import { calendarAnnouncements } from "@/components/calendar/announcements";
399
+ import { CalendarToolbar } from "@/components/calendar/calendar-toolbar";
400
+ import type { CalendarEventColor } from "@/components/calendar/event-colors";
401
+ import { useRecurrenceScopePrompt } from "@/components/calendar/recurrence-scope-dialog/use-recurrence-scope-prompt";
402
+ import { createWeekView } from "@/components/calendar/time-grid-view/time-grid-view";
403
+ import { Button } from "@/components/ui/button";
404
+
405
+ import type { GoogleCalendarEvent, GoogleEvent } from "@/lib/google-calendar";
406
+ import { createGoogleCalendarApi, GoogleApiError } from "@/lib/google-calendar-api";
407
+ import {
408
+ createGoogleCalendarSync,
409
+ newGoogleId,
410
+ type GoogleCalendarSync,
411
+ } from "@/lib/google-calendar-sync";
412
+
413
+ /** What the calendar shows: an occurrence of a series, or a one-off event. */
414
+ export type GoogleOccurrence = RecurrenceOccurrence<GoogleCalendarEvent, string>;
415
+
416
+ const canonical = createCanonicalRecurrenceAdapter<GoogleEvent>();
417
+
418
+ export const adapters: RecurrenceAdapters<GoogleCalendarEvent, string, string> = {
419
+ ...canonical,
420
+ event: {
421
+ ...canonical.event,
422
+ // Google's "Show as": a free event doesn't make you busy, for `busyAt`, `useBusyResources`
423
+ // and `conflictPolicy` alike. Without `transparency`, Google counts an event as busy, all-day
424
+ // ones too; its own app saves new all-day events as free.
425
+ isBusy: (event) => event.data.transparency !== "transparent",
426
+ },
427
+ };
428
+
429
+ /**
430
+ * Google's event colors, "1" (Lavender) to "11" (Tomato), as the theme's nearest. `colors.get`
431
+ * has their hex values, if you'd rather show Google's own.
432
+ */
433
+ const googleColors: Readonly<Record<string, CalendarEventColor>> = {
434
+ "1": "purple",
435
+ "2": "green",
436
+ "3": "purple",
437
+ "4": "pink",
438
+ "5": "yellow",
439
+ "6": "orange",
440
+ "7": "teal",
441
+ "8": "gray",
442
+ "9": "blue",
443
+ "10": "green",
444
+ "11": "red",
445
+ };
446
+
447
+ export const Calendar = createCalendar<GoogleOccurrence>()({
448
+ eventAdapter: createOccurrenceAdapter(adapters.event),
449
+ views: [
450
+ createWeekView<GoogleOccurrence>({
451
+ describeEvent: ({ event }) =>
452
+ event.data.transparency === "transparent" ? "free" : undefined,
453
+ // Without `colorId`, an event has its calendar's color, here blue.
454
+ getEventColor: ({ event }) => googleColors[event.data.colorId ?? ""] ?? "blue",
455
+ }),
456
+ ],
457
+ });
458
+ ```
459
+
460
+ - **Busy or free.** `isBusy` is the one place the calendar asks whether an event takes up time:
461
+ `busyAt`, `useBusyResources` and `conflictPolicy` all follow it, as
462
+ [Busy or available](../availability.md#busy-or-available) describes. Without the adapter, the
463
+ calendar treats all-day events as free, as Google's app does when it saves them. Google's API
464
+ says it with `transparency`, and counts an event without it as busy, all-day or not, so the
465
+ adapter reads the field rather than the kind.
466
+ - **Colors.** Google's `colorId` is a key into `colors.get`, "1" (Lavender) to "11" (Tomato).
467
+ The map picks the theme's nearest named color. An event without `colorId` has its calendar's
468
+ color, which `calendarList.get` returns.
469
+ - **Imports.** The view imports the `lib/` files through `@/lib/…`, the alias Next.js apps start
470
+ with. `lib/google-calendar-sync.ts` imports its neighbors with `./`.
471
+
472
+ Changes go back the other way. `toGoogleTimes` writes an interval as Google's `start` and `end`:
473
+
474
+ ```ts title="lib/google-calendar-sync.ts"
475
+ /**
476
+ * An interval as Google's `start` and `end`, on `timeZone`'s clock unless the event has its own.
477
+ * Each sets the field it uses and clears the other, so a move between all-day and timed works.
478
+ */
479
+ export function toGoogleTimes(
480
+ interval: CalendarEventInterval,
481
+ timeZone: string,
482
+ ): Pick<GoogleEventWrite, "end" | "start"> {
483
+ if (interval.kind === "all-day") {
484
+ // Google's `end.date` is the day after the last one, as the calendar's `end` is.
485
+ const date = (day: Temporal.PlainDate) => ({ date: day.toString(), dateTime: null });
486
+ return { end: date(interval.end), start: date(interval.start) };
487
+ }
488
+ const zone = (interval.kind === "timed" && interval.sourceTimeZone) || timeZone;
489
+ const time = (at: Temporal.Instant | Temporal.PlainDateTime) => ({
490
+ date: null,
491
+ // RFC 3339 with the offset, such as 2026-10-20T11:00:00+02:00.
492
+ dateTime: (at instanceof Temporal.Instant
493
+ ? at.toZonedDateTimeISO(zone)
494
+ : at.toZonedDateTime(zone)
495
+ ).toString({ timeZoneName: "never" }),
496
+ timeZone: zone,
497
+ });
498
+ return { end: time(interval.end), start: time(interval.start) };
499
+ }
500
+
501
+ /** Google event IDs are base32hex: lowercase a–v and digits. A UUID's hex digits fit. */
502
+ export const newGoogleId = () => crypto.randomUUID().replaceAll("-", "");
503
+ ```
504
+
505
+ `events.patch` merges `start` and `end` field by field, so a write sets the field it uses and
506
+ clears the other with `null`. Without that, an event dragged from the all-day row into the time
507
+ grid would keep its `date` beside the new `dateTime`.
508
+
509
+ ## Series: masters, not instances
510
+
511
+ `events.list` can return a series two ways:
512
+
513
+ - **`singleEvents=true`.** Google expands each series between `timeMin` and `timeMax` and leaves
514
+ the master out. Each occurrence is an event of its own, with its series in `recurringEventId`,
515
+ but not the series' rule.
516
+ - **Masters**, the default. Each series comes once, with its rule in `recurrence`, plus the
517
+ occurrences that changed or were cancelled. `@moltenship/calendar-recurrence` expands them for the
518
+ dates on screen, as [Show and edit recurring events](../recurrence/calendar.md) does.
519
+
520
+ This guide loads masters:
521
+
522
+ - **Edits need the rule.** "This and following events" ends the series before the occurrence and
523
+ starts a new one, and "All events" moves the rule. Both rewrite the master's `recurrence`, and
524
+ `resolveRecurrenceEdit` works them out from it. With `singleEvents=true` you would fetch each
525
+ master as well.
526
+ - **Smaller syncs.** A change to a series is one item in a sync, the master, rather than every
527
+ occurrence Google expanded. A series that never ends is one event.
528
+ - **Fewer requests.** Once a master has loaded, the calendar expands it for whatever dates it
529
+ shows.
530
+
531
+ The cost is expanding series yourself, which the recurrence package does, with Google's DST and
532
+ interop cases in its tests. A read-only calendar that never edits series can take
533
+ `singleEvents=true` and skip the recurrence package.
534
+
535
+ ## Load the dates on screen
536
+
537
+ The calendar reports the dates it shows through `onVisibleRangeChange`. `loadInstantRange` is
538
+ those dates, and the pages a scrolling view keeps ready, as instants:
539
+
540
+ ```tsx title="components/google-calendar-view.tsx"
541
+ export function GoogleCalendar({ sync, timeZone }: GoogleCalendarProps) {
542
+ const [today] = useState(() => Temporal.Now.plainDateISO(timeZone));
543
+ const events = useSyncExternalStore(sync.subscribe, sync.getEvents, sync.getEvents);
544
+ // One expander while the calendar is mounted, so series that didn't change keep their work.
545
+ const [expander] = useState(() => createOccurrenceExpander(adapters));
546
+ const [range, setRange] = useState(() => weekRange(today, { weekStartsOn: weekRules.firstDay }));
547
+ const { occurrences } = useMemo(
548
+ () => expander.expand(events, { range, timeZone }),
549
+ [expander, events, range, timeZone],
550
+ );
551
+ const [selection, setSelection] = useState<CalendarSelection | null>(null);
552
+ const [focus, setFocus] = useState<CalendarFocus | null>(null);
553
+ const [status, setStatus] = useState("");
554
+ const { ask, dialog } = useRecurrenceScopePrompt();
555
+
556
+ function onVisibleRangeChange({ loadInstantRange, loadRange }: CalendarVisibleRange) {
557
+ setRange(loadRange);
558
+ // `timeMin` and `timeMax` for the dates on screen, and the pages a scrolling view keeps ready.
559
+ sync
560
+ .load(loadInstantRange)
561
+ .then(loaded, (error) => setStatus(`Couldn't load: ${reasonOf(error)}`));
562
+ }
563
+
564
+ // A later load or sync that works clears a load error.
565
+ function loaded() {
566
+ setStatus((current) => (current.startsWith("Couldn't load") ? "" : current));
567
+ }
568
+ ```
569
+
570
+ The sync store keeps Google's events by ID and maps each once:
571
+
572
+ ```ts title="lib/google-calendar-sync.ts"
573
+ // lib/google-calendar-sync.ts
574
+ import type { CalendarEventChange, CalendarEventInterval } from "@moltenship/calendar";
575
+ import {
576
+ createCanonicalRecurrenceAdapter,
577
+ createOccurrenceExpander,
578
+ recurrenceOverrideEdit,
579
+ type RecurrenceDate,
580
+ type RecurrenceEdit,
581
+ type RecurrenceSeriesEdit,
582
+ } from "@moltenship/calendar-recurrence";
583
+
584
+ import {
585
+ fromGoogleEvents,
586
+ readGoogleRecurrence,
587
+ toGoogleRecurrence,
588
+ type GoogleCalendarEvent,
589
+ type GoogleEvent,
590
+ } from "./google-calendar";
591
+ import {
592
+ GoogleApiError,
593
+ type GoogleCalendarApi,
594
+ type GoogleEventWrite,
595
+ } from "./google-calendar-api";
596
+
597
+ /** Instants to load events for, half-open, as `onVisibleRangeChange`'s `loadInstantRange`. */
598
+ export interface TimeRange {
599
+ readonly end: Temporal.Instant;
600
+ readonly start: Temporal.Instant;
601
+ }
602
+
603
+ /** What `resolveRecurrenceEdit` returns for a change it accepted. */
604
+ export type GoogleEdit = Exclude<
605
+ RecurrenceEdit<GoogleCalendarEvent, string, string>,
606
+ { type: "rejected" }
607
+ >;
608
+
609
+ export interface GoogleCalendarSync {
610
+ /** The events loaded so far, for the expander: the same array until one changes. */
611
+ readonly getEvents: () => readonly GoogleCalendarEvent[];
612
+ /** Calls `listener` whenever the events change, and returns a function that stops it. */
613
+ readonly subscribe: (listener: () => void) => () => void;
614
+ /** Loads the events `range` needs that aren't loaded yet. */
615
+ readonly load: (range: TimeRange) => Promise<void>;
616
+ /** Applies every change since the last sync, or syncs again from scratch after a 410. */
617
+ readonly sync: () => Promise<void>;
618
+ /** Writes an edit to Google, then syncs. Throws, after the sync, if Google refused a write. */
619
+ readonly save: (edit: GoogleEdit, timeZone: string) => Promise<void>;
620
+ }
621
+
622
+ const day = { hours: 24 };
623
+
624
+ export function createGoogleCalendarSync(api: GoogleCalendarApi): GoogleCalendarSync {
625
+ /** Google's events by ID: masters, changed and cancelled occurrences, one-off events. */
626
+ const stored = new Map<string, GoogleEvent>();
627
+ const mapped = new WeakMap<GoogleEvent, GoogleCalendarEvent | null>();
628
+ const listeners = new Set<() => void>();
629
+ let events: readonly GoogleCalendarEvent[] = [];
630
+ /** The sync covers every event from here on. */
631
+ let syncedFrom: Temporal.Instant | undefined;
632
+ /** Dates before `syncedFrom` loaded since, sorted and apart. */
633
+ let earlier: TimeRange[] = [];
634
+ let lastRange: TimeRange | undefined;
635
+ let syncToken: string | undefined;
636
+
637
+ // One request chain at a time, so an older answer never overwrites a newer one.
638
+ let queue: Promise<unknown> = Promise.resolve();
639
+ function enqueue<T>(task: () => Promise<T>): Promise<T> {
640
+ const run = queue.then(task, task);
641
+ queue = run.catch(() => undefined);
642
+ return run;
643
+ }
644
+
645
+ function changed() {
646
+ // Each Google event maps once, so the expander reuses its work for the ones that didn't change.
647
+ const next = [...stored.values()].flatMap((item) => {
648
+ if (!mapped.has(item)) {
649
+ const { events: mappedEvents, problems } = fromGoogleEvents([item]);
650
+ for (const problem of problems) console.warn(`Google Calendar: ${problem}`);
651
+ mapped.set(item, mappedEvents[0] ?? null);
652
+ }
653
+ return mapped.get(item) ?? [];
654
+ });
655
+ if (next.length === events.length && next.every((event, index) => event === events[index])) {
656
+ return;
657
+ }
658
+ events = next;
659
+ for (const listener of listeners) listener();
660
+ }
661
+
662
+ /** Google's answer, by ID. A cancelled occurrence stays, since it hides that occurrence. */
663
+ function apply(items: readonly GoogleEvent[]) {
664
+ const deleted = new Set<string>();
665
+ for (const item of items) {
666
+ if (item.recurringEventId !== undefined && deleted.has(item.recurringEventId)) continue;
667
+ if (item.status !== "cancelled" || item.recurringEventId !== undefined) {
668
+ stored.set(item.id, item);
669
+ continue;
670
+ }
671
+ stored.delete(item.id);
672
+ // A deleted series takes its changed and cancelled occurrences with it, in this answer too.
673
+ deleted.add(item.id);
674
+ for (const [id, other] of stored) if (other.recurringEventId === item.id) stored.delete(id);
675
+ }
676
+ }
677
+ /** The etags of a series' master and changed occurrences, or of one occurrence's, by ID. */
678
+ function versions(seriesId: string, recurrenceId?: RecurrenceDate) {
679
+ const found = new Map<string, string | undefined>();
680
+ for (const { data, override } of events) {
681
+ const inSeries = data.id === seriesId || override?.seriesId === seriesId;
682
+ const at =
683
+ recurrenceId === undefined ||
684
+ (override !== undefined &&
685
+ keyOf(override.seriesId, override.recurrenceId) === keyOf(seriesId, recurrenceId));
686
+ if (inSeries && at) found.set(data.id, data.etag);
687
+ }
688
+ return found;
689
+ }
690
+ ```
691
+
692
+ The first range starts the sync. Its list has a `timeMin` and no `timeMax`, as the full sync in
693
+ Google's [sync guide](https://developers.google.com/workspace/calendar/api/guides/sync) does, so
694
+ the store gets every event from the first date on screen on, and a sync token for them. Dates
695
+ before it load when the calendar shows them, between `timeMin` and `timeMax`:
696
+
697
+ ```ts title="lib/google-calendar-sync.ts"
698
+ /**
699
+ * The full sync, as Google's sync guide does it: every event that ends after the first date on
700
+ * screen, with no `timeMax`, and the token that syncs them from then on.
701
+ */
702
+ async function fullSync(range: TimeRange) {
703
+ // All-day events are dates on the Google calendar's own clock, which may not be the one on
704
+ // screen, so lists reach a day further.
705
+ const { items, nextSyncToken } = await api.list({ timeMin: range.start.subtract(day) });
706
+ // Swapped in once the list has worked, so a failure leaves the store as it was.
707
+ stored.clear();
708
+ apply(items);
709
+ syncedFrom = range.start;
710
+ earlier = [];
711
+ syncToken = nextSyncToken;
712
+ changed();
713
+ }
714
+
715
+ async function loadNow(range: TimeRange) {
716
+ lastRange = range;
717
+ if (syncedFrom === undefined) return fullSync(range);
718
+ // Later dates are in the store already. Earlier ones load once, between two bounds.
719
+ const end = Temporal.Instant.compare(range.end, syncedFrom) < 0 ? range.end : syncedFrom;
720
+ for (const gap of missing(earlier, { end, start: range.start })) {
721
+ const { items } = await api.list({
722
+ timeMax: gap.end.add(day),
723
+ timeMin: gap.start.subtract(day),
724
+ });
725
+ apply(items);
726
+ earlier = merged(earlier, gap);
727
+ changed();
728
+ }
729
+ }
730
+ ```
731
+
732
+ - **Half-open on both sides.** `timeMin` bounds an event's end and `timeMax` its start, both
733
+ exclusive, so Google returns the events that overlap `[timeMin, timeMax)`: the same rule as the
734
+ calendar's. An event that ends at midnight doesn't show on the next day.
735
+ - **All-day events** are dates on the Google calendar's clock, which may not be the viewer's, so
736
+ each list reaches a day further.
737
+ - **Later dates need no request.** Scroll forward, and the store has the events already. Scroll
738
+ back past the first date, and it lists each earlier range once.
739
+ - **Every page first.** A master on one page and its changed occurrences on the next are one
740
+ series, so the events show once the last page is in.
741
+ - **One request at a time.** Loads, syncs and writes wait for each other, so a slow answer never
742
+ overwrites a newer one.
743
+ - **One map per event.** `getEvents` returns the same array until an event changes, and the same
744
+ calendar event for a Google event that didn't change, so the expander only redoes the series
745
+ that did.
746
+
747
+ For a calendar with years of events ahead, the first list is long. Then bound it with a
748
+ `timeMax` too, and list later dates as the calendar reaches them, as it does earlier ones.
749
+
750
+ ## Sync changes
751
+
752
+ A list with `syncToken` returns every event that changed since the token, and a new token:
753
+
754
+ ```ts title="lib/google-calendar-sync.ts"
755
+ async function syncNow() {
756
+ if (syncToken === undefined) {
757
+ // The first load failed: try it again.
758
+ if (syncedFrom === undefined && lastRange !== undefined) await fullSync(lastRange);
759
+ return;
760
+ }
761
+ try {
762
+ // Every change since the last sync, whatever its dates.
763
+ const { items, nextSyncToken } = await api.list({ syncToken });
764
+ apply(items);
765
+ syncToken = nextSyncToken ?? syncToken;
766
+ changed();
767
+ } catch (error) {
768
+ // 410 Gone: the token expired. Sync again from scratch, from the dates on screen. Until that
769
+ // works, the old events stay, and the next sync tries again.
770
+ if (!isStatus(error, 410) || lastRange === undefined) throw error;
771
+ await fullSync(lastRange);
772
+ }
773
+ }
774
+ ```
775
+
776
+ | A sync returns | The store |
777
+ | ------------------------------------------- | -------------------------------------------------------------------- |
778
+ | An event | Replaces the one with its ID, or adds it |
779
+ | A cancelled event or master | Removes it, and a master's changed and cancelled occurrences with it |
780
+ | A cancelled occurrence (`recurringEventId`) | Keeps it: it hides that occurrence |
781
+
782
+ - **The same request.** With `syncToken`, Google refuses filters such as `timeMin`, `timeMax`,
783
+ `q`, `orderBy` and `updatedMin` with a 400. Keep any other parameter the same as on the first
784
+ list.
785
+ - **One token.** Lists of earlier dates return tokens too, and the store ignores them. A newer
786
+ token would skip what changed between the two lists. Google's guide doesn't say whether the sync
787
+ token reports changes to events before its `timeMin`; the store applies whatever a sync returns.
788
+ - **A failed first load** is tried again by the next sync, so the calendar fills in once the
789
+ network is back.
790
+ - **410 Gone.** Tokens expire, and then Google answers 410. The store syncs again from scratch,
791
+ from the dates on screen. It swaps the new events in once they've loaded, so a failure keeps
792
+ what's on screen, and the next sync tries again. Try it in the demo: expire the sync token, then
793
+ sync.
794
+
795
+ ### Stay live
796
+
797
+ A sync needs a reason to run. The calendar syncs after every write, when the tab comes back, and
798
+ once a minute:
799
+
800
+ ```tsx title="components/google-calendar-view.tsx"
801
+ useEffect(() => {
802
+ // Catch up when the tab comes back, and every minute: push notifications can be late, or lost.
803
+ const catchUp = () => {
804
+ if (document.visibilityState === "visible") sync.sync().then(loaded, () => undefined);
805
+ };
806
+ document.addEventListener("visibilitychange", catchUp);
807
+ const timer = setInterval(catchUp, 60_000);
808
+ return () => {
809
+ document.removeEventListener("visibilitychange", catchUp);
810
+ clearInterval(timer);
811
+ };
812
+ }, [sync]);
813
+ ```
814
+
815
+ To show changes as they happen, subscribe to
816
+ [push notifications](https://developers.google.com/workspace/calendar/api/guides/push). Your
817
+ server opens a watch channel for the user's calendar, with an HTTPS address of its own:
818
+
819
+ ```http
820
+ POST https://www.googleapis.com/calendar/v3/calendars/primary/events/watch
821
+ Authorization: Bearer <access token>
822
+ Content-Type: application/json
823
+
824
+ { "id": "<a new UUID>", "type": "web_hook", "address": "https://example.com/api/google-calendar/notifications" }
825
+ ```
826
+
827
+ - **Notifications carry no events.** Each one says that something changed, in
828
+ `X-Goog-Resource-State: exists`, and which channel it's for, in `X-Goog-Channel-ID`. Tell the
829
+ user's open tabs, over server-sent events or a WebSocket, and they sync. The demo's "Push
830
+ notifications" box does that part.
831
+ - **Channels expire.** Open a new one before `expiration`, and close old ones with
832
+ `channels.stop`. The first message on a channel says `sync`, and needs no action.
833
+ - **Some are lost.** Google drops notifications now and then, so keep the timer above.
834
+
835
+ ## Write changes back
836
+
837
+ When someone drags or deletes an event, `onEventChange` works out what to save and hands it to
838
+ the store:
839
+
840
+ ```tsx title="components/google-calendar-view.tsx"
841
+ async function onEventChange(change: OccurrenceChange) {
842
+ let scope: RecurrenceEditScope = "this";
843
+ // Google keeps deleted instances as cancelled overrides, which hide occurrences as EXDATEs do.
844
+ const options = { overrides: events, timeZone };
845
+ if (isRecurringChange(change)) {
846
+ const scopes = recurrenceEditScopes(change, adapters, options);
847
+ if (scopes.length === 0) {
848
+ setStatus("This repeating event can't change that way.");
849
+ throw new Error("No scope applies");
850
+ }
851
+ const picked = await ask({
852
+ action: change.cause === "delete" ? "delete" : "edit",
853
+ eventTitle: change.event.event.title,
854
+ scopes,
855
+ });
856
+ if (picked === null) throw new DOMException("Cancelled", "AbortError");
857
+ scope = picked;
858
+ }
859
+ const edit = resolveRecurrenceEdit(change, scope, adapters, {
860
+ ...options,
861
+ // Google takes IDs you pick, so a "following" edit's new series is known before it's saved.
862
+ newSeriesId: newGoogleId(),
863
+ occurrences,
864
+ });
865
+ if (edit.type === "rejected") {
866
+ setStatus(edit.message);
867
+ throw new Error(edit.message);
868
+ }
869
+
870
+ setStatus("Saving…");
871
+ try {
872
+ // The change shows, pending, until Google answers. Throwing rolls it back.
873
+ await sync.save(edit, timeZone);
874
+ } catch (error) {
875
+ setStatus(`Not saved: ${reasonOf(error)}`);
876
+ throw error;
877
+ }
878
+ setStatus("Saved.");
879
+ if (edit.type === "series") {
880
+ setSelection((current) => renamed(current, edit.occurrenceIds));
881
+ setFocus((current) => renamed(current, edit.occurrenceIds));
882
+ }
883
+ }
884
+ ```
885
+
886
+ ```ts title="lib/google-calendar-sync.ts"
887
+ async function saveNow(edit: GoogleEdit, timeZone: string) {
888
+ try {
889
+ if (edit.type === "event") await saveEvent(edit.change, timeZone);
890
+ else await saveSeries(edit, timeZone);
891
+ } finally {
892
+ // Picks up what Google did, such as the newer version a 412 refused to overwrite.
893
+ await syncNow().catch((error: unknown) => console.warn("Google Calendar sync failed", error));
894
+ changed();
895
+ }
896
+ }
897
+
898
+ /** A new event, or a change to a one-off event. */
899
+ async function saveEvent(
900
+ change: CalendarEventChange<GoogleCalendarEvent, string, string>,
901
+ timeZone: string,
902
+ ) {
903
+ if (change.cause === "create") {
904
+ const times = toGoogleTimes(change.proposed, timeZone);
905
+ await insert({ id: newGoogleId(), summary: "New event", ...times });
906
+ return;
907
+ }
908
+ // The etag of the version on screen: if someone changed it since, Google answers 412.
909
+ const { data } = change.event;
910
+ if (change.cause === "delete") {
911
+ await remove(data, data.etag);
912
+ return;
913
+ }
914
+ const times = toGoogleTimes(change.proposed, data.start?.timeZone ?? timeZone);
915
+ apply([await api.patch(data.id, times, data.etag)]);
916
+ }
917
+
918
+ /** Inserts an event with the ID it names. A 409 means a try whose answer was lost got there. */
919
+ async function insert(event: GoogleEventWrite) {
920
+ try {
921
+ apply([await api.insert(event)]);
922
+ } catch (error) {
923
+ if (!isStatus(error, 409)) throw error;
924
+ }
925
+ }
926
+
927
+ /** Deletes an event, which Google keeps as cancelled. One already gone is done. */
928
+ async function remove(event: GoogleEvent, etag: string | undefined) {
929
+ if (event.status === "cancelled") return;
930
+ try {
931
+ await api.remove(event.id, etag);
932
+ } catch (error) {
933
+ if (!isStatus(error, 404, 410)) throw error;
934
+ }
935
+ // Google's answer to a delete has no body, so the cancelled one's etag isn't known.
936
+ apply([{ ...event, etag: undefined, status: "cancelled" }]);
937
+ }
938
+ ```
939
+
940
+ - **Optimistic, with rollback.** The calendar shows the change as pending while `onEventChange`
941
+ runs, and keeps it until the events change. If it throws, the calendar puts the event back and
942
+ announces that the change wasn't saved. There's no copy of the events to restore by hand.
943
+ - **Etags.** Every Google event has an `etag` that changes on every write. Writes send the etag of
944
+ the version on screen as `If-Match`. A change to a recurring event syncs first, and stops with a
945
+ 412 if the series changed in Google since the user saw it: for "This event", the occurrence
946
+ itself.
947
+ The instances it then rewrites and clears go without an etag.
948
+ - **412 Precondition Failed.** Someone changed the event since it loaded. The write is refused,
949
+ the sync after it brings in their version, and the drag rolls back onto it. The footer says what
950
+ happened. To try it: turn off push notifications, move "Design review" with the button, then drag
951
+ it. You could also retry with the new etag when their change didn't touch the times.
952
+ - **Rate limits.** The client's backoff waits it out while the change stays pending. Rate-limit two
953
+ requests in the demo, then drag an event.
954
+ - **Already deleted.** Deleting an event someone else deleted gets a 410, which counts as done.
955
+ So is deleting an occurrence someone cancelled, with "This event". Moving one throws a 410
956
+ instead, or a 412 for "This and following events" and "All events", so the change rolls back
957
+ rather than bring the occurrence back.
958
+ - **New events** get an ID from `newGoogleId`. Google takes IDs you pick, so you know an event's ID
959
+ before it's saved, as you do for "This and following events". If an insert gets a 5xx after
960
+ Google stored it, the retry gets a 409, and the event is there.
961
+
962
+ The footer under the calendar says what happened to the last change, in words:
963
+
964
+ ```tsx title="components/google-calendar-view.tsx"
965
+ /** Why Google refused a request, for the user. */
966
+ function reasonOf(error: unknown): string {
967
+ if (!(error instanceof GoogleApiError)) return error instanceof Error ? error.message : "";
968
+ if (error.status === 412) return "it changed in Google Calendar. This is the latest.";
969
+ if (error.status === 410) return "it was deleted in Google Calendar.";
970
+ const rateLimited = ["rateLimitExceeded", "userRateLimitExceeded"].includes(error.reason ?? "");
971
+ if (error.status === 429 || rateLimited) return "Google is busy. Try again in a minute.";
972
+ return error.message;
973
+ }
974
+ ```
975
+
976
+ ### This, following and all events
977
+
978
+ A series edit from `resolveRecurrenceEdit` says what to write: the master, a new series, the edited
979
+ occurrence and the series' other changed occurrences. In Google, those are these calls:
980
+
981
+ | Scope | The edit | The Calendar API |
982
+ | ------------------------- | ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
983
+ | This event | `override` | `events.instances` with `originalStart` returns the occurrence's instance, with its ID and etag. Write it with `events.update`, and Google keeps it as a changed occurrence of the series. |
984
+ | This event, deleted | `series` with a new exception date | Delete the instance. Google keeps it as cancelled, and the master stays as it was. |
985
+ | This and following events | `newSeries`, and `series`, which ends the rule | Insert the new series, then patch the master's `recurrence` with UNTIL or a smaller COUNT. That's Google's own split: two events, with no link between them. If the patch fails, the store deletes the new series again. |
986
+ | All events | `series` | Patch the master's `start`, `end` and `recurrence`. |
987
+ | All events, deleted | `series: "delete"` | Delete the master. Google deletes its changed and cancelled occurrences with it. |
988
+
989
+ ```ts title="lib/google-calendar-sync.ts"
990
+ async function saveSeries(
991
+ edit: RecurrenceSeriesEdit<GoogleCalendarEvent, string, string>,
992
+ timeZone: string,
993
+ ) {
994
+ const { newSeries, override, series, seriesId } = edit;
995
+ const zoneOf = (event: GoogleEvent) => event.start?.timeZone ?? timeZone;
996
+ // Google deletes a series' changed and cancelled occurrences with it.
997
+ if (series.action === "delete") {
998
+ await remove(series.event.data, series.event.data.etag);
999
+ return;
1000
+ }
1001
+ // The writes below replace instances the store read, some without etags. So sync first, and
1002
+ // stop if the series changed in Google since the user saw it: the master and the changed
1003
+ // occurrences, or for "this", the occurrence's own instance. The edit holds what they saw of
1004
+ // the master and the edited occurrence; the store may have newer versions already.
1005
+ const only = edit.scope === "this" ? edit.recurrenceId : undefined;
1006
+ const edited = override?.action === "create" ? undefined : override?.event;
1007
+ const before = versions(seriesId, only);
1008
+ if (only !== undefined) before.clear();
1009
+ // The edited occurrence as the user saw it: its exception, or none.
1010
+ else for (const id of versions(seriesId, edit.recurrenceId).keys()) before.delete(id);
1011
+ if (series.action === "update" && only === undefined) {
1012
+ before.set(seriesId, series.event.data.etag);
1013
+ }
1014
+ if (edited !== undefined) before.set(edited.data.id, edited.data.etag);
1015
+ await syncNow();
1016
+ const after = versions(seriesId, only);
1017
+ if (only !== undefined) {
1018
+ // Cancelled in Google meanwhile: a delete is done, and a move would bring it back.
1019
+ const now = events.find(
1020
+ (event) => event.override?.seriesId === seriesId && after.has(event.data.id),
1021
+ );
1022
+ if (now?.override?.cancelled === true && before.get(now.data.id) !== now.data.etag) {
1023
+ if (edit.cause === "delete") return;
1024
+ throw new GoogleApiError(410, "deleted", "The occurrence was deleted in Google Calendar.");
1025
+ }
1026
+ }
1027
+ const changedInGoogle = [...after].some(([id, etag]) => {
1028
+ if (!before.has(id)) return true;
1029
+ // Undefined: cancelled here, and Google's answer to a delete has no etag.
1030
+ const seen = before.get(id);
1031
+ return seen !== undefined && seen !== etag;
1032
+ });
1033
+ if (changedInGoogle || (before.has(seriesId) && !after.has(seriesId))) {
1034
+ throw new GoogleApiError(412, "conditionNotMet", "The series changed in Google Calendar.");
1035
+ }
1036
+
1037
+ // "This event" deletes cancel the occurrence's instance, as Google does, and leave the master.
1038
+ if (edit.scope === "this" && edit.cause === "delete") {
1039
+ const write: OccurrenceWrite = {
1040
+ from: edited,
1041
+ placement: "cancel",
1042
+ recurrenceId: edit.recurrenceId,
1043
+ seriesId,
1044
+ };
1045
+ await writeOccurrences([write], [], timeZone);
1046
+ return;
1047
+ }
1048
+ // The new `recurrence` is written from what `fromGoogleEvents` read, which would drop the
1049
+ // lines it couldn't, such as EXRULE.
1050
+ const master = series.action === "update" ? series.event.data : undefined;
1051
+ if (master !== undefined && readGoogleRecurrence(master.recurrence ?? []).problems.length > 0) {
1052
+ throw new Error("This series has rules the app can't write back. Change it in Google.");
1053
+ }
1054
+ // The series' other changed and cancelled occurrences, which the edit moves or ends.
1055
+ const others = events
1056
+ .filter((event) => event.override?.seriesId === seriesId && event.data.id !== edited?.data.id)
1057
+ .map((event) => ({ event, next: recurrenceOverrideEdit(edit, event.override!.recurrenceId) }))
1058
+ .filter(({ next }) => next.action !== "keep");
1059
+
1060
+ // "This and following events" is Google's split: a new series from the occurrence on, and the
1061
+ // old one ended before it. The new one goes first, so a failure leaves the old one whole.
1062
+ const newSeriesId = newSeries?.id ?? newGoogleId();
1063
+ if (newSeries !== undefined) {
1064
+ const zone = zoneOf(newSeries.from.data);
1065
+ await insert({
1066
+ ...contentOf(newSeries.from.data),
1067
+ id: newSeriesId,
1068
+ ...toGoogleTimes(newSeries.placement, zone),
1069
+ recurrence: toGoogleRecurrence(newSeries.recurrence, zone),
1070
+ });
1071
+ }
1072
+ if (series.action === "update") {
1073
+ const zone = zoneOf(series.event.data);
1074
+ const fields = {
1075
+ ...toGoogleTimes(series.placement, zone),
1076
+ recurrence: toGoogleRecurrence(series.recurrence, zone),
1077
+ };
1078
+ try {
1079
+ apply([await api.patch(seriesId, fields, series.event.data.etag)]);
1080
+ } catch (error) {
1081
+ // With the old series still whole, the new one would repeat it: take it back.
1082
+ if (newSeries !== undefined) {
1083
+ await remove({ id: newSeriesId }, undefined).catch(() => undefined);
1084
+ }
1085
+ throw error;
1086
+ }
1087
+ }
1088
+
1089
+ // The edited occurrence, and the others, which follow the series' new times or end with it.
1090
+ const writes: OccurrenceWrite[] = [];
1091
+ const left: GoogleCalendarEvent[] = [];
1092
+ if (override?.action === "create") {
1093
+ writes.push({ placement: override.placement, recurrenceId: override.recurrenceId, seriesId });
1094
+ } else if (override?.action === "update") {
1095
+ writes.push({
1096
+ from: override.event,
1097
+ placement: override.cancelled ? "cancel" : override.placement,
1098
+ recurrenceId: override.recurrenceId,
1099
+ seriesId: override.series === "new" ? newSeriesId : seriesId,
1100
+ });
1101
+ } else if (override?.action === "delete") {
1102
+ left.push(override.event);
1103
+ }
1104
+ for (const { event, next } of others) {
1105
+ if (next.action === "delete") left.push(event);
1106
+ if (next.action !== "update") continue;
1107
+ writes.push({
1108
+ from: event,
1109
+ placement: event.override!.cancelled ? "cancel" : event,
1110
+ recurrenceId: next.recurrenceId,
1111
+ seriesId: next.series === "new" ? newSeriesId : seriesId,
1112
+ });
1113
+ }
1114
+ await writeOccurrences(writes, left, timeZone);
1115
+ }
1116
+
1117
+ /**
1118
+ * Writes each occurrence to the instance at its series and original start, then clears the
1119
+ * instances the moved ones leave. Google names an exception by its series and original start,
1120
+ * and neither can change, so an occurrence that moves to another original start is written to
1121
+ * the instance there. One may land where another leaves, so every write comes first.
1122
+ */
1123
+ async function writeOccurrences(
1124
+ writes: readonly OccurrenceWrite[],
1125
+ left: readonly GoogleCalendarEvent[],
1126
+ timeZone: string,
1127
+ ) {
1128
+ const written = new Set<string>();
1129
+ const vacated = [...left];
1130
+ for (const { from, placement, recurrenceId, seriesId } of writes) {
1131
+ written.add(keyOf(seriesId, recurrenceId));
1132
+ const stays =
1133
+ from?.override !== undefined &&
1134
+ keyOf(from.override.seriesId, from.override.recurrenceId) === keyOf(seriesId, recurrenceId);
1135
+ // The etag of the version on screen, or of the instance just read.
1136
+ let instance: GoogleEvent;
1137
+ try {
1138
+ instance = stays ? from.data : await api.instance(seriesId, recurrenceId.toString());
1139
+ } catch (error) {
1140
+ // An occurrence to cancel whose series is gone is gone too.
1141
+ if (placement === "cancel" && !stored.has(seriesId) && isStatus(error, 404, 410)) continue;
1142
+ throw error;
1143
+ }
1144
+ // Cancelled in Google since it loaded: a change to it would bring it back.
1145
+ if (from === undefined && instance.status === "cancelled" && placement !== "cancel") {
1146
+ throw new GoogleApiError(410, "deleted", "The occurrence was deleted in Google Calendar.");
1147
+ }
1148
+ if (placement === "cancel") await remove(instance, instance.etag);
1149
+ // The moved occurrence's own title, color and the rest, not the instance's.
1150
+ else await replace(instance, from?.data ?? instance, placement, instance.etag, timeZone);
1151
+ if (from !== undefined && !stays) vacated.push(from);
1152
+ }
1153
+ for (const { data, override } of vacated) {
1154
+ if (override === undefined || written.has(keyOf(override.seriesId, override.recurrenceId))) {
1155
+ continue;
1156
+ }
1157
+ // No etags: the edit replaces these, whatever changed on them since.
1158
+ const master = stored.get(override.seriesId);
1159
+ const occurrence = master && occurrenceAt(master, override.recurrenceId);
1160
+ // The series' rule still has an occurrence there, so it shows as the series has it.
1161
+ if (master !== undefined && occurrence !== undefined) {
1162
+ await replace(data, master, occurrence, undefined, timeZone);
1163
+ } else {
1164
+ await remove(data, undefined);
1165
+ }
1166
+ }
1167
+ }
1168
+
1169
+ /**
1170
+ * Replaces `instance` with `content` at `interval`: all of it, with `events.update`, so nothing
1171
+ * of what was there before stays.
1172
+ */
1173
+ async function replace(
1174
+ instance: GoogleEvent,
1175
+ content: GoogleEvent,
1176
+ interval: CalendarEventInterval,
1177
+ etag: string | undefined,
1178
+ timeZone: string,
1179
+ ) {
1180
+ const fields: GoogleEventWrite = {
1181
+ ...contentOf(content),
1182
+ ...toGoogleTimes(interval, content.start?.timeZone ?? timeZone),
1183
+ originalStartTime: instance.originalStartTime,
1184
+ recurringEventId: instance.recurringEventId,
1185
+ // A cancelled instance comes back.
1186
+ status: content.status === "tentative" ? "tentative" : "confirmed",
1187
+ };
1188
+ try {
1189
+ apply([await api.update(instance.id, fields, etag)]);
1190
+ } catch (error) {
1191
+ // An instance the edit clears may be gone already.
1192
+ if (etag !== undefined || !isStatus(error, 404, 410)) throw error;
1193
+ }
1194
+ }
1195
+ ```
1196
+
1197
+ - **Changed occurrences can't move.** Google names an occurrence by its series and original start,
1198
+ and neither can change. When "All events" moves a series, a changed occurrence keeps its own
1199
+ time and content, but its original start moves with the series. So the store writes it to the
1200
+ instance at the new original start, with `events.update`, which replaces the whole instance:
1201
+ nothing of what was there stays. Then it clears the instance it left: back to the series'
1202
+ occurrence if the new rule still has one there, else cancelled. Every write comes before the
1203
+ clearing, since one occurrence may land where another leaves.
1204
+ - **"This event" deletes** cancel the instance instead of adding an EXDATE line. That's what
1205
+ Google does, and it leaves the master as it was.
1206
+ - **Lines it can't write.** `fromGoogleEvents` doesn't read EXRULE or RDATE periods, so writing a
1207
+ master back would drop them. The store refuses series changes to such a master, and the change
1208
+ rolls back.
1209
+ - **What a copy keeps.** A new series, and an occurrence written to another instance, copy
1210
+ everything but the fields Google sets and the ones that name the event.
1211
+ - **Several requests.** A series edit is a few writes in a row. If one fails partway, the writes
1212
+ before it stay in Google, the sync after it shows them, and the dragged occurrence rolls back
1213
+ onto what Google has.
1214
+
1215
+ ### Limits
1216
+
1217
+ - **Changed occurrences out of view.** The store knows the changed occurrences from the first date
1218
+ on screen on, and in the earlier ranges it has loaded. A series edit doesn't move the ones before
1219
+ those. An occurrence moved to a date more than a day before what the store has loaded shows at its
1220
+ original time until the date it moved to loads.
1221
+ - **Everything ahead.** The first list returns every event from the first date on screen on. See
1222
+ [Load the dates on screen](#load-the-dates-on-screen) for calendars with years of them.
1223
+
1224
+ ## Put it together
1225
+
1226
+ The page's calendar creates one sync store for as long as it's mounted, with the client pointed at
1227
+ your route. Choose the time zone on the server, as the [Next.js guide](./nextjs.md) says:
1228
+
1229
+ ```tsx title="components/google-calendar-view.tsx"
1230
+ /** The calendar a page renders, with one sync store for as long as it's mounted. */
1231
+ export function SyncedCalendar({ timeZone }: { readonly timeZone: string }) {
1232
+ // The browser calls your route, which adds the user's access token.
1233
+ const [sync] = useState(() =>
1234
+ createGoogleCalendarSync(createGoogleCalendarApi({ baseUrl: "/api/google-calendar" })),
1235
+ );
1236
+ return <GoogleCalendar sync={sync} timeZone={timeZone} />;
1237
+ }
1238
+ ```
1239
+
1240
+ ## Sync on the server
1241
+
1242
+ This guide syncs in the browser, which suits a calendar the user looks at. When your server needs
1243
+ the events too, for reminders, booking pages or other people's availability, run the same sync
1244
+ there into your database, with a token per calendar, and let push notifications start it. The
1245
+ browser then loads the dates on screen from your own API, with the same `onVisibleRangeChange`, as
1246
+ [Load events with TanStack Query](./tanstack-query.md) does.