@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,598 @@
1
+ # Show and edit recurring events
2
+
3
+ Expand series for the dates on screen, and ask which events a change applies to.
4
+
5
+ Source: https://time.molten.sh/docs/react/recurrence/calendar
6
+
7
+ > Live example: see it at https://time.molten.sh/docs/react/recurrence/calendar
8
+
9
+ These events repeat: a stand-up every weekday, with Wednesday's skipped and Thursday's moved an
10
+ hour later, a 1:1 every other week, planning on eight Mondays, and a release day every Friday. Drag
11
+ an occurrence, or select one and delete it, and the calendar asks whether the change applies to
12
+ this event, this and following events, or all events. The change waits on screen while it asks.
13
+
14
+ This guide builds that calendar with `@moltenship/calendar-recurrence`. It expands each series into
15
+ its occurrences for the dates on screen, and turns a change to one occurrence into what to save.
16
+ [Recurring events](./model.md) explains the model behind it.
17
+
18
+ ## Install
19
+
20
+ The recurrence package is separate from the calendar. It doesn't use React, so you can also expand
21
+ series on a server.
22
+
23
+ **pnpm**
24
+
25
+ ```bash
26
+ pnpm add @moltenship/calendar-recurrence
27
+ ```
28
+
29
+ **npm**
30
+
31
+ ```bash
32
+ npm install @moltenship/calendar-recurrence
33
+ ```
34
+
35
+ **yarn**
36
+
37
+ ```bash
38
+ yarn add @moltenship/calendar-recurrence
39
+ ```
40
+
41
+ **bun**
42
+
43
+ ```bash
44
+ bun add @moltenship/calendar-recurrence
45
+ ```
46
+
47
+ The dialog that asks for the scope is UI source, like the views. Add it with the shadcn CLI, as
48
+ described in [UI source](../installation.md#ui-source-optional). It brings shadcn's `button` and
49
+ `dialog`:
50
+
51
+ ```bash
52
+ npx shadcn@latest add https://time.molten.sh/r/recurrence-scope-dialog.json
53
+ ```
54
+
55
+ ## Wire the adapters
56
+
57
+ The calendar shows occurrences, not your events. A `RecurrenceOccurrence` is one occurrence of a
58
+ series, or a one-off event passed through, and `createOccurrenceAdapter` turns your event adapter
59
+ into the calendar's adapter for them. A recurrence adapter beside it reads what makes an event a
60
+ series' master, or an override of one occurrence. Together, they're your `RecurrenceAdapters`.
61
+
62
+ An app without an event type of its own can store `RecurringCalendarEvent`s: core's
63
+ [`CalendarEvent`](../concepts/events.md#records-in-times-own-shape) with an optional `recurrence`
64
+ and `override`. `createCanonicalRecurrenceAdapter` returns both adapters for them:
65
+
66
+ ```tsx title="recurrence-calendar.tsx"
67
+ "use client";
68
+
69
+ import { createCalendar } from "@moltenship/calendar";
70
+ import {
71
+ createCanonicalRecurrenceAdapter,
72
+ createOccurrenceAdapter,
73
+ type RecurrenceOccurrence,
74
+ type RecurringCalendarEvent,
75
+ } from "@moltenship/calendar-recurrence";
76
+
77
+ import type { CalendarEventColor } from "@/components/calendar/event-colors";
78
+ import { createWeekView } from "@/components/calendar/time-grid-view/time-grid-view";
79
+
80
+ export interface TeamEventData {
81
+ readonly color: CalendarEventColor;
82
+ }
83
+
84
+ /**
85
+ * A series' master has a `recurrence`, an event that replaces one of its occurrences has an
86
+ * `override`, and any other event happens once.
87
+ */
88
+ export type TeamEvent = RecurringCalendarEvent<TeamEventData>;
89
+
90
+ /** What the calendar shows: one occurrence of a series, or a one-off event. */
91
+ export type TeamOccurrence = RecurrenceOccurrence<TeamEvent, string>;
92
+
93
+ export const adapters = createCanonicalRecurrenceAdapter<TeamEventData>();
94
+
95
+ /** Lucide's "repeat" icon, for the chips of repeating events. */
96
+ const repeatIcon = (
97
+ <svg
98
+ fill="none"
99
+ stroke="currentColor"
100
+ strokeLinecap="round"
101
+ strokeLinejoin="round"
102
+ strokeWidth={2}
103
+ viewBox="0 0 24 24"
104
+ >
105
+ <path d="m17 2 4 4-4 4" />
106
+ <path d="M3 11v-1a4 4 0 0 1 4-4h14" />
107
+ <path d="m7 22-4-4 4-4" />
108
+ <path d="M21 13v1a4 4 0 0 1-4 4H3" />
109
+ </svg>
110
+ );
111
+
112
+ export const Calendar = createCalendar<TeamOccurrence>()({
113
+ // Occurrences are the calendar's events. It reads their titles through your adapter.
114
+ eventAdapter: createOccurrenceAdapter(adapters.event),
115
+ views: [
116
+ createWeekView<TeamOccurrence>({
117
+ // The icon marks a repeating event on screen, and the description says so to screen readers.
118
+ describeEvent: (occurrence) => (occurrence.recurrence ? "repeating event" : undefined),
119
+ getEventColor: (occurrence) => occurrence.event.data.color,
120
+ getEventIcon: (occurrence) => (occurrence.recurrence ? repeatIcon : null),
121
+ }),
122
+ ],
123
+ });
124
+ ```
125
+
126
+ Views receive occurrences, so `getEventColor` reads the color from `occurrence.event`, the event
127
+ the occurrence shows: the master, the override, or the one-off event. `occurrence.recurrence` is set
128
+ on occurrences of a series, so `getEventIcon` marks their chips with a repeat icon, and
129
+ `describeEvent` adds "repeating event" to their accessible names, since the icon is decorative.
130
+
131
+ ### Your own event type
132
+
133
+ With your own event type, write the recurrence adapter yourself. `getRecurrence` returns a master's
134
+ rule, exception dates and extra dates, and `getOverride` returns the series and original start an
135
+ override replaces:
136
+
137
+ ```ts title="meetings.ts"
138
+ import { createCalendar, defineEventAdapter } from "@moltenship/calendar";
139
+ import {
140
+ createOccurrenceAdapter,
141
+ parseRecurrenceRule,
142
+ type RecurrenceAdapters,
143
+ type RecurrenceOccurrence,
144
+ } from "@moltenship/calendar-recurrence";
145
+
146
+ export interface Meeting {
147
+ readonly id: string;
148
+ readonly title: string;
149
+ readonly start: Temporal.Instant;
150
+ readonly end: Temporal.Instant;
151
+ /** Where it was booked. A series repeats on this zone's wall clock. */
152
+ readonly timeZone: string;
153
+ /** On a series' first meeting: an RRULE, such as "FREQ=WEEKLY;BYDAY=MO,WE". */
154
+ readonly repeats?: string;
155
+ /** Starts of meetings the series skips. */
156
+ readonly skips?: readonly Temporal.Instant[];
157
+ /** On a meeting that replaces one of a series: the series, and the start it replaces. */
158
+ readonly replaces?: { readonly seriesId: string; readonly start: Temporal.Instant };
159
+ }
160
+
161
+ export const adapters: RecurrenceAdapters<Meeting, string, never> = {
162
+ event: defineEventAdapter<Meeting>()({
163
+ getId: (meeting) => meeting.id,
164
+ getTitle: (meeting) => meeting.title,
165
+ getInterval: (meeting) => ({
166
+ kind: "timed",
167
+ start: meeting.start,
168
+ end: meeting.end,
169
+ sourceTimeZone: meeting.timeZone,
170
+ }),
171
+ getResourceIds: () => [],
172
+ }),
173
+ recurrence: {
174
+ getRecurrence: (meeting) =>
175
+ meeting.repeats === undefined
176
+ ? undefined
177
+ : { rule: parseRecurrenceRule(meeting.repeats).rule, exceptionDates: meeting.skips },
178
+ getOverride: (meeting) =>
179
+ meeting.replaces && {
180
+ seriesId: meeting.replaces.seriesId,
181
+ recurrenceId: meeting.replaces.start,
182
+ },
183
+ },
184
+ };
185
+
186
+ export const Calendar = createCalendar<RecurrenceOccurrence<Meeting, string>>()({
187
+ eventAdapter: createOccurrenceAdapter(adapters.event),
188
+ });
189
+ ```
190
+
191
+ - A master's `getInterval` is its first occurrence. A timed series repeats on the wall clock of
192
+ `sourceTimeZone`, so a 09:00 meeting stays at 09:00 across daylight saving time.
193
+ - `parseRecurrenceRule` reads RRULE text, with or without the `RRULE:` prefix. It never throws:
194
+ check its `issues` when you save the text, and show an error then.
195
+ - The expander reads each event once while it's the same object, so parsing in the adapter is
196
+ cheap. Replace events rather than changing them.
197
+
198
+ ## Expand the dates on screen
199
+
200
+ A series can be endless, so expand it only for the dates the calendar needs. The calendar reports
201
+ them through `onVisibleRangeChange`:
202
+
203
+ ```ts title="use-occurrences.ts"
204
+ import type { CalendarVisibleRange, PlainDateInterval } from "@moltenship/calendar";
205
+ import { createOccurrenceExpander } from "@moltenship/calendar-recurrence";
206
+ import { useMemo, useState } from "react";
207
+
208
+ import { adapters, type TeamEvent } from "./recurrence-calendar";
209
+
210
+ /**
211
+ * The occurrences of `events` on the dates the calendar asks for. Pass `occurrences` to `events`
212
+ * on `Root`, and `onVisibleRangeChange` to the prop of that name.
213
+ */
214
+ export function useOccurrences(
215
+ events: readonly TeamEvent[],
216
+ timeZone: string,
217
+ // The dates the calendar opens on, so its first render isn't empty.
218
+ initialRange: PlainDateInterval,
219
+ ) {
220
+ // One expander for as long as the calendar is mounted: it keeps its work for series that
221
+ // didn't change, and returns the same occurrence objects for them.
222
+ const [expander] = useState(() => createOccurrenceExpander(adapters));
223
+ const [range, setRange] = useState(initialRange);
224
+ const expansion = useMemo(
225
+ () => expander.expand(events, { range, timeZone }),
226
+ [expander, events, range, timeZone],
227
+ );
228
+
229
+ return {
230
+ issues: expansion.issues,
231
+ occurrences: expansion.occurrences,
232
+ onVisibleRangeChange: ({ loadRange }: CalendarVisibleRange) => setRange(loadRange),
233
+ };
234
+ }
235
+ ```
236
+
237
+ - **One expander.** Create it once, in `useState` as here or at module scope. It keeps its work for
238
+ each series between calls, and gives back the same occurrence objects for events that didn't
239
+ change, so the calendar and its views skip them.
240
+ - **`useMemo` over events and range.** Expansion runs again only when your events or the dates
241
+ change. A new array holding the same event objects is cheap: unchanged series reuse their work.
242
+ - **`loadRange`, not `range`.** Scrolling views render a page of days on either side of the ones
243
+ they show, so a swipe never reveals empty days. `loadRange` includes those pages; `range` is only
244
+ what's visible. In paged views the two are the same.
245
+ - **The first render.** The calendar reports its range after it first renders, so the hook starts
246
+ from the week it opens on, from `weekRange`. Without a first guess, the first frame has no
247
+ events.
248
+ - **Time zones.** `timeZone` is the calendar's zone, which places the range's dates for timed
249
+ series. Series don't repeat in it. They repeat in their own `sourceTimeZone`, or, for events
250
+ without one, in the expander's `defaultTimeZone`, which is UTC unless you set it.
251
+
252
+ `expansion.issues` lists what the expander couldn't read, such as an invalid rule or an override
253
+ whose series isn't loaded, with each event and its position. Bad data never throws: the rest of
254
+ the series and the other events still show. Log the issues, as you would
255
+ [diagnostics](../concepts/events.md#invalid-records).
256
+
257
+ ## Ask which events a change applies to
258
+
259
+ When someone drags an occurrence, the calendar calls `onEventChange` with a change whose `event` is
260
+ the occurrence. `useRecurrenceScopePrompt` from the dialog you added returns `ask`, which opens the
261
+ dialog and resolves with the scope picked, and `dialog`, to render once:
262
+
263
+ ```tsx title="team-calendar.tsx"
264
+ async function onEventChange(change: OccurrenceChange) {
265
+ // A new event, or a change to a one-off event, needs no question.
266
+ let scope: RecurrenceEditScope = "this";
267
+ if (isRecurringChange(change)) {
268
+ const scopes = recurrenceEditScopes(change, adapters, { timeZone });
269
+ // None applies, so there's nothing to ask: tell the user why instead. Throwing rolls the
270
+ // change back.
271
+ if (scopes.length === 0) throw new Error("This repeating event can't change that way.");
272
+ const picked = await ask({
273
+ action: change.cause === "delete" ? "delete" : "edit",
274
+ eventTitle: change.event.event.title,
275
+ scopes,
276
+ });
277
+ // An `AbortError` is announced as a cancel, not as a change that couldn't be saved.
278
+ if (picked === null) throw new DOMException("Cancelled", "AbortError");
279
+ scope = picked;
280
+ }
281
+
282
+ const edit = resolveRecurrenceEdit(change, scope, adapters, {
283
+ // Picked now, so the IDs of a "following" edit's new series are known.
284
+ newSeriesId: crypto.randomUUID(),
285
+ occurrences,
286
+ // The zone the calendar moves occurrences on, so a series dragged by days keeps its time.
287
+ timeZone,
288
+ });
289
+ if (edit.type === "rejected") throw new Error(edit.message);
290
+
291
+ // Save the edit on your server here. The change stays pending until this function returns.
292
+ if (edit.type === "event") {
293
+ setEvents((current) => applyEventChange(current, edit.change));
294
+ return;
295
+ }
296
+ setEvents((current) =>
297
+ applyRecurrenceEdit(current, edit, { createId: () => crypto.randomUUID() }),
298
+ );
299
+ // "following" and "all" give the occurrences new IDs. The selection and keyboard focus
300
+ // follow them, and the calendar moves focus to the occurrence under its new ID.
301
+ setSelection((current) => renamed(current, edit.occurrenceIds));
302
+ setFocus((current) => renamed(current, edit.occurrenceIds));
303
+ }
304
+ ```
305
+
306
+ 1. **`isRecurringChange`** says whether the change is to an occurrence of a series. A new event, or
307
+ a change to a one-off event, needs no question.
308
+ 2. **`ask`** opens the dialog. `action` picks its wording for an edit or a delete, and `scopes`
309
+ comes from **`recurrenceEditScopes`**, which offers only the scopes that apply: no "This and
310
+ following events" on a series' first occurrence, and only "This event" when the rule can't
311
+ follow the change, such as the 28th of each month dragged to a 29th. When none applies, the list
312
+ is empty and there's nothing to ask: tell the user why, and roll the change back.
313
+ 3. **Cancel** resolves `null`. Throwing rolls the change back, as any error in `onEventChange`
314
+ does. Throw an `AbortError`, as the handler does, and the calendar's announcements say the
315
+ change was cancelled rather than that it couldn't be saved.
316
+ 4. **`resolveRecurrenceEdit`** turns the change into an edit: what to save for that scope. Pass
317
+ the calendar's `timeZone` to it and to `recurrenceEditScopes`, so the change is replayed on the
318
+ series' own clock: a series dragged by days keeps its time of day when the calendar's zone and
319
+ the series' change DST on different dates, and one dragged an hour later moves an hour. If you
320
+ keep deleted occurrences as cancelled overrides, as Google's API does, pass them as `overrides`
321
+ too. A
322
+ change that needs no scope comes back as `type: "event"`, with your event unwrapped from the
323
+ occurrence, to apply as you would without recurrence. A scope that can't apply comes back as
324
+ `type: "rejected"`, with a `reason` and a `message`.
325
+ 5. **Save** the edit, below. The change stays pending until `onEventChange` returns.
326
+
327
+ While the dialog is open, the change waits on screen as pending: the dragged occurrence shows where
328
+ it was dropped. Only that occurrence shows the change. The calendar keeps pending changes per event
329
+ and knows nothing about series, so for "This and following events" or "All events" the rest of the
330
+ series moves when your events change, and the calendar keeps showing the change until then.
331
+
332
+ ### Deleting
333
+
334
+ The views don't delete events; your own UI does, with `proposeEventChange`. The change goes through
335
+ the same `onEventChange`, and `ask` uses the dialog's wording for a delete:
336
+
337
+ ```tsx title="team-calendar.tsx"
338
+ /** The selected occurrence's title, and a button that deletes it through `onEventChange`. */
339
+ function SelectedEvent({ occurrence }: { readonly occurrence: TeamOccurrence | undefined }) {
340
+ const { proposeEventChange } = Calendar.useCalendarActions();
341
+
342
+ return (
343
+ <div className="flex min-h-12 shrink-0 items-center gap-3 border-t px-4 py-2 text-sm">
344
+ {occurrence === undefined ? (
345
+ <span className="text-muted-foreground">Click an event to select it.</span>
346
+ ) : (
347
+ <>
348
+ <span className="min-w-0 truncate font-medium">{occurrence.event.title}</span>
349
+ <Button
350
+ className="ms-auto"
351
+ onClick={() => void proposeEventChange({ cause: "delete", eventId: occurrence.id })}
352
+ size="sm"
353
+ variant="outline"
354
+ >
355
+ Delete
356
+ </Button>
357
+ </>
358
+ )}
359
+ </div>
360
+ );
361
+ }
362
+ ```
363
+
364
+ ## Save the edit
365
+
366
+ A series edit lists its writes as plain data, so you can send it to a server as it is or apply it
367
+ to your own store. If your events are `RecurringCalendarEvent`s, `applyRecurrenceEdit` applies it
368
+ and returns the new array, as `onEventChange` above does. `createId` names the events it creates:
369
+ overrides, and the series a "This and following events" edit starts when you didn't pick its ID.
370
+
371
+ With your own event type or a database, write the same steps yourself:
372
+
373
+ | Field | What to write |
374
+ | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
375
+ | `series` | `"update"`: the master at `placement`, its first occurrence, with `recurrence` in place of the stored one. `"delete"`: remove the master. |
376
+ | `newSeries` | For "This and following events": a new master, copied from `from` apart from its ID, at `placement`, with `recurrence`, and `id` if you gave one. |
377
+ | `override` | The edited occurrence's override: `"create"` one from the master `from`, `"update"` the stored one, or `"delete"` it. |
378
+ | `otherOverrides` | Call `recurrenceOverrideEdit(edit, recurrenceId)` for each override of `seriesId` you store, loaded or not, and keep, delete or rekey it. |
379
+
380
+ The edit describes placement and recurrence only. If the change also edited the event's title or
381
+ other fields, copy them yourself. [The reference](./reference.md#recurrenceedit) describes
382
+ each write.
383
+
384
+ A "This event" delete adds the occurrence's start to the master's exception dates, which every
385
+ iCalendar store understands. Google's API records a deleted occurrence as a cancelled instance
386
+ instead; this package reads both.
387
+
388
+ ## Keep the selection
389
+
390
+ An occurrence's ID is its series' ID and its original start, such as
391
+ `standup::2026-10-14T07:30:00Z`. It's stable across views, time zones and reloads, and when "This
392
+ event" moves the occurrence, since its override keeps the original start.
393
+
394
+ "This and following events" and "All events" change the original starts, and so the IDs.
395
+ `edit.occurrenceIds` maps old IDs to new ones, and the handler above moves the selection and the
396
+ keyboard focus with it: select an occurrence in the preview, drag it with "All events", and it
397
+ stays selected.
398
+
399
+ - Control `focus` with `onFocusChange`, and map it before `onEventChange` returns. `ask` resolves
400
+ once the dialog has closed and focus is back on the occurrence, and the calendar then moves focus
401
+ to the occurrence under its new ID. Left alone, focus would name the old ID, which no longer
402
+ shows.
403
+
404
+ - Pass `occurrences`, the expansion you give the calendar, so the map covers every occurrence on
405
+ screen, not only the dragged one.
406
+ - Pass `newSeriesId` for "This and following events", so the map can name the new series'
407
+ occurrences. Pick it before you save, as you would for an optimistic create.
408
+ - Map anything else that holds occurrence IDs the same way, such as an open details panel or a URL.
409
+ - Read an occurrence's series from `occurrence.recurrence`, which keeps the series ID's type. Use
410
+ `parseOccurrenceId` only for IDs you stored.
411
+
412
+ ## Put it together
413
+
414
+ The whole calendar: the occurrences go to `events`, the handlers to `Root`, and the dialog renders
415
+ beside it. Clicks on events select them, through the `data-event-id` every view puts on its
416
+ events, and `SelectedEvent` is the component from [Deleting](#deleting).
417
+
418
+ ```tsx title="team-calendar.tsx"
419
+ "use client";
420
+
421
+ import {
422
+ eventIdOf,
423
+ weekRange,
424
+ type CalendarEventChange,
425
+ type CalendarFocus,
426
+ type CalendarSelection,
427
+ type EventId,
428
+ } from "@moltenship/calendar";
429
+ import {
430
+ applyRecurrenceEdit,
431
+ isRecurringChange,
432
+ recurrenceEditScopes,
433
+ resolveRecurrenceEdit,
434
+ type RecurrenceEditScope,
435
+ } from "@moltenship/calendar-recurrence";
436
+ import { useState, type MouseEvent } from "react";
437
+
438
+ import { calendarAnnouncements } from "@/components/calendar/announcements";
439
+ import { CalendarToolbar } from "@/components/calendar/calendar-toolbar";
440
+ import { useRecurrenceScopePrompt } from "@/components/calendar/recurrence-scope-dialog/use-recurrence-scope-prompt";
441
+ import { Button } from "@/components/ui/button";
442
+
443
+ import { adapters, Calendar, type TeamEvent, type TeamOccurrence } from "./recurrence-calendar";
444
+ import { useOccurrences } from "./use-occurrences";
445
+
446
+ type OccurrenceChange = CalendarEventChange<TeamOccurrence, string, string>;
447
+
448
+ /** A selection or focus on an occurrence, moved to the occurrence's new ID after an edit. */
449
+ function renamed<T extends CalendarSelection | CalendarFocus>(
450
+ current: T | null,
451
+ ids: ReadonlyMap<EventId, string>,
452
+ ): T | null {
453
+ return current?.kind === "event"
454
+ ? { ...current, eventId: ids.get(current.eventId) ?? current.eventId }
455
+ : current;
456
+ }
457
+
458
+ const weekRules = { firstDay: 1, minimalDays: 4, weekend: [6, 7] } as const;
459
+
460
+ interface TeamCalendarProps {
461
+ readonly initialEvents: readonly TeamEvent[];
462
+ readonly timeZone: string;
463
+ }
464
+
465
+ export function TeamCalendar({ initialEvents, timeZone }: TeamCalendarProps) {
466
+ const [today] = useState(() => Temporal.Now.plainDateISO(timeZone));
467
+ const [events, setEvents] = useState(initialEvents);
468
+ const [selection, setSelection] = useState<CalendarSelection | null>(null);
469
+ const [focus, setFocus] = useState<CalendarFocus | null>(null);
470
+ const { occurrences, onVisibleRangeChange } = useOccurrences(
471
+ events,
472
+ timeZone,
473
+ weekRange(today, { weekStartsOn: weekRules.firstDay }),
474
+ );
475
+ const { ask, dialog } = useRecurrenceScopePrompt();
476
+
477
+ async function onEventChange(change: OccurrenceChange) {
478
+ // A new event, or a change to a one-off event, needs no question.
479
+ let scope: RecurrenceEditScope = "this";
480
+ if (isRecurringChange(change)) {
481
+ const scopes = recurrenceEditScopes(change, adapters, { timeZone });
482
+ // None applies, so there's nothing to ask: tell the user why instead. Throwing rolls the
483
+ // change back.
484
+ if (scopes.length === 0) throw new Error("This repeating event can't change that way.");
485
+ const picked = await ask({
486
+ action: change.cause === "delete" ? "delete" : "edit",
487
+ eventTitle: change.event.event.title,
488
+ scopes,
489
+ });
490
+ // An `AbortError` is announced as a cancel, not as a change that couldn't be saved.
491
+ if (picked === null) throw new DOMException("Cancelled", "AbortError");
492
+ scope = picked;
493
+ }
494
+
495
+ const edit = resolveRecurrenceEdit(change, scope, adapters, {
496
+ // Picked now, so the IDs of a "following" edit's new series are known.
497
+ newSeriesId: crypto.randomUUID(),
498
+ occurrences,
499
+ // The zone the calendar moves occurrences on, so a series dragged by days keeps its time.
500
+ timeZone,
501
+ });
502
+ if (edit.type === "rejected") throw new Error(edit.message);
503
+
504
+ // Save the edit on your server here. The change stays pending until this function returns.
505
+ if (edit.type === "event") {
506
+ setEvents((current) => applyEventChange(current, edit.change));
507
+ return;
508
+ }
509
+ setEvents((current) =>
510
+ applyRecurrenceEdit(current, edit, { createId: () => crypto.randomUUID() }),
511
+ );
512
+ // "following" and "all" give the occurrences new IDs. The selection and keyboard focus
513
+ // follow them, and the calendar moves focus to the occurrence under its new ID.
514
+ setSelection((current) => renamed(current, edit.occurrenceIds));
515
+ setFocus((current) => renamed(current, edit.occurrenceIds));
516
+ }
517
+
518
+ // Apps open an event by delegating clicks on `[data-event-id]`.
519
+ function selectClicked(event: MouseEvent) {
520
+ const element = (event.target as Element).closest("[data-event-id]");
521
+ const eventId = element === null ? null : eventIdOf(element);
522
+ setSelection(eventId === null ? null : { eventId, kind: "event" });
523
+ }
524
+
525
+ const selected =
526
+ selection?.kind === "event"
527
+ ? occurrences.find((occurrence) => occurrence.id === selection.eventId)
528
+ : undefined;
529
+
530
+ return (
531
+ <>
532
+ <Calendar.Root
533
+ events={occurrences}
534
+ focus={focus}
535
+ onFocusChange={setFocus}
536
+ onEventChange={onEventChange}
537
+ onVisibleRangeChange={onVisibleRangeChange}
538
+ selection={selection}
539
+ onSelectionChange={setSelection}
540
+ defaultAnchorDate={today}
541
+ defaultTimeZone={timeZone}
542
+ locale="en-US"
543
+ weekRules={weekRules}
544
+ >
545
+ <Calendar.Frame className="flex h-full flex-col">
546
+ <CalendarToolbar calendar={Calendar} className="border-b" />
547
+ <Calendar.Viewport className="min-h-0 flex-1" onClick={selectClicked}>
548
+ <Calendar.ActiveView />
549
+ </Calendar.Viewport>
550
+ <SelectedEvent occurrence={selected} />
551
+ <Calendar.Announcer messages={calendarAnnouncements} />
552
+ </Calendar.Frame>
553
+ </Calendar.Root>
554
+ {dialog}
555
+ </>
556
+ );
557
+ }
558
+
559
+ /** A change to a one-off event, or a new event, as any calendar applies it. */
560
+ function applyEventChange(
561
+ events: readonly TeamEvent[],
562
+ change: CalendarEventChange<TeamEvent, string, string>,
563
+ ): readonly TeamEvent[] {
564
+ if (change.cause === "delete") return events.filter((event) => event.id !== change.eventId);
565
+ const { resourceIds: _resourceIds, ...placement } = change.proposed;
566
+ if (change.cause === "create") {
567
+ const id = crypto.randomUUID();
568
+ return [...events, { data: { color: "blue" }, id, title: "New event", ...placement }];
569
+ }
570
+ return events.map((event) =>
571
+ event.id === change.eventId
572
+ ? { data: event.data, id: event.id, title: event.title, ...placement }
573
+ : event,
574
+ );
575
+ }
576
+ ```
577
+
578
+ ## The dialog
579
+
580
+ The dialog shows one button per scope offered, always in the same order, then Cancel. Focus starts
581
+ on the narrowest scope offered, usually "This event".
582
+
583
+ | Key | What it does |
584
+ | -------------- | ------------------------------------------------------------------------ |
585
+ | Arrow keys | Move between the scopes, wrapping at the ends. Left and Right follow RTL |
586
+ | Tab, Shift+Tab | Move through the scopes and Cancel, and stay inside the dialog |
587
+ | Enter, Space | Pick the focused scope, or cancel |
588
+ | Escape | Cancel |
589
+
590
+ When it closes, focus goes back to where it was, such as the event, and only then does `ask`
591
+ resolve. Safari skips buttons on Tab unless a setting says otherwise, so the arrow keys reach every
592
+ scope there. The wording, English, is in `recurrence-scope.ts` beside the dialog, to edit or
593
+ translate.
594
+
595
+ ## Recipes
596
+
597
+ - [Google Calendar events](../guides/google-calendar.md): Read masters, changed and cancelled occurrences, and RRULE, EXDATE and RDATE lines from the Calendar API.
598
+ - [An ICS feed](../ics/feed.md#recurring-events): Group a parsed feed into series with recurringEventsFromIcs, and expand it.