`. Without it nothing
is announced. Picking up Standup and moving it down a slot, for example, reads:
1. "Picked up Standup, Thursday, October 8, 9:30 – 9:45 AM. Use the arrow keys to move it, then
Enter to drop it or Escape to cancel."
2. "Thursday, October 8, 9:45 – 10:00 AM"
3. "Moved Standup to Thursday, October 8, 9:45 – 10:00 AM." once `onEventChange` has saved it.
In a calendar with resources, picking up, moving and creating an event also name the resources it
books, from `Root`'s `resources`: "Moved Standup to Thursday, October 8, 9:45 – 10:00 AM, Orchid."
While moving, a step names them only when they change.
### Customize and localize them
The packages ship no text. `calendarAnnouncements` lives in `components/calendar/announcements.ts`
in your app once you add the UI source, so you can edit it in place. To translate it, write a
`CalendarAnnouncementMessages` object of your own, with one builder per phase:
| Phase | When | The update also has |
| -------- | -------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `start` | An event is picked up, or a create starts | `check`: what the policies say about `proposed`, or `null` with no answer yet (a keyboard move or resize that hasn't stepped, or an async policy) |
| `step` | Each arrow key, or each new slot under the pointer | `check`, as for `start` |
| `commit` | Your handler saved the change | `proposed`: the change as saved, and `warnings` |
| `reject` | A policy or your handler refused it, or the event is read-only | `reason`, such as `"read-only"`, and `error`: what your handler or a policy threw, if one did (an `AbortError` from your handler means the app cancelled) |
| `cancel` | Escape, Tab, leaving the view, or a drag dropped outside it | |
Each builder receives the update and a context, and returns the text to speak or `null` to stay
silent. The update has `cause` (`"move"`, `"resize-start"`, `"resize-end"`, or `"create"`),
`input` (`"keyboard"` or `"pointer"`), `event` (`null` while creating), and the `original` and
`proposed` placements. The context has `locale`, `timeZone`, `resourceTitle(resourceId)`, and
`formatRange(placement)`, which formats a placement as the drag preview labels it ("9:30 – 10:00 AM").
```tsx title="announcements-de.ts"
import type { CalendarAnnouncementMessages } from "@moltenship/calendar";
const titleOf = ({ event }: { readonly event: { readonly title: string } | null }) =>
event === null ? "Der neue Termin" : event.title;
export const announcementsDe: CalendarAnnouncementMessages = {
start: (update) =>
update.cause === "create"
? "Neuer Termin. Mit den Pfeiltasten verlängern, Eingabe zum Speichern."
: `${titleOf(update)} aufgenommen. Pfeiltasten zum Verschieben, Eingabe zum Ablegen.`,
step: ({ proposed }, { formatRange }) => (proposed === null ? null : formatRange(proposed)),
commit: (update, { formatRange }) => `${titleOf(update)}: ${formatRange(update.proposed)}.`,
reject: (update) =>
update.reason === "superseded" ? null : `${titleOf(update)} bleibt, wo er war.`,
cancel: () => "Abgebrochen.",
};
```
`formatRange` follows the calendar's `locale`. To change how ranges read, add an optional
`formatRange(placement, { locale, timeZone })` to your messages; the default is
`formatPlacementRange`. It labels the drag preview and becomes the context's `formatRange`, so it
changes spoken ranges only in builders that call that helper, as the German example does.
`calendarAnnouncements` spells dates out with `describeWhen` from `event-label.ts` instead; edit
that to change how its announcements read.
### Pointer gestures
The built-in views pass the same announcer to the pointer layer, so drags are announced by the same
messages and the drag preview labels ranges with the same `formatRange`. In your own views, do the
same:
```tsx
const announcer = useCalendarAnnouncer();
const pointerRef = useCalendarPointer({ announcer, events, onPropose, timeZone });
```
### Event names
Every event is a `
` named in full: "Standup, Thursday, October 8, 9:30 – 9:45 AM, Work
calendar, saving". The name leads with the title, then says when, where (the resource, in the
resource columns view), an optional detail, and whether a change is still saving. `useEventLabel` builds it in `registry/calendar/event-label.ts`, where the
English words live, so edit or translate them there. Pass `describeEvent: (event) => string` to a
view to add the detail, such as the calendar's name.
## ARIA patterns
| View | Pattern |
| ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Month | A `grid` labelled with the month ("October 2026"). A header `row` holds a `columnheader` per weekday, named in full. Each week is a `row` of seven `gridcell`s named by date and event count ("Thursday, October 8, 2026, 2 events"). A cell holds its date button and the events that start that day. "+N more" opens a dialog named "Events on Thursday, October 8, 2026". |
| Year | A `group` labelled with the year ("2026") holding a `grid` per month, labelled "October 2026". A header `row` holds a `columnheader` per weekday, named in full. Each week is a `row` of seven `gridcell`s: a day is named by date and event count ("Thursday, October 8, 2026, 2 events") with `aria-haspopup="dialog"`, and cells outside the month are empty. The twelve grids share one tab stop. A day's events open in a dialog named "Events on Thursday, October 8, 2026". |
| Week and day | A `grid` labelled with the range ("Oct 4 – 10, 2026") with three rows: a header row of `columnheader`s (the time zone, then each day); the all-day row, led by an "All day" `rowheader` that also holds the expand toggle (`aria-expanded`), with a `gridcell` per day; and the timed row, led by a "Timed events" `rowheader`, with a `gridcell` per day. Hour labels, including those of [secondary time zones](https://time.molten.sh/docs/react/views/week-and-day.md#secondary-time-zones), are hidden from assistive tech. The focused slot renders as a `button` named "Thursday, October 8 at 9:30 AM", followed by its time in each secondary time zone; the other slots aren't elements at all. |
| Resource columns | A `grid` labelled with the range, with `aria-colcount` and an `aria-colindex` on every cell, since only the columns in view render. A header `row` has a `columnheader` per resource, named with its groups ("Maya, Design"), and a group's header holds its collapse toggle (`aria-expanded`). Then the all-day and timed rows, as in the week view, with each cell, slot and event named with its resource ("Maya, Thursday, October 8 at 9:30 AM"). |
| Resource timeline | A `grid` labelled with the range ("Oct 5 – 11, 2026" or "October 2026"). A header `row` holds a "Resources" `columnheader` and one per hour or day, named in full. Each resource is a `row` named by the resource, led by a `rowheader` with its name (and a group's expand toggle, `aria-expanded`, out of the tab order), then a `gridcell` per slot named by resource, time, and event count ("Orchid, Monday, October 5, 2026, 2 events"). `aria-rowcount` and `aria-colcount` count every resource and slot, though only those in view render. The focused cell renders a `button` with the same name. |
| Agenda | An `` labelled with the range, with one `` per day and a `` of its events. Only the days in view render, so each day has `aria-posinset` and `aria-setsize`. A range without events is a focusable group named "No events". The scrolling agenda is the same list. |
All views share these:
- **One tab stop** with a roving `tabIndex`: only the focused day, slot, or event has
`tabIndex={0}`. The header's "Open date" buttons and the all-day row's expand toggle are out of
the tab order; Shift+Enter and focusing a hidden event do their job.
- **Today** is marked `aria-current="date"`.
- **Events** are ``s with the full names above. Events with a pending change have
`aria-busy`.
- **Focus** shows as a solid 2px `outline-ring` outline, which stays visible in forced-colors mode.
A focused event rises above its neighbours.
The mini month in `registry/calendar` is a separate `grid` of date buttons: arrow keys move by a
day or a week, and Page Up and Page Down by a month.
### Checked in CI
`vp run a11y` runs [axe-core](https://github.com/dequelabs/axe-core) in Chromium over every built-in
view, the toolbar and mini month, and the demo's main screens, in light and dark, and fails on any
serious or critical WCAG 2.2 A/AA or best-practice violation. It exempts four rules, each only on
specific elements:
- **Label in name**, for events and day cells: a chip shows an abbreviated subset of its name
("9:30 AM Standup"), and a day cell is named by its date and event count because its events are
focused separately. Event names lead with the title, so speech input still matches it.
- **Target size**, inside the month and time grids, where an event's box is its time span (WCAG
2.5.8's "essential" exception).
- **Hidden focusable elements**, for Base UI's focus guards, which pass focus straight on. The
demo's own shadcn components still use Base UI.
- **Command name**, for the same focus guards in WebKit, where Base UI makes them unnamed buttons
on purpose, so its focus trap catches VoiceOver's cursor instead of letting it leave a popup.
`vp run browsers` runs the same checks in Firefox and WebKit (WebKit alone on macOS 27, where
Playwright's Firefox doesn't start), except the reduced-motion tests, which run in Chromium.
On touch screens, month events and "+N more" are 24 px tall; with a mouse they stay 20 px. A test
emulates a 375 px touch screen in Chromium and checks that every target in the day, 3-day, month,
year, agenda and resource views is at least 24 px, or spaced as WCAG 2.5.8 allows. It leaves out:
- timed events in the time grids, whose height is their time span, the exception above: a
15-minute event is 12 px tall;
- annotation marks, which are still 12–20 px wide (#219);
- the week view, whose seven columns are too narrow for its events on a phone. Offer the 3-day view
there.
A separate test checks the [theme](https://time.molten.sh/docs/react/theming.md) against WCAG AA in both color schemes: event text
on every event color, the today marker, the now line, and the focus ring. If you override `--ring`,
keep it at 3:1 or more against your background, even at 50% opacity. shadcn's default light ring is
about 1.5:1 at 50%.
## Reduced motion
When the system asks for reduced motion (`prefers-reduced-motion: reduce`), the calendar theme:
- fades popovers, dialogs, and tooltips in and out without zooming or sliding;
- fades sheets without sliding them in;
- keeps transitions off the drag preview;
- crossfades view transitions in place instead of moving them.
The rules come with the `calendar-theme` item, which adds them to your global CSS, because the
registry views use shadcn's own popover, select, and tooltip, which you install from shadcn.
## Right-to-left
Right-to-left takes two settings: `dir="rtl"` on an ancestor of the calendar, such as ``,
for the layout, and `direction="rtl"` on `Root` for the keys. `Root` doesn't read the page's
`dir`, so set both.
```tsx
```
The month, week, day, and agenda views then mirror: days run from right to left, the hour gutter
moves to the right, events put their accent edge on the right, continuation chevrons point the way
the event continues, and the toolbar's arrows turn around. ← and → follow the layout, so ← moves to
the next day, which an RTL grid shows on the left, and a picked-up event moves the same way. The
views use logical CSS properties throughout (`ms-*`, `border-s`, `start-*`), so your own edits
should too.
## In your own views
[Custom views](https://time.molten.sh/docs/react/views/custom-views.md) get the same keyboard support from three pieces:
- **`getSpatialNavigation`** on the view's strategy says where each key moves focus. Reuse
`monthSpatialNavigation`, `yearSpatialNavigation`, `timeGridSpatialNavigation`, or
`listSpatialNavigation`, or write your own.
- **`useCalendarKeyboard(options)`** returns `onKeyDown` and `onBlur` handlers. Spread them on the
element around the view.
- **`useRovingFocus(focus)`** returns the props for one focusable day (`{ kind: "day", date }`),
slot, or event (`{ kind: "event", date, eventId }`), including its `tabIndex`.
`useCalendarInteraction()` returns the keyboard gesture in progress, for drawing a create's draft
or tinting the cells it covers.
# Testing
Test the calendar you built with a fixed clock, typed builders, a render harness, and keyboard and pointer drivers.
Source: https://time.molten.sh/docs/react/testing
`@moltenship/calendar-testing` tests the calendar your app builds: your copies of the registry
views, your policies and the code that saves changes. It renders your `Root` with a fixed clock,
time zone and locale, owns the events the way your app's state would, records what the calendar
tells your app, and drives it with the keyboard and the pointer as a person would.
It uses only the public API of `@moltenship/calendar` and `@moltenship/calendar-recurrence`, and
depends on no test runner. The examples here use [Vitest](https://vitest.dev) with jsdom; happy-dom
works too, and pointer tests run in [Vitest's browser mode](#pointer-and-touch).
## Install
```bash
pnpm add -D @moltenship/calendar-testing vitest jsdom
```
Its peer dependencies are the four packages a 2.0 app already has: `react` and `react-dom` 19, which
the harness renders and hydrates with, and `@ui-sdk/core` and `@ui-sdk/react`, which the calendar's
parts are built on. See [Installation](https://time.molten.sh/docs/react/installation.md) if the app doesn't have them yet.
## Set up Vitest
Run the tests in a DOM environment:
```ts title="vitest.config.ts"
import { defineConfig } from "vitest/config";
export default defineConfig({
test: { environment: "jsdom", setupFiles: ["./tests/setup.ts"] },
});
```
Node.js 26 and later have `Temporal`. On an older runtime, or a browser without it, install the
polyfill in the setup file, as the app does. The package never installs one itself, and its helpers
throw an error that says so when `Temporal` is missing.
```ts title="tests/setup.ts"
if (!("Temporal" in globalThis)) await import("temporal-polyfill/global");
```
The registry's controls are ui-sdk's, which read paint timing, measure toasts and wait for
transitions, none of which jsdom has. jsdom's stylesheet also hides every popup that isn't
`:popover-open`, which nothing matches without the Popover API. A test that renders them adds
these to the setup file:
```ts title="tests/setup.ts"
performance.getEntriesByType ??= () => [];
globalThis.ResizeObserver ??= class {
disconnect() {}
observe() {}
unobserve() {}
};
Element.prototype.getAnimations ??= () => [];
// ui-sdk marks an open popup `data-open`; jsdom weighs its rules by specificity alone.
const popups = document.createElement("style");
popups.textContent = "[popover][data-open] { display: block !important; }";
document.head.append(popups);
```
The harness turns on React's `IS_REACT_ACT_ENVIRONMENT` flag when it first renders, unless your
setup set it already.
## A fixed clock and zone
The calendar reads the current time only from `Root`'s `now` or `clock`, and the time zone from
`timeZone` or `defaultTimeZone`; `locale` and `weekRules` are required props. So a test makes it
deterministic through props, without faking timers or patching `Temporal.Now`.
`createTestEnvironment(options?)` fixes all of them. Its defaults are Thursday, 8 October 2026 at
noon UTC, US English, weeks from Monday, and left to right.
```ts
const environment = createTestEnvironment({ timeZone: "Europe/Berlin" });
environment.now; // 2026-10-08T12:00:00Z, a Temporal.Instant
environment.today; // 2026-10-08, now's date in the zone
environment.at("09:00"); // 09:00 today in Berlin: 2026-10-08T07:00:00Z
environment.at("2026-10-26T09:00"); // a wall time in Berlin, after the clocks go back
environment.rootProps; // { now, defaultTimeZone, locale, weekRules, direction, defaultAnchorDate }
```
`at` reads a time alone on the environment's own date, `today`, however far the calendar has moved.
| Option | Default |
| ------------ | -------------------------------------------------------------------------- |
| `now` | `"2026-10-08T12:00:00Z"`; text without a zone is a wall time on `timeZone` |
| `timeZone` | `"UTC"` |
| `locale` | `"en-US"` |
| `weekRules` | `{ firstDay: 1, minimalDays: 4, weekend: [6, 7] }` |
| `direction` | `"ltr"` |
| `anchorDate` | `today` |
To show a later time, call the harness's `setNow`: the calendar re-renders with it at once. To let
time pass as an app's clock does, pass `createTestClock(start)` as the harness's `clock` option, or
`Root`'s `clock` in your own render, and move it with `set` or `advance`. The calendar samples a
clock once a minute, so move fake timers with it. A clock reads text without a zone as UTC.
## Builders
Builders make records in the canonical shape `createCanonicalEventAdapter` reads. Every field has
a default, so a test names only what it's about. Text times without a zone are wall times on the
event's `timeZone`, UTC by default, and `timeZone` becomes the event's `sourceTimeZone`.
| Builder | Makes |
| ------------------------------ | -------------------------------------------------------------------------------------------- |
| `buildEvent(input?)` | A timed event: an hour at 09:00 on the default date. `start` with `end` or `duration` |
| `buildAllDayEvent(input?)` | An all-day event: `start` with `end` (exclusive) or `days` |
| `buildResource(input?)` | A `CalendarResource`, with `timeZone`, `parentId` and `availability` |
| `buildRecurringEvent(input)` | A timed series for `@moltenship/calendar-recurrence`: `rule` as RRULE text, `exceptionDates` |
| `withRecurrence(event, input)` | Makes any event, all-day ones too, the master of a series |
| `buildAvailability(input?)` | Working hours: `days`, `hours` such as `"09:00-17:00"`, `exceptions`; 9 to 5 on weekdays |
An event's `id` defaults to its title and its title to its ID, so `buildEvent({ title: "Standup" })`
is the event `"Standup"`.
## Render a calendar
Create your calendar as the app does, then render it with `renderCalendar`. Clean up after each
test.
```tsx title="calendar.test.tsx"
import {
createCalendar,
createCanonicalEventAdapter,
type CalendarEvent,
} from "@moltenship/calendar";
import {
buildEvent,
cleanup,
createTestEnvironment,
hydrateCalendar,
renderCalendar,
} from "@moltenship/calendar-testing";
import { createAgent } from "@ui-sdk/react/agent";
import { calendarAnnouncements } from "@/components/calendar/announcements";
import { createWeekView } from "@/components/calendar/time-grid-view/time-grid-view";
type Meeting = CalendarEvent;
const Calendar = createCalendar()({
eventAdapter: createCanonicalEventAdapter(),
views: [createWeekView()],
});
// Unmounts every calendar a test rendered.
afterEach(cleanup);
```
`afterEach`, `expect` and `test` come from `vitest`.
`renderCalendar(Calendar, options)` renders `Root` with the environment's props inside `act`, and
` ` inside it. It owns the events: a change your calendar saves is applied to
them, so the next render shows it, as your app's state would.
```tsx title="calendar.test.tsx"
const environment = createTestEnvironment({ timeZone: "Europe/Berlin" });
const standup = buildEvent({ title: "Standup", start: environment.at("09:00") });
test("a saved move reaches onEventChange and the events", async () => {
const calendar = await renderCalendar(Calendar, {
environment,
events: [standup],
messages: calendarAnnouncements,
});
await calendar.propose({
cause: "move",
eventId: "Standup",
proposed: {
kind: "timed",
start: environment.at("10:00"),
end: environment.at("10:30"),
},
});
expect(calendar.changes.map((change) => change.cause)).toEqual(["move"]);
expect(calendar.results[0]?.result.status).toBe("committed");
expect(String(calendar.events()[0]?.start)).toBe("2026-10-08T08:00:00Z");
});
```
| Option | Effect |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `events` | The events the calendar starts with |
| `view` | The view it opens on; the first registered one by default |
| `environment` | `createTestEnvironment()` by default |
| `clock` | A clock to read the time from instead of the environment's fixed `now` |
| `resources` | `Root`'s `resources` |
| `onEventChange` | Called with each change before the harness applies it. Return a promise to keep the change pending; throw or reject to roll it back |
| `onEventChangeResult` | Called with each result after the harness records it |
| `applyChange` | Applies a saved change to your events. The default, `applyCanonicalChange`, needs canonical events; pass your own for your app's records |
| `createEvent` | The record a created event gets, from the change and a free `new-` ID; the proposed placement goes over it. `{ id, title: "New event", data: null }` by default |
| `readOnly` | Renders `Root` without `onEventChange` |
| `messages` | Renders ` ` |
| `rootProps` | Any other `Root` prop, such as `policies` or `availability` |
| `children` | What `Root` renders instead of ` ` |
| `wrapper` | A component around the calendar, such as a provider |
| `strictMode` | Renders in `StrictMode` |
| `container` | Where to render; a new element in `document.body` by default, which unmounting removes |
| `identifierPrefix` | `useId`'s prefix |
The harness it returns:
| Member | Contents |
| --------------------------------- | ------------------------------------------------------------------------------------ |
| `container` | The element the calendar rendered into |
| `changes` | Every change `onEventChange` received, in order |
| `results` | Every `onEventChangeResult` call: `{ result, detail }` |
| `diagnostics` | What `onDiagnosticsChange` last reported |
| `events()` | The events now, with every saved change applied |
| `state()`, `meta()` | `useCalendarState()` and `useCalendarMeta()`, read from inside `Root` |
| `pendingChanges()` | `useCalendarPendingChanges()`: changes still validating, saving or awaiting events |
| `actions`, `act(callback)` | The calendar's actions, and a way to call them inside `act` |
| `propose(proposal)` | `proposeEventChange` inside `act`; resolves with its result once it settles |
| `setEvents`, `setNow`, `rerender` | Change the events, the fixed `now`, or the options that apply after the first render |
| `unmount()` | Unmounts it; `cleanup()` unmounts every one |
`setNow` takes exact text, a wall time on the environment's zone, or a time such as `"10:00"` on
the calendar's current date. `rerender` changes the events, the handlers, `children`, `messages`,
`resources`, `readOnly` and `rootProps`; the view, the environment, the wrapper and the container
set up the first render. Change the view or date through `act`, as a person would:
`await calendar.act((actions) => actions.setView("day"))`. Change the locale, week rules or
direction through `rootProps`: `await calendar.rerender({ rootProps: { locale: "de-DE" } })`.
Name the harness type with `CalendarHarnessFor`.
## Saves that take time
When `onEventChange` returns a promise, the calendar shows the change as pending until it settles.
Hold the promise in the test to check what the calendar shows meanwhile.
```tsx title="calendar.test.tsx"
test("a slow save stays pending, then settles", async () => {
let finish = () => {};
const calendar = await renderCalendar(Calendar, {
environment,
events: [standup],
onEventChange: () => new Promise((resolve) => (finish = resolve)),
});
// Propose through act without waiting for the save, which the test holds.
let saving: ReturnType | undefined;
await calendar.act((actions) => {
saving = actions.proposeEventChange({
cause: "move",
eventId: "Standup",
proposed: { kind: "timed", start: environment.at("11:00"), end: environment.at("12:00") },
});
});
expect([...calendar.pendingChanges().values()].map(({ phase }) => phase)).toEqual(["saving"]);
await calendar.act(() => finish());
expect((await saving)?.status).toBe("committed");
expect(calendar.pendingChanges().size).toBe(0);
});
```
## Changes an agent makes
An [agent](https://time.molten.sh/docs/react/agents.md) acts on the calendar through a bridge, and its changes take the same path
as a person's. Test them with the real bridge: no model is involved, since a step is a plain object.
```tsx title="calendar.test.tsx"
test("an agent's move is saved like a person's, and says who asked", async () => {
const agent = createAgent();
const calendar = await renderCalendar(Calendar, {
environment,
events: [standup],
// An agent finds a calendar by its name, on the frame.
rootProps: { label: "Team calendar" },
children: (
),
});
const outcome = await calendar.act(() =>
agent.act({
steps: [
{
ref: "Team calendar",
action: "moveEvent",
// One object per action. The event's ID is what `listEvents` gives the agent.
args: [{ eventId: standup.id, start: "2026-10-08T11:00" }],
},
],
}),
);
await calendar.settled();
// The step returns the change, and the harness saved it at once.
expect(outcome.steps[0]?.result).toMatchObject({ cause: "move", status: "saved" });
expect(calendar.changes.map((change) => change.cause)).toEqual(["move"]);
expect(calendar.results[0]?.detail.input).toBe("agent");
expect(calendar.placementOf("Standup").wallRange).toBe("2026-10-08T11:00/2026-10-08T12:00");
});
```
Three things make it work:
- **A name and a frame.** The bridge lists a calendar that renders `Calendar.Frame`, and finds it
by the `label` on `Root`. The harness renders ` ` alone by default, so pass
the frame as `children`.
- **`calendar.act`.** The agent's steps change React state, so they run inside `act` like any
other change.
- **`calendar.settled()`.** A step returns the change with its `status`: `"saved"` when the handler
saved at once, as the harness does by default, and `"saving"` when the handler returned a
promise. `settled()` waits for every save before the test reads `results`.
`results[n].detail.input` is `"agent"` for these changes, which is how an app's handler, a policy
and the history tell them from a person's.
## Find what the calendar shows
Queries find events through the calendar's own events, by ID, title or start, so they don't
depend on the text a view renders or its language. Cells are found by the attributes every
registry view carries for the pointer layer: `data-event-id` on events, `data-date` on day cells
and time columns, `data-all-day` on a time grid's all-day cells, `data-axis="inline"` on a
timeline's time strips, and `data-resource-id` on a resource's column or row. A view of your own
that follows the [same contract](https://time.molten.sh/docs/react/interactions.md#in-your-own-views) works the same way: a
`data-date` element without `data-all-day` counts as a time column, and in a time grid, events sit
inside their column.
```tsx title="calendar.test.tsx"
test("queries find events by title, and cells by date", async () => {
const calendar = await renderCalendar(Calendar, { environment, events: [standup] });
const event = calendar.getEvent("Standup");
expect(calendar.getTimeColumn("2026-10-08").contains(event)).toBe(true);
expect(calendar.queryEvent("Lunch")).toBeNull();
// A slot exists only while it has focus, so the keyboard driver focuses it.
await calendar.keyboard.focusCell({ date: "2026-10-08", time: "14:00" });
expect(document.activeElement?.getAttribute("aria-label")).toBe("Thursday, October 8 at 2:00 PM");
});
```
| Query | Returns |
| -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| `getEvent(event)` | The first element showing an event |
| `getAllEvents(event)` | Every element showing it: one per part the view draws, such as a time grid's day, a month's week row, a resource's column |
| `queryEvent(event)` | The first element, or `null` when the view doesn't show it |
| `getDayCell(date, { resourceId? })` | A time grid's all-day cell, or else a month's day |
| `getTimeColumn(date, { resourceId? })` | The column of a date's hours, or its strip along a timeline row |
| `getResource(resource)` | The element a resource's column or row carries its ID on; `resource` is an ID, `null` for the unassigned row, or `{ title }` |
| `placementOf(event)` | Where it shows now, pending changes included, as text: `range`, `wallRange`, `isPending` |
`event` is an ID or a title as text (an ID wins), or `{ id }`, `{ title }` or `{ start }`. A
`start` is a date for an all-day event, a date and time for a floating one, or a time for a timed
one, exact or on the calendar's wall clock. The `get` queries throw a `CalendarQueryError` that
lists the calendar's events when they find nothing, and every query throws when it finds several
events. `placementOf` gives text, such as `"2026-10-09T08:30:00Z/2026-10-09T09:30:00Z"`, which
reads plainly in a failing assertion; `wallRange` gives the same ends on the display zone's clock,
to the minute.
## Keyboard
`calendar.keyboard` presses keys on the focused element inside `act`, as a person would, so it
works in jsdom, happy-dom and a browser alike, and through every check your views make. Focus
goes through the calendar's own focus, as arrow keys move it, so a slot, which renders only while
it has focus, can take it too.
```tsx title="calendar.test.tsx"
test("Space, arrow keys and Enter move the standup a day on and half an hour later", async () => {
const calendar = await renderCalendar(Calendar, {
environment,
events: [standup],
messages: calendarAnnouncements,
});
// Focus the event, Space, two slots down and a day across, then Enter.
await calendar.keyboard.moveEvent("Standup", { across: 1, down: 2 });
await calendar.settled();
expect(calendar.placementOf("Standup").wallRange).toBe("2026-10-09T09:30/2026-10-09T10:30");
expect(calendar.lastAnnouncement()).toBe("Moved Standup to Friday, October 9, 9:30 – 10:30 AM.");
expect(calendar.results[0]?.detail.input).toBe("keyboard");
});
```
| Method | Keys |
| ------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
| `focusEvent(event, { date?, resourceId? })` | Focuses the event's part on `date`, by default the day it starts or the first day shown, in `resourceId` |
| `focusCell({ date, time?, resourceId? })` | Focuses a day, or a slot with `time` |
| `press(key, modifiers?)`, `arrows({ up, down, left, right })` | Any key on whatever has focus, or arrow keys by count |
| `step({ across, down })` | Arrow keys by direction |
| `grab()`, `grabEdge()` | Space picks up the focused event or starts a create; Shift+Space picks up its end, and again its start |
| `drop()`, `cancel()` | Enter and Escape |
| `moveEvent(event, { across?, down?, date?, resourceId? })` | Focus, Space, the steps, Enter |
| `resizeEvent(event, { edge?, across?, down?, date?, resourceId? })` | Focus, Shift+Space (twice for the start), the steps, Enter |
| `createEvent(cell, steps?)` | Focus the cell, Space, the steps, Enter |
The focus methods throw when the view doesn't show what they name, and leave the calendar's focus
as it was. A step `across` goes toward the end of the line: Arrow Right in a left-to-right
calendar, Arrow Left in a right-to-left one, from `Root`'s `direction`. A step `down` is Arrow
Down; negative steps go back and up. What a step is depends on the view:
| View | `across` | `down` |
| ----------------- | ---------------------------------------------- | ----------------------------- |
| Week, day | A day | A slot, 15 minutes by default |
| Month | A day | A week |
| Resource columns | A column: the next resource, then the next day | A slot |
| Resource timeline | A slot, or a day over days | The next resource |
## Wait for saves
Drivers return once their keys or moves are handled, not when the change is saved. `settled()`
waits until no change is pending: every proposal validated, saved, and in the events. It gives up
after five seconds of real time, and says which changes are still pending. It doesn't advance fake
timers, so a save that waits on one needs them advanced first.
`announcements()` lists what the `Announcer` said, oldest first, a message said twice included,
and `lastAnnouncement()` what it says now, with `Intl`'s thin and no-break spaces made plain.
Render one with the `messages` option, or your own in `children`: only the one mounted last
speaks, and the harness follows whichever does. `normalizeText(text)` makes your own text plain
the same way.
## Pointer and touch
`calendar.pointer` drags with Pointer Events at measured points, as a mouse, a pen or a finger
would. It needs a page that's laid out and real timers, so it runs in a browser:
```ts title="vitest.config.ts"
import { defineConfig } from "vitest/config";
import { playwright } from "@vitest/browser-playwright";
export default defineConfig({
test: {
browser: {
enabled: true,
provider: playwright(),
instances: [{ browser: "chromium" }],
},
},
});
```
```tsx title="calendar.browser.test.tsx"
test("a mouse moves the standup to Friday at 11:00", async () => {
const calendar = await renderCalendar(Calendar, {
// Give the calendar a height, as the app's layout does.
children: (
),
events: [standup],
});
await calendar.pointer.moveEvent("Standup", { date: "2026-10-09", time: "11:00" });
await calendar.settled();
expect(calendar.placementOf("Standup").range).toBe("2026-10-09T11:00:00Z/2026-10-09T12:00:00Z");
});
```
| Method | Drag |
| ------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `moveEvent(event, { date, time?, resourceId? })` | By the event's middle, so it starts at `time` on `date`; without `time`, by whole days, keeping its time. It stays in its resource unless `resourceId` names another |
| `resizeEvent(event, { date, time?, edge? })` | Its end (or start) handle to `time`, or to `date` in a view that resizes by days, as a timeline over days does |
| `createEvent(from, to)` | Across empty slots or days, both included |
| `drag(from, to)` | From one element or point to another |
Each takes `{ pointerType }`: `"mouse"` by default, `"pen"`, or `"touch"`, which holds still
until the long press starts a drag. The press and the drop must be on screen: the drivers scroll
the event into view, and throw when its middle is covered or when the drop point isn't on its cell,
so make the calendar tall enough. Where they let go is measured again after each frame, so a view
that auto-scrolls under the pointer still gets the drop where it was meant. The repository runs
these drivers on its views in Chromium on every pull request, and in Firefox and WebKit, WebKit on
`temporal-polyfill`, in the full gate.
### What jsdom can't do
jsdom and happy-dom don't lay pages out: every element is an empty box at the top left, and
nothing scrolls. So in them:
- the pointer drivers throw a `PointerLayoutError` that says to use a browser;
- views measure nothing, so anything that depends on sizes, such as virtualized resource columns
past the first screen, auto-scroll at an edge, or which part of a scrolling view is visible,
isn't there to test;
- CSS doesn't apply: hidden, clipped and focus-visible states are classes, not what's shown.
Keyboard drivers, queries, the harness, saves and announcements work in all three.
## Fixtures
Fixtures are ready datasets for contract tests: tests that every view, or your custom one, should
pass on the same data. Each is a function that builds new records, with the environment,
resources and `Root` props it's meant for, so spreading it into the harness's options renders it.
Merge `rootProps` when you pass your own. Their events are canonical, with `data: { group }`, so
type your calendar with `FixtureEvent` and `FixtureResource`.
```tsx title="calendar.test.tsx"
import { dstWeekFixture, type FixtureEvent } from "@moltenship/calendar-testing";
const FixtureCalendar = createCalendar()({
eventAdapter: createCanonicalEventAdapter<{ readonly group: string }>(),
views: [createWeekView()],
});
test("a move a day on keeps an event's wall time across the clocks going back", async () => {
// New York's week of Sunday 1 November 2026, with a 09:00 standup every day.
const calendar = await renderCalendar(FixtureCalendar, { ...dstWeekFixture(), view: "week" });
// `d6` is Saturday's standup; a day on is Sunday, after the change.
await calendar.keyboard.moveEvent("d6", { across: 1 });
await calendar.settled();
expect(calendar.placementOf("d6").wallRange).toBe("2026-11-01T09:00/2026-11-01T09:30");
});
```
| Fixture | Data |
| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `denseDayFixture()` | Thursday 8 October 2026 in UTC: 30 timed events, from back-to-back half hours that overlap nothing to five at once at 13:00 and a staircase, two across midnight, and 3 all-day events |
| `dstWeekFixture({ change? })` | New York's week to Sunday 1 November 2026, when the clocks go back, or with `change: "spring"` to 8 March, when they go forward: a 09:00 standup a day, an event in the changing hour, one across the change |
| `resourceDayFixture()` | A team in three zones, one with hours of its own, and rooms under a parent that opens expanded; events on one resource, on several, and on none; working hours from 9 to 6 |
| `multiZoneSeriesFixture()` | Series in Berlin, Los Angeles and Tokyo from 19 October 2026, across Berlin's and Los Angeles' DST changes a week apart |
Each fixture's JSDoc lists its events and resources by ID, title and time. Those, and the counts,
are part of the API: they change only in a major version, so tests can name them.
`multiZoneSeriesFixture` gives series masters, `series`, not events: a calendar shows a series
once it's expanded into occurrences, as your app does with `@moltenship/calendar-recurrence`.
```tsx title="calendar.test.tsx"
import {
createCanonicalRecurrenceAdapter,
createOccurrenceAdapter,
createOccurrenceExpander,
type RecurrenceOccurrence,
} from "@moltenship/calendar-recurrence";
import { multiZoneSeriesFixture, type FixtureSeriesEvent } from "@moltenship/calendar-testing";
type Occurrence = RecurrenceOccurrence;
const SeriesCalendar = createCalendar()({
eventAdapter: createOccurrenceAdapter(createCanonicalEventAdapter<{ readonly group: string }>()),
views: [createWeekView()],
});
test("Berlin's standup is an hour later in UTC once its clocks go back; Los Angeles' isn't yet", async () => {
const { environment, series } = multiZoneSeriesFixture();
const week = {
end: Temporal.PlainDate.from("2026-11-02"),
start: Temporal.PlainDate.from("2026-10-26"),
};
const { occurrences } = createOccurrenceExpander(
createCanonicalRecurrenceAdapter<{ readonly group: string }>(),
).expand(series, { range: week, timeZone: environment.timeZone });
const calendar = await renderCalendar(SeriesCalendar, {
environment,
events: occurrences,
// Occurrences are views of their series: save changes through the recurrence edits instead.
readOnly: true,
rootProps: { defaultAnchorDate: week.start },
view: "week",
});
expect(calendar.placementOf({ start: "2026-10-26T08:00:00Z" }).title).toBe("Standup (Berlin)");
expect(calendar.placementOf({ start: "2026-10-27T17:00:00Z" }).title).toBe(
"Review (Los Angeles)",
);
});
```
## Server rendering and hydration
`hydrateCalendar` takes the same options. It renders the calendar with `renderToString`, puts the
markup in a container and hydrates it, then returns the same harness, with the markup as
`serverMarkup`. When the client renders something else, it throws a `HydrationMismatchError` with
React's reasons: a recoverable error, or a warning such as an attribute that differs, which React
only logs. It watches the console for those while hydration runs, so test with React's development
build, which logs them. A component that throws on the client fails the test with its error, and
nothing stays mounted. A fixed `now` renders today's date on the server too, so a calendar with
one hydrates with nothing to patch.
```tsx title="calendar.test.tsx"
test("the week renders on the server and hydrates without a mismatch", async () => {
// Throws a HydrationMismatchError when the client renders something else.
const calendar = await hydrateCalendar(Calendar, { environment, events: [standup] });
expect(calendar.serverMarkup).toContain("Standup");
});
```
The server render runs in the test's DOM environment, so code that checks for `window` takes its
browser branch there too. To test a real server boundary, render with `react-dom/server` in a
Node environment and hydrate in another, as the repository's SSR fixture does.
# Next.js and server rendering
Fetch events in a Server Component and render the same calendar on the server and in the browser.
Source: https://time.molten.sh/docs/react/guides/nextjs
Time works with any React 19 framework that renders on the server. This guide uses the Next.js App
Router. The same rules apply elsewhere.
## Calendars are Client Components
Calendar state lives in React state, so `createCalendar`, `defineCalendarView`, and the components
are client-only. Put your calendar, its views, and `Root` in files that start with `"use client"`,
as the [Quick start](https://time.molten.sh/docs/react/quick-start.md) does. Server Components can render those components and pass
them props.
The rest of `@moltenship/calendar` works on the server too. A Server Component can import the
Temporal helpers or build a snapshot, for example to filter events before sending them.
## Send strings, not Temporal objects
Props from a Server Component to a Client Component must be serializable. Temporal objects aren't,
so send ISO 8601 strings and turn them into Temporal values in the client:
```tsx title="team-calendar.tsx"
// app/calendar/team-calendar.tsx
"use client";
import { useMemo } from "react";
import { Calendar, weekRules, type Meeting } from "./quick-start";
// A Meeting with its times as ISO 8601 strings.
export type MeetingJson = Omit & {
readonly start: string;
readonly end: string;
};
interface TeamCalendarProps {
readonly meetings: readonly MeetingJson[];
readonly now: string;
readonly timeZone: string;
}
export function TeamCalendar({ meetings, now, timeZone }: TeamCalendarProps) {
const events = useMemo(
() =>
meetings.map((meeting): Meeting => ({
...meeting,
start: Temporal.Instant.from(meeting.start),
end: Temporal.Instant.from(meeting.end),
})),
[meetings],
);
const nowInstant = Temporal.Instant.from(now);
return (
Previous
Today
Next
);
}
```
`useMemo` keeps the converted array stable between renders, so the calendar only re-reads events
when `meetings` actually changes.
The page fetches the data on the server:
```tsx title="page.tsx"
// app/calendar/page.tsx (a Server Component)
import { TeamCalendar, type MeetingJson } from "./team-calendar";
async function getMeetings(): Promise {
// Replace with your database or API call. Return ISO 8601 strings, not Temporal objects.
return [
{
id: "standup",
title: "Standup",
color: "blue",
start: "2026-10-08T07:00:00Z",
end: "2026-10-08T07:15:00Z",
},
];
}
export default async function CalendarPage() {
const meetings = await getMeetings();
return (
);
}
```
## Match the server and the browser
During server rendering and hydration, Time doesn't read the clock, the host time zone, or `window`.
Everything that affects the first render comes from props, so the server and the browser produce the
same markup as long as they get the same props. In practice:
- **Compute "now" once on the server** and pass it down, as `now` above. Calling
`Temporal.Now.instant()` in a Client Component gives the server and the browser different values.
Without `now`, anything that depends on the current time (a view's `today`, `useNow()`) is empty
on the server and fills in after hydration. A fixed `now` also stops the clock, so the
[App Router example](https://time.molten.sh/docs/react/guides/nextjs-app-router.md#the-calendar) passes it only while the page
hydrates.
- **Choose the time zone on the server**, for example from the user's profile or a cookie. The
server's own zone is rarely the user's.
- **Pass the same `locale`** to both. Dates and times are formatted with `Intl`, which depends on it.
Runtimes also disagree on some spaces: Node.js puts thin spaces around the dash in "Oct 12 – 18"
where Chrome puts plain ones. The views' titles, times and labels use plain spaces, and so can your
own formatting, with `withAsciiSpaces(format.formatRange(start, end))`.
If you only learn the user's time zone in the browser, render the calendar after hydration, or pass
the zone as a controlled `timeZone` and update it once you know it.
## Element IDs
`Root` derives element IDs from React's `useId`, so they match between server and browser. If you
render several separate React roots on one page, give each a distinct `identifierPrefix` when you
create it (on both server and client), or pass an explicit `id` to each `Root`.
## A complete example
[Next.js App Router example](https://time.molten.sh/docs/react/guides/nextjs-app-router.md) builds a whole route on this page: the
view and the date in the URL, events fetched by a Server Component, changes saved through Server
Actions, and the time zone in a cookie.
# Next.js App Router example
A calendar whose view and date live in the URL, loaded by a Server Component and saved through Server Actions.
Source: https://time.molten.sh/docs/react/guides/nextjs-app-router
[Next.js and server rendering](https://time.molten.sh/docs/react/guides/nextjs.md) covers the basics: Client Components, strings
instead of Temporal values, and `now` and the time zone from the server. This page walks through a
complete App Router route built on them. [Open the example](https://time.molten.sh/examples/nextjs), then read its source
here. To load events in the browser from an API instead, see
[Load events with TanStack Query](https://time.molten.sh/docs/react/guides/tanstack-query.md).
- **The URL holds the view and the date**, as in `/examples/nextjs?view=week&date=2026-10-12`.
Previous, next, Today and the view switcher change it, and Back and Forward work.
- **A Server Component fetches the meetings** for the range the URL shows.
- **Server Actions save** created, moved and resized meetings. The calendar proposes each change, the
server decides, and the page renders again with the result.
- **The time zone comes from a cookie**, and the first render's clock from the server.
The route has eight files:
| File | Kind | What it does |
| ------------------- | ---------------- | --------------------------------------------------------- |
| `layout.tsx` | Server Component | The heading and the frame, which stay put as pages change |
| `page.tsx` | Server Component | Reads the URL and the cookies, and fetches the meetings |
| `loading.tsx` | Server Component | The first load's skeleton |
| `location.ts` | Shared | The URL's view and date, and the dates they show |
| `meetings.ts` | Server only | An in-memory store that stands in for your database |
| `actions.ts` | Server Actions | Save meetings and the time zone |
| `calendar.ts` | Client | The calendar, its views and its policies |
| `team-calendar.tsx` | Client Component | The calendar's state, wired to the URL and the actions |
## The URL
The view and the date are search params. A missing or broken view falls back to the week, and a
missing or broken date to today, so every link opens something:
```ts title="location.ts"
export const meetingViews = ["week", "day", "month"] as const;
export type MeetingView = (typeof meetingViews)[number];
/** Where the calendar is, as the URL says: `?view=week&date=2026-10-12`. */
export interface CalendarLocation {
readonly date: string;
readonly view: MeetingView;
}
type SearchParams = Readonly>;
/** Reads the view and date from the URL. Missing or broken ones fall back to this week. */
export function parseLocation(params: SearchParams, today: Temporal.PlainDate): CalendarLocation {
const view = meetingViews.find((name) => name === params.view) ?? "week";
return { date: (parseDate(params.date) ?? today).toString(), view };
}
function parseDate(value: string | string[] | undefined): Temporal.PlainDate | undefined {
if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return undefined;
try {
return Temporal.PlainDate.from(value, { overflow: "reject" });
} catch {
return undefined;
}
}
export function locationSearch({ date, view }: CalendarLocation): string {
return new URLSearchParams({ view, date }).toString();
}
```
## The page
The page is a Server Component. It reads the URL, the visitor and the clock, and fetches the
meetings for the range the calendar will show:
```tsx title="page.tsx"
import { TeamCalendar } from "./team-calendar";
import { parseLocation, visibleRange } from "./location";
import { findMeetings, getVisitor } from "./meetings";
interface MeetingsPageProps {
readonly searchParams: Promise>;
}
export default async function MeetingsPage({ searchParams }: MeetingsPageProps) {
const visitor = await getVisitor();
// Until the browser has said which zone it's in, render in UTC.
const timeZone = visitor.timeZone ?? "UTC";
// Read the clock once, and hand the instant to the browser, so both render the same today.
const now = Temporal.Now.instant();
const location = parseLocation(
await searchParams,
now.toZonedDateTimeISO(timeZone).toPlainDate(),
);
const meetings = await findMeetings(visitor, visibleRange(location, timeZone));
return (
);
}
```
- **It renders on every request.** Reading `searchParams` and cookies makes the page dynamic.
- **`now` is read once**, here, and passed down as a string, so the server and the browser render
the same today. Once the page has hydrated, the calendar follows the browser's clock instead, so
the now line keeps moving between server renders.
- **Meetings arrive as strings.** `meetings.ts` sends them as `MeetingJson`, with ISO 8601 times:
```ts title="meetings.ts"
/** A meeting as the server sends it: Client Components get strings, not Temporal values. */
export interface MeetingJson {
readonly color: CalendarEventColor;
readonly end: string;
readonly id: string;
readonly start: string;
readonly title: string;
}
```
The server works out the dates with the functions the views use, so it fetches exactly what they
show. The example's tests check that the two agree for every view:
```ts title="location.ts"
export const locale = "en-US";
export const weekRules = { firstDay: 1, minimalDays: 4, weekend: [6, 7] } as const;
/** The dates a location shows, by the same rules as its view. */
export function visibleDates({ date, view }: CalendarLocation): PlainDateInterval {
const anchor = Temporal.PlainDate.from(date);
switch (view) {
case "day":
return timeGridRange(anchor, { count: 1, kind: "days" }, weekRules);
case "week":
return timeGridRange(anchor, { kind: "week" }, weekRules);
case "month":
return getMonthRange(anchor, environment("UTC"));
}
}
/** The instants between those dates' starts of day in `timeZone`: the events to fetch. */
export function visibleRange(location: CalendarLocation, timeZone: string): InstantInterval {
return resolveViewInstantRange(visibleDates(location), timeZone);
}
export function environment(timeZone: string): CalendarEnvironmentBase {
return { direction: "ltr", disambiguation: "compatible", locale, timeZone, weekRules };
}
```
`visibleRange` turns the dates into instants in the visitor's time zone, as `Root` does for
`onVisibleRangeChange`. A week in Tokyo starts nine hours before a week in UTC.
## The calendar
The calendar is defined in a client module. Meetings have a time, so a policy refuses drops on the
all-day row before they reach the server:
```ts title="calendar.ts"
import {
createCalendar,
defineEventAdapter,
minimumDurationPolicy,
snapPolicy,
type CalendarEventChange,
type CalendarPolicy,
} from "@moltenship/calendar";
import type { CalendarEventColor } from "@/components/calendar/event-colors";
import { createMonthView } from "@/components/calendar/month-view/month-view";
import { createDayView, createWeekView } from "@/components/calendar/time-grid-view/time-grid-view";
export interface Meeting {
readonly color: CalendarEventColor;
readonly end: Temporal.Instant;
readonly id: string;
/** Created in this tab and not saved yet, so it has no ID from the server. */
readonly pending?: true;
readonly start: Temporal.Instant;
readonly title: string;
}
export type MeetingChange = CalendarEventChange;
const getEventColor = (meeting: Meeting) => meeting.color;
export const Calendar = createCalendar()({
eventAdapter: defineEventAdapter()({
getId: (meeting) => meeting.id,
getInterval: ({ end, start }) => ({ end, kind: "timed", start }),
getResourceIds: () => [],
getTitle: (meeting) => meeting.title,
// The server knows a new meeting by the ID it gives it, so it can't move until then.
isReadOnly: (meeting) => meeting.pending === true,
}),
views: [
createWeekView({ dayView: "day", getEventColor }),
createDayView({ getEventColor }),
createMonthView({ getEventColor }),
],
});
// Meetings always have a time, so drops on the all-day row stop here, before the server.
const timedOnly: CalendarPolicy = ({ proposed }) =>
proposed === null || proposed.kind === "timed"
? { type: "accept" }
: { reason: "meetings-need-a-time", type: "reject" };
export const policies = [
timedOnly,
snapPolicy({ minutes: 15 }),
minimumDurationPolicy({ minutes: 15 }),
];
```
The Client Component wires it to the URL, the Server Actions and the time zone cookie:
```tsx title="team-calendar.tsx"
const viewOptions = [
{ label: "Week", value: "week" },
{ label: "Day", value: "day" },
{ label: "Month", value: "month" },
] as const;
export interface TeamCalendarProps {
readonly location: CalendarLocation;
readonly meetings: readonly MeetingJson[];
/** When the server rendered the page, so both sides agree on today. */
readonly now: string;
readonly timeZone: string;
/** `false` on a first visit, when the time zone is a guess. */
readonly timeZoneFromCookie: boolean;
}
const subscribeToNothing = () => () => undefined;
/** `false` while the page hydrates, `true` from then on. */
function useHydrated() {
return useSyncExternalStore(
subscribeToNothing,
() => true,
() => false,
);
}
export function TeamCalendar(props: TeamCalendarProps) {
const { loading, location, navigate } = useCalendarLocation(props.location);
const { meetings, message, save } = useMeetings(props.meetings);
const [timeZone, setTimeZone] = useTimeZone(props.timeZone, props.timeZoneFromCookie);
// The server's clock while hydrating, so both sides render the same today. The browser's clock
// after that, so the now line keeps moving between server renders.
const serverNow = useHydrated() ? {} : { now: Temporal.Instant.from(props.now) };
return (
navigate({ date: date.toString() })}
onEventChange={save}
onViewChange={(view) => navigate({ view })}
policies={policies}
timeZone={timeZone}
view={location.view}
weekRules={weekRules}
>
navigate({ view })}
options={viewOptions}
value={location.view}
/>
{/* Stays on screen while the next range loads; only this bar says so. */}
);
}
```
`view` and `anchorDate` are controlled, so the URL decides what the calendar shows. `timeZone` is
controlled too, and comes from the cookie. `useHydrated` is `false` only while the page hydrates, so
`now` is the server's for that first render and the calendar's own clock after it.
## Navigation
When someone moves to another week or view, the calendar calls `onAnchorDateChange` or
`onViewChange`. The component pushes a new URL instead of keeping the change in state:
```tsx title="team-calendar.tsx"
/** The view and date from the URL. Changing them pushes a new URL; the calendar moves at once. */
function useCalendarLocation(location: CalendarLocation) {
const router = useRouter();
const pathname = usePathname();
const [loading, startNavigation] = useTransition();
// Shown until the new page has rendered on the server, so the grid moves on the click.
const [shown, show] = useOptimistic(location);
const queued = useRef(null);
function navigate(change: Partial) {
const first = queued.current === null;
queued.current = { ...(queued.current ?? shown), ...change };
if (!first) return;
// Opening a day from the month view changes the date and the view in one click. Wait for
// both, so they land in one URL and one history entry.
queueMicrotask(() => {
const next = queued.current ?? shown;
queued.current = null;
if (next.date === shown.date && next.view === shown.view) return;
startNavigation(() => {
show(next);
router.push(`${pathname}?${locationSearch(next)}`, { scroll: false });
});
});
}
return { loading, location: shown, navigate };
}
```
- **The grid moves on the click.** `router.push` runs inside a transition, and `useOptimistic` shows
the new view and date at once. Their meetings arrive with the server's render. Until then the grid
shows the meetings it already has that fall in the new range: all of them when zooming from a
month into a week, none when stepping to the next week.
- **The page says it's loading.** The transition's `loading` flag sets `aria-busy` on the viewport
and shows a thin bar under the toolbar. The grid itself never blanks.
- **One click, one URL.** Opening a day from the month view changes the view and the date. The
changes queue for one microtask, so they land in a single URL and a single history entry.
- **Back and Forward** restore that URL's render from the Next.js router's cache, or fetch it again
when it isn't cached, as after a save or a zone change. The controlled props follow.
The calendar stays mounted through all of this. Next.js keeps the page on screen while it fetches
the next render, and the props change in place, so the scroll position and the focus survive.
`loading.tsx` only shows when the route first loads, before there's a page to keep:
```tsx title="loading.tsx"
// The first visit's fallback. Later navigations keep the calendar on screen instead.
export default function Loading() {
return (
);
}
```
## Saving
The calendar proposes; the app commits. Every move, resize and create runs through the calendar's
policies first, then reaches `onEventChange`, which calls a Server Action:
```ts title="actions.ts"
export type SaveResult =
| { readonly ok: true }
| { readonly ok: false; readonly reason: "invalid" | "in-the-past" | "not-found" | "full" };
interface Times {
readonly end: string;
readonly start: string;
}
// Server Actions are public endpoints: check every argument, whatever the calendar sent.
function parseTimes(input: unknown) {
const { end, start } = (input ?? {}) as Partial>;
if (typeof start !== "string" || typeof end !== "string") return undefined;
try {
const times = { end: Temporal.Instant.from(end), start: Temporal.Instant.from(start) };
const minutes = times.start.until(times.end).total("minutes");
return minutes >= 15 && minutes <= 24 * 60 ? times : undefined;
} catch {
return undefined;
}
}
/** The rule this server adds on top of the calendar's policies. */
function startsInThePast(times: { readonly start: Temporal.Instant }) {
return Temporal.Instant.compare(times.start, Temporal.Now.instant()) < 0;
}
export async function createMeeting(input: Times): Promise {
const times = parseTimes(input);
if (times === undefined) return { ok: false, reason: "invalid" };
if (startsInThePast(times)) return { ok: false, reason: "in-the-past" };
const session = await startSession(await getVisitor());
if (insertMeeting(session, times) === undefined) return { ok: false, reason: "full" };
// Re-render the page in this response, so the new meeting arrives with its ID.
refresh();
return { ok: true };
}
/** Moves and both resizes send the meeting's new start and end. */
export async function moveMeeting(input: Times & { readonly id: string }): Promise {
const times = parseTimes(input);
const id: unknown = input?.id;
if (times === undefined || typeof id !== "string") return { ok: false, reason: "invalid" };
if (startsInThePast(times)) return { ok: false, reason: "in-the-past" };
const session = await startSession(await getVisitor());
if (!updateMeeting(session, id, times)) return { ok: false, reason: "not-found" };
refresh();
return { ok: true };
}
```
- **Check every argument.** A Server Action is a public endpoint, and anyone can call it with
anything. The calendar's snap and minimum duration don't protect the server.
- **The server has the last word.** This one refuses meetings that start in the past, a rule the
calendar doesn't know.
- **`refresh()` re-renders the page** in the same response as the action's result, so the saved
meeting arrives without another request. If your reads are cached with `"use cache"`, call
`updateTag` instead.
- **Saves run one at a time.** Next.js sends a page's Server Actions in order, so two quick moves of
one meeting are saved in the order they were made.
On the client, `save` turns the action's result into the promise the calendar waits for:
```tsx title="team-calendar.tsx"
function fromJson(meeting: MeetingJson): Meeting {
return {
...meeting,
end: Temporal.Instant.from(meeting.end),
start: Temporal.Instant.from(meeting.start),
};
}
function addMeeting(meetings: readonly Meeting[], meeting: Meeting): readonly Meeting[] {
return [...meetings, meeting];
}
function send(change: MeetingChange): Promise {
if (change.proposed?.kind !== "timed") return Promise.resolve({ ok: false, reason: "invalid" });
const times = { end: change.proposed.end.toString(), start: change.proposed.start.toString() };
return change.cause === "create"
? createMeeting(times)
: moveMeeting({ ...times, id: change.eventId });
}
const refusals: Record["reason"], string> = {
full: "Not saved: this example keeps 200 meetings at most.",
"in-the-past": "Not saved: the server refuses meetings that start in the past.",
invalid: "Not saved: the server couldn't read the change.",
"not-found": "Not saved: the meeting is gone. Reload the page.",
};
/** The server's meetings, plus new ones still saving. */
function useMeetings(json: readonly MeetingJson[]) {
const saved = useMemo(() => json.map(fromJson), [json]);
// The calendar shows a moved or resized meeting in its new place while it saves. A new one has
// no ID until the server gives it one, so it's shown here until the page re-renders with it.
const [meetings, addPending] = useOptimistic(saved, addMeeting);
const [message, setMessage] = useState("");
// The calendar keeps a change pending until this promise settles, and undoes it on a rejection.
function save(change: MeetingChange): Promise {
const { promise, reject, resolve } = Promise.withResolvers();
// Cleared first, so the same refusal twice is announced twice.
setMessage("");
startTransition(async () => {
if (change.cause === "create" && change.proposed.kind === "timed") {
const { end, start } = change.proposed;
addPending({
color: "blue",
end,
id: change.id,
pending: true,
start,
title: "New meeting",
});
}
const result = await send(change).catch(() => null);
if (result?.ok === true) {
resolve();
} else {
setMessage(
result === null ? "Not saved: the server didn't answer." : refusals[result.reason],
);
reject(new Error(result?.reason ?? "network"));
}
});
return promise;
}
return { meetings, message, save };
}
```
- **Moves and resizes** stay where they were dropped while the promise is pending. The calendar
shows them as saving, then keeps them in place until the page's next render has the saved times.
- **A refusal** rejects the promise, and the calendar moves the meeting back. The reason shows under
the calendar.
- **New meetings** have no ID until the server gives them one, so the calendar can't show them as
pending. `useOptimistic` adds them to the meetings on screen until the page renders again with the
saved one. They're marked `pending`, and the adapter's `isReadOnly` keeps them still until then.
## The time zone
The page renders in the zone from the `time-zone` cookie. On a first visit there's no cookie, so the
server renders in UTC, and the browser sends its own zone once it has hydrated:
```tsx title="team-calendar.tsx"
const timeZones = [
"America/Los_Angeles",
"America/New_York",
"Europe/London",
"Europe/Berlin",
"Asia/Kolkata",
"Asia/Tokyo",
"Australia/Sydney",
"UTC",
];
/** The cookie's time zone. A first visit has none: store the browser's, and render in it. */
function useTimeZone(timeZone: string, fromCookie: boolean) {
const [shown, show] = useOptimistic(timeZone);
// The calendar switches at once, and the page renders again in the new zone when the cookie is
// set. If saving fails, it goes back to the zone the server rendered in.
const change = useCallback(
(next: string) => {
startTransition(async () => {
show(next);
await saveTimeZone(next).catch(() => undefined);
});
},
[show],
);
useEffect(() => {
if (!fromCookie) change(Temporal.Now.timeZoneId());
}, [change, fromCookie]);
return [shown, change] as const;
}
function TimeZonePicker({
onChange,
value,
}: {
readonly onChange: (timeZone: string) => void;
readonly value: string;
}) {
const options = (timeZones.includes(value) ? timeZones : [value, ...timeZones]).map((zone) => ({
label: zone.replaceAll("_", " "),
value: zone,
}));
return (
zone !== null && onChange(zone)} value={value}>
{options.map((option) => (
{option.label}
))}
);
}
```
`useOptimistic` switches the calendar to the new zone at once. Setting a cookie in a Server Action
re-renders the page in the same response, so the meetings for the new zone's range arrive with the
action's result. Every later request renders in the right zone from the start, and hydration
matches. The picker under the calendar calls the same action.
Switching zones keeps each meeting at its instant, so a 09:30 standup in Tokyo shows in the small
hours in Berlin. A first visit has no zone to keep, so its sample meetings simply follow the browser's.
```ts title="actions.ts"
export async function saveTimeZone(input: string): Promise {
const timeZone = timeZoneOf(input);
if (timeZone === undefined) return;
const visitor = await getVisitor();
// Switching zones keeps the meetings at the instants the visitor saw, so they move on the clock.
// A first visit has no zone to keep, and its sample meetings simply follow the new one.
if (visitor.timeZone !== undefined && visitor.timeZone !== timeZone) await startSession(visitor);
// Setting a cookie re-renders the page in this response, in the new zone.
await setTimeZoneCookie(timeZone);
}
```
## Temporal in the browser
The server runs on Node.js 26, which has `Temporal`. The calendar also renders while the page
hydrates, so `Temporal` has to exist in the browser before then. `team-calendar.tsx` imports
`temporal-polyfill/global` before anything else. The polyfill installs itself only in browsers
without `Temporal`, but as a static import every browser downloads it. The dynamic import that
[Installation](https://time.molten.sh/docs/react/installation.md#temporal) shows saves that, but only suits a calendar that renders
after hydration.
## Make it yours
- **Replace `meetings.ts`** with your database. Its functions take the visitor and a range, as
queries would.
- **Use your auth** in place of the session cookie, and check in every action that the visitor owns
the meeting they're changing.
- **Refuse stale writes.** Give meetings a revision, send it with each change, and refuse a change
made to an older one. The adapter's `getRevision` tells the calendar about them.
[Sync with Google Calendar](https://time.molten.sh/docs/react/guides/google-calendar-sync.md) does the same with etags.
- **Cache the reads** with `"use cache"` and `cacheTag`, and call `updateTag` from the actions.
# Google Calendar events
Read recurring events from the Google Calendar API, with their RRULE, EXDATE and RDATE lines, and show and edit them.
Source: https://time.molten.sh/docs/react/guides/google-calendar
The Google Calendar API stores a repeating event the way iCalendar does. `events.list`, without
`singleEvents=true`, returns each series once:
- **The master**, at the series' first occurrence, with its rule and exceptions as iCalendar lines
in `recurrence`, and the zone it repeats in as `start.timeZone`.
- **Changed occurrences**: events with the master's ID in `recurringEventId`, and the start the
series gave them in `originalStartTime`.
- **Deleted occurrences**: the same, with `status: "cancelled"` and no times of their own.
```json
[
{
"id": "standup",
"summary": "Stand-up",
"start": { "dateTime": "2026-10-19T09:00:00+02:00", "timeZone": "Europe/Berlin" },
"end": { "dateTime": "2026-10-19T09:30:00+02:00", "timeZone": "Europe/Berlin" },
"recurrence": ["RRULE:FREQ=DAILY;COUNT=5", "EXDATE;TZID=Europe/Berlin:20261021T090000"]
},
{
"id": "standup_20261020T070000Z",
"recurringEventId": "standup",
"originalStartTime": { "dateTime": "2026-10-20T09:00:00+02:00", "timeZone": "Europe/Berlin" },
"summary": "Stand-up (late)",
"start": { "dateTime": "2026-10-20T11:00:00", "timeZone": "Europe/Berlin" },
"end": { "dateTime": "2026-10-20T11:30:00", "timeZone": "Europe/Berlin" }
},
{
"id": "standup_20261022T070000Z",
"recurringEventId": "standup",
"originalStartTime": { "dateTime": "2026-10-22T09:00:00+02:00", "timeZone": "Europe/Berlin" },
"status": "cancelled"
}
]
```
That's a master, overrides and cancelled overrides, as in
[Recurring events](https://time.molten.sh/docs/react/recurrence/model.md). This page maps them to `RecurringCalendarEvent`s,
which the calendar from [Show and edit recurring events](https://time.molten.sh/docs/react/recurrence/calendar.md) expands and
edits. Here, the stand-up shows on Monday at 09:00, Tuesday at 11:00 and Friday at 09:00.
With `singleEvents=true`, Google expands series itself, between `timeMin` and `timeMax`, and
leaves the masters out. Each occurrence is then an event of its own. It names its series in
`recurringEventId`, but not the series' rule, which "This and following events" and "All events"
change. [Sync with Google Calendar](https://time.molten.sh/docs/react/guides/google-calendar-sync.md#series-masters-not-instances)
compares the two.
## The event type
The mapping reads a few fields of Google's
[Event resource](https://developers.google.com/workspace/calendar/api/v3/reference/events), and
keeps the whole Google event as each calendar event's `data`:
```ts title="google-calendar.ts"
// lib/google-calendar.ts
import type { CalendarEventInterval } from "@moltenship/calendar";
import {
formatRecurrenceRule,
parseRecurrenceRule,
type EventRecurrence,
type RecurrenceDate,
type RecurrenceRule,
type RecurringCalendarEvent,
} from "@moltenship/calendar-recurrence";
import {
decodeIcsDateValue,
encodeIcsValue,
icsValueTypeOf,
parseIcsComponents,
splitIcsValues,
type IcsDateValue,
} from "@moltenship/ics";
/** The fields of a Google Calendar API event that this mapping and the sync guide read. */
export interface GoogleEvent {
readonly id: string;
/** Changes on every write. Send it as `If-Match`, so a write never overwrites a newer one. */
readonly etag?: string;
readonly status?: "confirmed" | "tentative" | "cancelled";
readonly summary?: string;
/** An event color from `colors.get`, "1" to "11". Without it, the calendar's color. */
readonly colorId?: string;
/** "transparent" shows the time as free. "opaque", the default, as busy. */
readonly transparency?: "opaque" | "transparent";
readonly start?: GoogleEventTime;
readonly end?: GoogleEventTime;
/** On a series' master: RRULE, EXRULE, RDATE and EXDATE lines. */
readonly recurrence?: readonly string[];
/** On a changed or cancelled occurrence: the master's ID. */
readonly recurringEventId?: string;
/** On a changed or cancelled occurrence: where the series put it. */
readonly originalStartTime?: GoogleEventTime;
}
export interface GoogleEventTime {
/** An all-day event's date, such as "2026-10-12". */
readonly date?: string;
/** RFC 3339. The offset may be left out when `timeZone` is set. */
readonly dateTime?: string;
/** The IANA time zone a series repeats in. */
readonly timeZone?: string;
}
/** A Google event as the calendar's event, with the Google event as its `data`. */
export type GoogleCalendarEvent = RecurringCalendarEvent;
```
## Read the recurrence lines
`parseRecurrenceRule` reads an `RRULE:` line as Google writes it. EXDATE and RDATE lines need their
parameters: `TZID` names the zone of their wall times, and `VALUE=DATE` makes them dates. The
syntax layer of `@moltenship/ics` reads those lines, and its value decoders read each date:
```ts title="google-calendar.ts"
/** A master's `recurrence` lines as an `EventRecurrence`, and the lines it couldn't read. */
export function readGoogleRecurrence(lines: readonly string[]): {
readonly problems: readonly string[];
readonly recurrence: EventRecurrence;
} {
const problems: string[] = [];
const exceptionDates: RecurrenceDate[] = [];
const recurrenceDates: RecurrenceDate[] = [];
let rule: RecurrenceRule | undefined;
// The ICS syntax layer splits content lines into names, parameters and values.
const { components } = parseIcsComponents(["BEGIN:VEVENT", ...lines, "END:VEVENT"].join("\r\n"));
for (const property of components[0]?.properties ?? []) {
if (property.name === "RRULE") {
const parsed = parseRecurrenceRule(property.value);
rule = parsed.rule;
problems.push(...parsed.issues.map((issue) => `RRULE: ${issue.message}`));
continue;
}
// EXRULE, which RFC 5545 deprecated, and anything else.
if (property.name !== "EXDATE" && property.name !== "RDATE") {
problems.push(`${property.name} isn't supported`);
continue;
}
// A DATE-TIME unless VALUE says otherwise, as in EXDATE;VALUE=DATE:20261014.
const type = icsValueTypeOf(property);
if (type !== "DATE" && type !== "DATE-TIME") {
problems.push(`${property.name};VALUE=${type} isn't read`);
continue;
}
const tzid = property.parameters.TZID?.[0];
const dates = property.name === "EXDATE" ? exceptionDates : recurrenceDates;
for (const raw of splitIcsValues(type, property.value)) {
const decoded = decodeIcsDateValue(raw, type, tzid === undefined ? {} : { tzid });
const date = decoded.ok ? recurrenceDateOf(decoded.value) : undefined;
if (date === undefined) problems.push(`${property.name}: can't read ${raw}`);
else dates.push(date);
}
}
return { problems, recurrence: { exceptionDates, recurrenceDates, rule } };
}
/** An ICS date in the series' terms. The expander converts dates of another kind. */
function recurrenceDateOf(value: IcsDateValue): RecurrenceDate | undefined {
switch (value.kind) {
case "date":
return value.date;
case "utc":
return value.instant;
case "zoned":
return value.zoned.toInstant();
case "floating":
return value.wallTime;
case "unresolved":
return undefined;
}
}
```
- **`parseIcsComponents`** splits each line into its name, parameters and raw value. It reads
content lines inside a component, so the lines are wrapped in a `VEVENT`.
- **`icsValueTypeOf`** gives the line's value type: its `VALUE` parameter, else DATE-TIME for
EXDATE and RDATE. **`splitIcsValues`** splits a line that lists several dates, and
**`decodeIcsDateValue`** reads each one, in the zone `TZID` names.
- **Dates of another kind** are fine. A UTC EXDATE on a series in Berlin, or a date-only one that
excludes a whole day, converts when the series is expanded.
- **What it leaves out** goes to `problems`: EXRULE, which RFC 5545 deprecated, RDATE periods, and
dates it can't read. The rest of the series still shows.
## Map the events
Masters get their recurrence, changed and cancelled occurrences become overrides, and everything
else is a one-off event:
```ts title="google-calendar.ts"
/**
* Events from `events.list` without `singleEvents`: masters with `recurrence`, occurrences that
* changed or were cancelled with `recurringEventId`, and one-off events.
*/
export function fromGoogleEvents(items: readonly GoogleEvent[]): {
readonly events: readonly GoogleCalendarEvent[];
readonly problems: readonly string[];
} {
const events: GoogleCalendarEvent[] = [];
const problems: string[] = [];
for (const item of items) {
const base = { data: item, id: item.id, title: item.summary ?? "(No title)" };
if (item.recurringEventId !== undefined) {
// An occurrence that changed, or was cancelled, which Google returns without times.
const recurrenceId = item.originalStartTime && pointOf(item.originalStartTime);
const interval = intervalOf(item.start, item.end) ?? recurrenceId?.interval;
if (recurrenceId === undefined || interval === undefined) {
problems.push(`${item.id}: no original start`);
continue;
}
const cancelled = item.status === "cancelled";
events.push({
...base,
...interval,
override: { cancelled, recurrenceId: recurrenceId.date, seriesId: item.recurringEventId },
});
continue;
}
if (item.status === "cancelled") continue;
const interval = intervalOf(item.start, item.end);
if (interval === undefined) {
problems.push(`${item.id}: no start or end`);
continue;
}
if (item.recurrence === undefined) {
events.push({ ...base, ...interval });
continue;
}
const { problems: lines, recurrence } = readGoogleRecurrence(item.recurrence);
problems.push(...lines.map((problem) => `${item.id}: ${problem}`));
events.push({ ...base, ...interval, recurrence });
}
return { events, problems };
}
function intervalOf(
start: GoogleEventTime | undefined,
end: GoogleEventTime | undefined,
): CalendarEventInterval | undefined {
if (start?.date !== undefined && end?.date !== undefined) {
const [from, to] = [Temporal.PlainDate.from(start.date), Temporal.PlainDate.from(end.date)];
return { end: to, kind: "all-day", start: from };
}
if (start?.dateTime === undefined || end?.dateTime === undefined) return undefined;
const timeZone = start.timeZone;
return {
end: instantOf(end.dateTime, end.timeZone ?? timeZone),
kind: "timed",
start: instantOf(start.dateTime, timeZone),
// A series repeats on this zone's wall clock, so 09:00 stays 09:00 across DST.
...(timeZone === undefined ? {} : { sourceTimeZone: timeZone }),
};
}
/** `originalStartTime` as a recurrence ID, and an interval there for a cancelled occurrence. */
function pointOf(time: GoogleEventTime) {
const interval = intervalOf(time, time);
return interval && { date: interval.start, interval };
}
function instantOf(dateTime: string, timeZone: string | undefined): Temporal.Instant {
// "2026-10-12T09:00:00+02:00" has its offset; "2026-10-12T09:00:00" is a wall time in timeZone.
return /(?:Z|[+-]\d{2}:\d{2})$/i.test(dateTime)
? Temporal.Instant.from(dateTime)
: Temporal.PlainDateTime.from(dateTime)
.toZonedDateTime(timeZone ?? "UTC")
.toInstant();
}
```
- **Times.** `start.dateTime` is RFC 3339, and may leave out its offset when `timeZone` is set, so
`instantOf` reads it in that zone. `start.date` makes an all-day event, whose `end.date` is
exclusive, as the calendar's is.
- **The zone a series repeats in** is `start.timeZone`, which Google requires on recurring events.
It becomes `sourceTimeZone`, so a 09:00 meeting stays at 09:00 across daylight saving time.
- **Overrides** keep Google's instance IDs as their own. The calendar shows them under the ID of
the occurrence they replace, such as `standup::2026-10-20T07:00:00Z`, before and after their
master loads.
- **Cancelled occurrences** have no times, so they're placed at their original start. A cancelled
override only hides its occurrence and never shows, so its length doesn't matter.
Give the events to the calendar with the canonical adapters, as the
[guide](https://time.molten.sh/docs/react/recurrence/calendar.md#wire-the-adapters) does:
```ts
import {
createCanonicalRecurrenceAdapter,
createOccurrenceExpander,
} from "@moltenship/calendar-recurrence";
const adapters = createCanonicalRecurrenceAdapter();
const expander = createOccurrenceExpander(adapters);
const { events, problems } = fromGoogleEvents(response.items);
```
Google returns an event list a page at a time, with `nextPageToken`. Read every page before you
expand: a master on one page and its overrides on another are one series.
## Write changes back
An edit from `resolveRecurrenceEdit` writes the master's whole recurrence. Google stores it as the
master's `recurrence` lines, so write them back in Google's format:
```ts title="google-calendar.ts"
/**
* A series' recurrence as Google's `recurrence` lines, such as the one an edit writes. Instants
* are written on the series' wall clock when it has a time zone.
*/
export function toGoogleRecurrence(
recurrence: EventRecurrence,
timeZone: string | undefined,
): string[] {
const lines =
recurrence.rule === undefined ? [] : [`RRULE:${formatRecurrenceRule(recurrence.rule)}`];
for (const date of recurrence.exceptionDates ?? [])
lines.push(`EXDATE${dateText(date, timeZone)}`);
for (const date of recurrence.recurrenceDates ?? []) {
// This mapping reads no RDATE periods, so edits write none.
if ("start" in date) continue;
lines.push(`RDATE${dateText(date, timeZone)}`);
}
return lines;
}
function dateText(date: RecurrenceDate, timeZone: string | undefined): string {
if (date instanceof Temporal.PlainDate) {
return `;VALUE=DATE:${encodeIcsValue("DATE", { date, kind: "date" })}`;
}
if (date instanceof Temporal.PlainDateTime) {
return `:${encodeIcsValue("DATE-TIME", { kind: "floating", wallTime: date })}`;
}
if (timeZone === undefined)
return `:${encodeIcsValue("DATE-TIME", { instant: date, kind: "utc" })}`;
const wallTime = date.toZonedDateTimeISO(timeZone).toPlainDateTime();
return `;TZID=${timeZone}:${encodeIcsValue("DATE-TIME", { kind: "floating", wallTime })}`;
}
```
`formatRecurrenceRule` writes the rule's value without the `RRULE:` prefix, so the line adds it.
Exception dates are written on the series' wall clock, with its `TZID`, as Google writes them.
Apply the edit to your copy of the events with `applyRecurrenceEdit`, as the guide does, and send
its writes to Google:
| The edit says | In the Calendar API |
| ------------------------------------- | --------------------------------------------------------------------------------------------- |
| `series.action: "update"` | Patch the master: `start` and `end` from `placement`, `recurrence` from `toGoogleRecurrence`. |
| `series.action: "delete"` | Delete the master, which deletes the whole series. |
| `newSeries` | Insert a new event, copied from the master, with its own `recurrence`. |
| `override` (`"create"` or `"update"`) | Patch the occurrence: the instance whose `originalStartTime` is the edit's `recurrenceId`. |
| `override` (`"delete"`) | Delete that instance. |
After a write that changes the master, list the series again, so your copy matches what Google
stored for its other occurrences. [Sync with Google Calendar](https://time.molten.sh/docs/react/guides/google-calendar-sync.md)
does this with sync tokens, and writes with etags.
A "This event" delete adds an EXDATE line to the master, which Google reads like any other
`recurrence` line. Google records a deleted occurrence as a cancelled instance instead;
`fromGoogleEvents` reads both.
# Sync with Google Calendar
Load a Google calendar from the dates on screen, keep it current with sync tokens, and write changes back with etags.
Source: https://time.molten.sh/docs/react/guides/google-calendar-sync
> Live example: see it at https://time.molten.sh/docs/react/guides/google-calendar-sync
This calendar syncs with a Google calendar. There are no Google credentials on this page, so it
talks to a fake Calendar API that runs in your browser. It answers with API v3's JSON, pages, sync
tokens, etags and errors. Drag an event, or delete one, and it's written back. The buttons change
events as someone else would in Google, expire the sync token and rate-limit requests. The log
shows each request.
This guide builds it. The code is what a real app runs. The demo hands it a fake `fetch` instead
of your route, and a shorter retry delay.
| File | What it does |
| -------------------------------------------- | -------------------------------------------------------------------------------------------------- |
| `lib/google-calendar-api.ts` | A small client for the API's events, over `fetch` |
| `app/api/google-calendar/[...path]/route.ts` | Sends the browser's requests to Google with the user's token |
| `lib/google-calendar.ts` | Maps Google events to calendar events, from [Google Calendar events](https://time.molten.sh/docs/react/guides/google-calendar.md) |
| `lib/google-calendar-sync.ts` | The events loaded so far: loads, syncs and writes |
| `components/google-calendar-view.tsx` | The calendar |
None of it is in the calendar's packages. They don't depend on Google, and this guide doesn't add
a Google SDK either.
## Sign-in is up to you
The Calendar API needs an OAuth 2.0 access token for the user. Ask for the
`https://www.googleapis.com/auth/calendar.events` scope to read and write events, or
`calendar.events.readonly` to only read them. Your auth library, such as Auth.js or Better Auth,
runs the sign-in on your server and keeps the tokens there. Ask Google for offline access, so you
get a refresh token, and refresh the access token when it expires, as your library's docs show.
This guide starts once you have one.
Keep the tokens on the server. The browser calls your own route, and the route adds the token.
## Call the API
The client covers the calls the calendar needs: list events, read one occurrence of a series, and
insert, patch, replace and delete:
```ts title="lib/google-calendar-api.ts"
// lib/google-calendar-api.ts
import type { GoogleEvent } from "./google-calendar";
export interface GoogleCalendarApiOptions {
/**
* `https://www.googleapis.com/calendar/v3` on your server, with `headers` adding the user's
* access token. In the browser, your own route that adds it.
*/
readonly baseUrl: string;
/** "primary", or a calendar's ID from `calendarList.list`. */
readonly calendarId?: string;
readonly fetch?: typeof fetch;
/** Headers for every request, such as `Authorization: Bearer `. */
readonly headers?: () => HeadersInit | Promise;
/** How often to retry a rate-limited or failed request before giving up. */
readonly retries?: number;
/** How long to wait before retry `attempt`, from 0, when Google doesn't say. */
readonly retryDelay?: (attempt: number) => number;
}
/** A request Google refused: its status, and the reason its error body gives. */
export class GoogleApiError extends Error {
override readonly name = "GoogleApiError";
readonly reason: string | undefined;
readonly status: number;
constructor(status: number, reason: string | undefined, message: string) {
super(message);
this.reason = reason;
this.status = status;
}
}
/**
* The events that end after `timeMin` and start before `timeMax`, if given, or the changes since a
* sync token. Google doesn't take both at once.
*/
export type GoogleEventsQuery =
| { readonly timeMax?: Temporal.Instant; readonly timeMin: Temporal.Instant }
| { readonly syncToken: string };
export interface GoogleEventTimeWrite {
readonly date?: string | null;
readonly dateTime?: string | null;
readonly timeZone?: string | null;
}
/**
* What a write sends: these fields, and any other of the Event resource. In a patch, `null` clears a
* field, as a move between all-day and timed needs.
*/
export interface GoogleEventWrite {
readonly colorId?: string;
readonly end?: GoogleEventTimeWrite;
/** Insert only: lowercase a–v and digits, 5 to 1024 of them, so you can pick it up front. */
readonly id?: string;
readonly originalStartTime?: GoogleEventTimeWrite;
readonly recurrence?: readonly string[];
readonly recurringEventId?: string;
readonly start?: GoogleEventTimeWrite;
readonly status?: "confirmed" | "tentative";
readonly summary?: string;
readonly transparency?: "opaque" | "transparent";
}
interface GoogleEventsPage {
readonly items?: readonly GoogleEvent[];
readonly nextPageToken?: string;
readonly nextSyncToken?: string;
}
const rateLimits = new Set(["rateLimitExceeded", "userRateLimitExceeded"]);
/** 1, 2, 4… seconds, up to 32, plus up to a second at random, so clients don't retry in step. */
const backoff = (attempt: number) => Math.min(2 ** attempt, 32) * 1000 + Math.random() * 1000;
/** The Calendar API's events, over `fetch`. */
export function createGoogleCalendarApi({
baseUrl,
calendarId = "primary",
fetch: send = fetch,
headers,
retries = 5,
retryDelay = backoff,
}: GoogleCalendarApiOptions) {
const events = `${baseUrl}/calendars/${encodeURIComponent(calendarId)}/events`;
async function request(
method: "DELETE" | "GET" | "PATCH" | "POST" | "PUT",
url: string,
{ body, etag }: { readonly body?: GoogleEventWrite; readonly etag?: string | undefined } = {},
): Promise {
const sent = new Headers(await headers?.());
if (body !== undefined) sent.set("Content-Type", "application/json");
// Google writes only over the version you read, and answers 412 if it has changed since.
if (etag !== undefined) sent.set("If-Match", etag);
for (let attempt = 0; ; attempt++) {
const response = await send(url, {
body: body === undefined ? null : JSON.stringify(body),
headers: sent,
method,
});
if (response.ok) return (response.status === 204 ? undefined : await response.json()) as T;
const error = await errorOf(response);
const rateLimited =
error.status === 429 || (error.status === 403 && rateLimits.has(error.reason ?? ""));
if (attempt >= retries || !(rateLimited || error.status >= 500)) throw error;
const retryAfter = Number(response.headers.get("Retry-After"));
await sleep(retryAfter > 0 ? retryAfter * 1000 : retryDelay(attempt));
}
}
return {
/**
* Every page of `events.list`. Series come as their masters, with their changed and cancelled
* occurrences, since `singleEvents` stays off. The sync token is on the last page.
*/
async list(query: GoogleEventsQuery) {
const items: GoogleEvent[] = [];
let pageToken: string | undefined;
for (;;) {
const params = new URLSearchParams(
"syncToken" in query
? { syncToken: query.syncToken }
: { timeMin: query.timeMin.toString() },
);
if ("timeMax" in query && query.timeMax !== undefined) {
params.set("timeMax", query.timeMax.toString());
}
if (pageToken !== undefined) params.set("pageToken", pageToken);
const page = await request("GET", `${events}?${params}`);
items.push(...(page.items ?? []));
pageToken = page.nextPageToken;
if (pageToken === undefined) return { items, nextSyncToken: page.nextSyncToken };
}
},
/**
* The occurrence a series' rule puts at `originalStart`, with its own ID and etag, cancelled
* or not.
*/
async instance(seriesId: string, originalStart: string) {
const params = new URLSearchParams({ originalStart, showDeleted: "true" });
for (;;) {
const page = await request(
"GET",
`${events}/${encodeURIComponent(seriesId)}/instances?${params}`,
);
const [instance] = page.items ?? [];
if (instance !== undefined) return instance;
// A page may be empty and still have more.
if (page.nextPageToken === undefined) break;
params.set("pageToken", page.nextPageToken);
}
throw new GoogleApiError(
404,
"notFound",
`${seriesId} has no occurrence at ${originalStart}`,
);
},
insert: (event: GoogleEventWrite) => request("POST", events, { body: event }),
patch: (id: string, fields: GoogleEventWrite, etag: string | undefined) =>
request("PATCH", `${events}/${encodeURIComponent(id)}`, { body: fields, etag }),
remove: (id: string, etag: string | undefined) =>
request("DELETE", `${events}/${encodeURIComponent(id)}`, { etag }),
/** Replaces the whole event: a field the write leaves out is cleared. */
update: (id: string, event: GoogleEventWrite, etag: string | undefined) =>
request("PUT", `${events}/${encodeURIComponent(id)}`, { body: event, etag }),
};
}
export type GoogleCalendarApi = ReturnType;
/** Google's error body: `{ error: { code, message, errors: [{ reason }] } }`. */
async function errorOf(response: Response): Promise {
const body = (await response.json().catch(() => undefined)) as
| { error?: { errors?: { reason?: string }[]; message?: string } }
| undefined;
return new GoogleApiError(
response.status,
body?.error?.errors?.[0]?.reason,
body?.error?.message ?? response.statusText,
);
}
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
```
- **Where it runs.** On your server, `baseUrl` is Google's and `headers` adds the access token. In
the browser, `baseUrl` is your route, below, and the cookie your auth library set signs the
request. The rest of the guide runs in the browser.
- **Pages.** `list` follows `nextPageToken` until the last page, which has `nextSyncToken`
instead. Google may send fewer events than `maxResults`, or none, and still have more.
- **Rate limits.** A 429, a 403 with `rateLimitExceeded` or `userRateLimitExceeded`, and a 5xx
are retried after 1, 2, 4… seconds, up to 32, plus a random part so that clients don't retry
together. A `Retry-After` header wins. Other errors throw a `GoogleApiError` at once: a 410 or a
412 means something, and retrying won't change it.
- **`googleapis`.** On a Node.js server you can use Google's SDK instead.
`calendar.events.list({ calendarId, timeMin, timeMax, pageToken, syncToken })` takes the same
parameters. Wrap its calls so their errors become `GoogleApiError`s with the status and reason,
which the store reads. Plain `fetch` also runs in the browser and on edge runtimes, and adds no
dependency.
### The route
A Route Handler sends the browser's requests on to Google with the user's access token:
```ts title="app/api/google-calendar/[...path]/route.ts"
// app/api/google-calendar/[...path]/route.ts
import type { NextRequest } from "next/server";
/**
* The signed-in user's Google access token, from your auth library, with the
* `https://www.googleapis.com/auth/calendar.events` scope. `null` when they aren't signed in.
*/
declare function googleAccessToken(request: NextRequest): Promise;
const calendarApi = "https://www.googleapis.com/calendar/v3";
/** The query parameters the client sends. */
const parameters = new Set([
"originalStart",
"pageToken",
"showDeleted",
"syncToken",
"timeMax",
"timeMin",
]);
/** Which calls go through: the methods each path takes, below `calendars/primary/events`. */
function allowed(method: string, event: readonly string[]): boolean {
const [id, instances, ...rest] = event;
if (id === undefined) return method === "GET" || method === "POST"; // list, insert
if (id === "." || id === ".." || rest.length > 0) return false;
if (instances !== undefined) return instances === "instances" && method === "GET";
return method === "PATCH" || method === "PUT" || method === "DELETE";
}
/**
* Sends the browser's Calendar API requests on to Google with the user's access token, which never
* reaches the browser. Only the calls the client makes, on the user's own events.
*/
async function forward(request: NextRequest, { params }: { params: Promise<{ path: string[] }> }) {
// Only your own pages: browsers mark a request from another site.
if (request.headers.get("Sec-Fetch-Site") === "cross-site") {
return Response.json({ error: { code: 403, message: "Forbidden" } }, { status: 403 });
}
const { path } = await params;
const [calendars, calendarId, events, ...event] = path;
const { searchParams } = request.nextUrl;
if (
calendars !== "calendars" ||
calendarId !== "primary" ||
events !== "events" ||
!allowed(request.method, event) ||
[...searchParams.keys()].some((name) => !parameters.has(name))
) {
return Response.json({ error: { code: 404, message: "Not found" } }, { status: 404 });
}
const token = await googleAccessToken(request);
if (token === null) {
return Response.json({ error: { code: 401, message: "Sign in again" } }, { status: 401 });
}
const url = new URL(`${calendarApi}/${path.map(encodeURIComponent).join("/")}`);
url.search = searchParams.toString();
const headers = new Headers({ Authorization: `Bearer ${token}` });
for (const name of ["Content-Type", "If-Match"]) {
const value = request.headers.get(name);
if (value !== null) headers.set(name, value);
}
const response = await fetch(url, {
body: request.method === "GET" || request.method === "DELETE" ? null : await request.text(),
headers,
method: request.method,
});
// The status, Retry-After and Google's error body pass through, so the browser handles 410, 412
// and 429 itself.
const passed = new Headers();
for (const name of ["Content-Type", "Retry-After"]) {
const value = response.headers.get(name);
if (value !== null) passed.set(name, value);
}
return new Response(response.body, { headers: passed, status: response.status });
}
export const GET = forward;
export const POST = forward;
export const PATCH = forward;
export const PUT = forward;
export const DELETE = forward;
```
- **Only what the client calls.** It forwards the calls above, on the user's primary calendar's
events, with the query parameters the client sends. Anything else gets a 404, so the route can't
be used to reach the rest of their Google account.
- **Only your pages.** Browsers mark a request another site makes with
`Sec-Fetch-Site: cross-site`, and the route refuses it.
- **Errors pass through.** The status, `Retry-After` and Google's error body reach the browser, so
the client there handles 410, 412 and 429 as it would on the server.
## Map the events
`fromGoogleEvents`, from [Google Calendar events](https://time.molten.sh/docs/react/guides/google-calendar.md), maps the
[Event resource](https://developers.google.com/workspace/calendar/api/v3/reference/events) to the
calendar's events, and keeps the Google event as each one's `data`:
| Google | Calendar |
| ----------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `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. |
| `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](https://time.molten.sh/docs/react/concepts/time.md#end-times-are-exclusive) means, so it maps as it is. |
| `status: "cancelled"` | Deleted. A cancelled occurrence of a series hides that occurrence. |
| `recurrence`, `recurringEventId`, `originalStartTime` | A series' master, and its changed and cancelled occurrences. See [Series](#series-masters-not-instances). |
| `colorId` | One of Google's 11 event colors. Read by `getEventColor`. |
| `transparency` | `"transparent"` is "Show as: Free". Read by `isBusy`. |
The calendar's adapters read color and busy from `data`:
```tsx title="components/google-calendar-view.tsx"
"use client";
import {
createCalendar,
eventIdOf,
weekRange,
type CalendarEventChange,
type CalendarFocus,
type CalendarSelection,
type CalendarVisibleRange,
type EventId,
} from "@moltenship/calendar";
import {
createCanonicalRecurrenceAdapter,
createOccurrenceAdapter,
createOccurrenceExpander,
isRecurringChange,
recurrenceEditScopes,
resolveRecurrenceEdit,
type RecurrenceAdapters,
type RecurrenceEditScope,
type RecurrenceOccurrence,
} from "@moltenship/calendar-recurrence";
import { useEffect, useMemo, useState, useSyncExternalStore, type MouseEvent } from "react";
import { calendarAnnouncements } from "@/components/calendar/announcements";
import { CalendarToolbar } from "@/components/calendar/calendar-toolbar";
import type { CalendarEventColor } from "@/components/calendar/event-colors";
import { useRecurrenceScopePrompt } from "@/components/calendar/recurrence-scope-dialog/use-recurrence-scope-prompt";
import { createWeekView } from "@/components/calendar/time-grid-view/time-grid-view";
import { Button } from "@/components/ui/button";
import type { GoogleCalendarEvent, GoogleEvent } from "@/lib/google-calendar";
import { createGoogleCalendarApi, GoogleApiError } from "@/lib/google-calendar-api";
import {
createGoogleCalendarSync,
newGoogleId,
type GoogleCalendarSync,
} from "@/lib/google-calendar-sync";
/** What the calendar shows: an occurrence of a series, or a one-off event. */
export type GoogleOccurrence = RecurrenceOccurrence;
const canonical = createCanonicalRecurrenceAdapter();
export const adapters: RecurrenceAdapters = {
...canonical,
event: {
...canonical.event,
// Google's "Show as": a free event doesn't make you busy, for `busyAt`, `useBusyResources`
// and `conflictPolicy` alike. Without `transparency`, Google counts an event as busy, all-day
// ones too; its own app saves new all-day events as free.
isBusy: (event) => event.data.transparency !== "transparent",
},
};
/**
* Google's event colors, "1" (Lavender) to "11" (Tomato), as the theme's nearest. `colors.get`
* has their hex values, if you'd rather show Google's own.
*/
const googleColors: Readonly> = {
"1": "purple",
"2": "green",
"3": "purple",
"4": "pink",
"5": "yellow",
"6": "orange",
"7": "teal",
"8": "gray",
"9": "blue",
"10": "green",
"11": "red",
};
export const Calendar = createCalendar()({
eventAdapter: createOccurrenceAdapter(adapters.event),
views: [
createWeekView({
describeEvent: ({ event }) =>
event.data.transparency === "transparent" ? "free" : undefined,
// Without `colorId`, an event has its calendar's color, here blue.
getEventColor: ({ event }) => googleColors[event.data.colorId ?? ""] ?? "blue",
}),
],
});
```
- **Busy or free.** `isBusy` is the one place the calendar asks whether an event takes up time:
`busyAt`, `useBusyResources` and `conflictPolicy` all follow it, as
[Busy or available](https://time.molten.sh/docs/react/availability.md#busy-or-available) describes. Without the adapter, the
calendar treats all-day events as free, as Google's app does when it saves them. Google's API
says it with `transparency`, and counts an event without it as busy, all-day or not, so the
adapter reads the field rather than the kind.
- **Colors.** Google's `colorId` is a key into `colors.get`, "1" (Lavender) to "11" (Tomato).
The map picks the theme's nearest named color. An event without `colorId` has its calendar's
color, which `calendarList.get` returns.
- **Imports.** The view imports the `lib/` files through `@/lib/…`, the alias Next.js apps start
with. `lib/google-calendar-sync.ts` imports its neighbors with `./`.
Changes go back the other way. `toGoogleTimes` writes an interval as Google's `start` and `end`:
```ts title="lib/google-calendar-sync.ts"
/**
* An interval as Google's `start` and `end`, on `timeZone`'s clock unless the event has its own.
* Each sets the field it uses and clears the other, so a move between all-day and timed works.
*/
export function toGoogleTimes(
interval: CalendarEventInterval,
timeZone: string,
): Pick {
if (interval.kind === "all-day") {
// Google's `end.date` is the day after the last one, as the calendar's `end` is.
const date = (day: Temporal.PlainDate) => ({ date: day.toString(), dateTime: null });
return { end: date(interval.end), start: date(interval.start) };
}
const zone = (interval.kind === "timed" && interval.sourceTimeZone) || timeZone;
const time = (at: Temporal.Instant | Temporal.PlainDateTime) => ({
date: null,
// RFC 3339 with the offset, such as 2026-10-20T11:00:00+02:00.
dateTime: (at instanceof Temporal.Instant
? at.toZonedDateTimeISO(zone)
: at.toZonedDateTime(zone)
).toString({ timeZoneName: "never" }),
timeZone: zone,
});
return { end: time(interval.end), start: time(interval.start) };
}
/** Google event IDs are base32hex: lowercase a–v and digits. A UUID's hex digits fit. */
export const newGoogleId = () => crypto.randomUUID().replaceAll("-", "");
```
`events.patch` merges `start` and `end` field by field, so a write sets the field it uses and
clears the other with `null`. Without that, an event dragged from the all-day row into the time
grid would keep its `date` beside the new `dateTime`.
## Series: masters, not instances
`events.list` can return a series two ways:
- **`singleEvents=true`.** Google expands each series between `timeMin` and `timeMax` and leaves
the master out. Each occurrence is an event of its own, with its series in `recurringEventId`,
but not the series' rule.
- **Masters**, the default. Each series comes once, with its rule in `recurrence`, plus the
occurrences that changed or were cancelled. `@moltenship/calendar-recurrence` expands them for the
dates on screen, as [Show and edit recurring events](https://time.molten.sh/docs/react/recurrence/calendar.md) does.
This guide loads masters:
- **Edits need the rule.** "This and following events" ends the series before the occurrence and
starts a new one, and "All events" moves the rule. Both rewrite the master's `recurrence`, and
`resolveRecurrenceEdit` works them out from it. With `singleEvents=true` you would fetch each
master as well.
- **Smaller syncs.** A change to a series is one item in a sync, the master, rather than every
occurrence Google expanded. A series that never ends is one event.
- **Fewer requests.** Once a master has loaded, the calendar expands it for whatever dates it
shows.
The cost is expanding series yourself, which the recurrence package does, with Google's DST and
interop cases in its tests. A read-only calendar that never edits series can take
`singleEvents=true` and skip the recurrence package.
## Load the dates on screen
The calendar reports the dates it shows through `onVisibleRangeChange`. `loadInstantRange` is
those dates, and the pages a scrolling view keeps ready, as instants:
```tsx title="components/google-calendar-view.tsx"
export function GoogleCalendar({ sync, timeZone }: GoogleCalendarProps) {
const [today] = useState(() => Temporal.Now.plainDateISO(timeZone));
const events = useSyncExternalStore(sync.subscribe, sync.getEvents, sync.getEvents);
// One expander while the calendar is mounted, so series that didn't change keep their work.
const [expander] = useState(() => createOccurrenceExpander(adapters));
const [range, setRange] = useState(() => weekRange(today, { weekStartsOn: weekRules.firstDay }));
const { occurrences } = useMemo(
() => expander.expand(events, { range, timeZone }),
[expander, events, range, timeZone],
);
const [selection, setSelection] = useState(null);
const [focus, setFocus] = useState(null);
const [status, setStatus] = useState("");
const { ask, dialog } = useRecurrenceScopePrompt();
function onVisibleRangeChange({ loadInstantRange, loadRange }: CalendarVisibleRange) {
setRange(loadRange);
// `timeMin` and `timeMax` for the dates on screen, and the pages a scrolling view keeps ready.
sync
.load(loadInstantRange)
.then(loaded, (error) => setStatus(`Couldn't load: ${reasonOf(error)}`));
}
// A later load or sync that works clears a load error.
function loaded() {
setStatus((current) => (current.startsWith("Couldn't load") ? "" : current));
}
```
The sync store keeps Google's events by ID and maps each once:
```ts title="lib/google-calendar-sync.ts"
// lib/google-calendar-sync.ts
import type { CalendarEventChange, CalendarEventInterval } from "@moltenship/calendar";
import {
createCanonicalRecurrenceAdapter,
createOccurrenceExpander,
recurrenceOverrideEdit,
type RecurrenceDate,
type RecurrenceEdit,
type RecurrenceSeriesEdit,
} from "@moltenship/calendar-recurrence";
import {
fromGoogleEvents,
readGoogleRecurrence,
toGoogleRecurrence,
type GoogleCalendarEvent,
type GoogleEvent,
} from "./google-calendar";
import {
GoogleApiError,
type GoogleCalendarApi,
type GoogleEventWrite,
} from "./google-calendar-api";
/** Instants to load events for, half-open, as `onVisibleRangeChange`'s `loadInstantRange`. */
export interface TimeRange {
readonly end: Temporal.Instant;
readonly start: Temporal.Instant;
}
/** What `resolveRecurrenceEdit` returns for a change it accepted. */
export type GoogleEdit = Exclude<
RecurrenceEdit,
{ type: "rejected" }
>;
export interface GoogleCalendarSync {
/** The events loaded so far, for the expander: the same array until one changes. */
readonly getEvents: () => readonly GoogleCalendarEvent[];
/** Calls `listener` whenever the events change, and returns a function that stops it. */
readonly subscribe: (listener: () => void) => () => void;
/** Loads the events `range` needs that aren't loaded yet. */
readonly load: (range: TimeRange) => Promise;
/** Applies every change since the last sync, or syncs again from scratch after a 410. */
readonly sync: () => Promise;
/** Writes an edit to Google, then syncs. Throws, after the sync, if Google refused a write. */
readonly save: (edit: GoogleEdit, timeZone: string) => Promise;
}
const day = { hours: 24 };
export function createGoogleCalendarSync(api: GoogleCalendarApi): GoogleCalendarSync {
/** Google's events by ID: masters, changed and cancelled occurrences, one-off events. */
const stored = new Map();
const mapped = new WeakMap();
const listeners = new Set<() => void>();
let events: readonly GoogleCalendarEvent[] = [];
/** The sync covers every event from here on. */
let syncedFrom: Temporal.Instant | undefined;
/** Dates before `syncedFrom` loaded since, sorted and apart. */
let earlier: TimeRange[] = [];
let lastRange: TimeRange | undefined;
let syncToken: string | undefined;
// One request chain at a time, so an older answer never overwrites a newer one.
let queue: Promise = Promise.resolve();
function enqueue(task: () => Promise): Promise {
const run = queue.then(task, task);
queue = run.catch(() => undefined);
return run;
}
function changed() {
// Each Google event maps once, so the expander reuses its work for the ones that didn't change.
const next = [...stored.values()].flatMap((item) => {
if (!mapped.has(item)) {
const { events: mappedEvents, problems } = fromGoogleEvents([item]);
for (const problem of problems) console.warn(`Google Calendar: ${problem}`);
mapped.set(item, mappedEvents[0] ?? null);
}
return mapped.get(item) ?? [];
});
if (next.length === events.length && next.every((event, index) => event === events[index])) {
return;
}
events = next;
for (const listener of listeners) listener();
}
/** Google's answer, by ID. A cancelled occurrence stays, since it hides that occurrence. */
function apply(items: readonly GoogleEvent[]) {
const deleted = new Set();
for (const item of items) {
if (item.recurringEventId !== undefined && deleted.has(item.recurringEventId)) continue;
if (item.status !== "cancelled" || item.recurringEventId !== undefined) {
stored.set(item.id, item);
continue;
}
stored.delete(item.id);
// A deleted series takes its changed and cancelled occurrences with it, in this answer too.
deleted.add(item.id);
for (const [id, other] of stored) if (other.recurringEventId === item.id) stored.delete(id);
}
}
/** The etags of a series' master and changed occurrences, or of one occurrence's, by ID. */
function versions(seriesId: string, recurrenceId?: RecurrenceDate) {
const found = new Map();
for (const { data, override } of events) {
const inSeries = data.id === seriesId || override?.seriesId === seriesId;
const at =
recurrenceId === undefined ||
(override !== undefined &&
keyOf(override.seriesId, override.recurrenceId) === keyOf(seriesId, recurrenceId));
if (inSeries && at) found.set(data.id, data.etag);
}
return found;
}
```
The first range starts the sync. Its list has a `timeMin` and no `timeMax`, as the full sync in
Google's [sync guide](https://developers.google.com/workspace/calendar/api/guides/sync) does, so
the store gets every event from the first date on screen on, and a sync token for them. Dates
before it load when the calendar shows them, between `timeMin` and `timeMax`:
```ts title="lib/google-calendar-sync.ts"
/**
* The full sync, as Google's sync guide does it: every event that ends after the first date on
* screen, with no `timeMax`, and the token that syncs them from then on.
*/
async function fullSync(range: TimeRange) {
// All-day events are dates on the Google calendar's own clock, which may not be the one on
// screen, so lists reach a day further.
const { items, nextSyncToken } = await api.list({ timeMin: range.start.subtract(day) });
// Swapped in once the list has worked, so a failure leaves the store as it was.
stored.clear();
apply(items);
syncedFrom = range.start;
earlier = [];
syncToken = nextSyncToken;
changed();
}
async function loadNow(range: TimeRange) {
lastRange = range;
if (syncedFrom === undefined) return fullSync(range);
// Later dates are in the store already. Earlier ones load once, between two bounds.
const end = Temporal.Instant.compare(range.end, syncedFrom) < 0 ? range.end : syncedFrom;
for (const gap of missing(earlier, { end, start: range.start })) {
const { items } = await api.list({
timeMax: gap.end.add(day),
timeMin: gap.start.subtract(day),
});
apply(items);
earlier = merged(earlier, gap);
changed();
}
}
```
- **Half-open on both sides.** `timeMin` bounds an event's end and `timeMax` its start, both
exclusive, so Google returns the events that overlap `[timeMin, timeMax)`: the same rule as the
calendar's. An event that ends at midnight doesn't show on the next day.
- **All-day events** are dates on the Google calendar's clock, which may not be the viewer's, so
each list reaches a day further.
- **Later dates need no request.** Scroll forward, and the store has the events already. Scroll
back past the first date, and it lists each earlier range once.
- **Every page first.** A master on one page and its changed occurrences on the next are one
series, so the events show once the last page is in.
- **One request at a time.** Loads, syncs and writes wait for each other, so a slow answer never
overwrites a newer one.
- **One map per event.** `getEvents` returns the same array until an event changes, and the same
calendar event for a Google event that didn't change, so the expander only redoes the series
that did.
For a calendar with years of events ahead, the first list is long. Then bound it with a
`timeMax` too, and list later dates as the calendar reaches them, as it does earlier ones.
## Sync changes
A list with `syncToken` returns every event that changed since the token, and a new token:
```ts title="lib/google-calendar-sync.ts"
async function syncNow() {
if (syncToken === undefined) {
// The first load failed: try it again.
if (syncedFrom === undefined && lastRange !== undefined) await fullSync(lastRange);
return;
}
try {
// Every change since the last sync, whatever its dates.
const { items, nextSyncToken } = await api.list({ syncToken });
apply(items);
syncToken = nextSyncToken ?? syncToken;
changed();
} catch (error) {
// 410 Gone: the token expired. Sync again from scratch, from the dates on screen. Until that
// works, the old events stay, and the next sync tries again.
if (!isStatus(error, 410) || lastRange === undefined) throw error;
await fullSync(lastRange);
}
}
```
| A sync returns | The store |
| ------------------------------------------- | -------------------------------------------------------------------- |
| An event | Replaces the one with its ID, or adds it |
| A cancelled event or master | Removes it, and a master's changed and cancelled occurrences with it |
| A cancelled occurrence (`recurringEventId`) | Keeps it: it hides that occurrence |
- **The same request.** With `syncToken`, Google refuses filters such as `timeMin`, `timeMax`,
`q`, `orderBy` and `updatedMin` with a 400. Keep any other parameter the same as on the first
list.
- **One token.** Lists of earlier dates return tokens too, and the store ignores them. A newer
token would skip what changed between the two lists. Google's guide doesn't say whether the sync
token reports changes to events before its `timeMin`; the store applies whatever a sync returns.
- **A failed first load** is tried again by the next sync, so the calendar fills in once the
network is back.
- **410 Gone.** Tokens expire, and then Google answers 410. The store syncs again from scratch,
from the dates on screen. It swaps the new events in once they've loaded, so a failure keeps
what's on screen, and the next sync tries again. Try it in the demo: expire the sync token, then
sync.
### Stay live
A sync needs a reason to run. The calendar syncs after every write, when the tab comes back, and
once a minute:
```tsx title="components/google-calendar-view.tsx"
useEffect(() => {
// Catch up when the tab comes back, and every minute: push notifications can be late, or lost.
const catchUp = () => {
if (document.visibilityState === "visible") sync.sync().then(loaded, () => undefined);
};
document.addEventListener("visibilitychange", catchUp);
const timer = setInterval(catchUp, 60_000);
return () => {
document.removeEventListener("visibilitychange", catchUp);
clearInterval(timer);
};
}, [sync]);
```
To show changes as they happen, subscribe to
[push notifications](https://developers.google.com/workspace/calendar/api/guides/push). Your
server opens a watch channel for the user's calendar, with an HTTPS address of its own:
```http
POST https://www.googleapis.com/calendar/v3/calendars/primary/events/watch
Authorization: Bearer
Content-Type: application/json
{ "id": "", "type": "web_hook", "address": "https://example.com/api/google-calendar/notifications" }
```
- **Notifications carry no events.** Each one says that something changed, in
`X-Goog-Resource-State: exists`, and which channel it's for, in `X-Goog-Channel-ID`. Tell the
user's open tabs, over server-sent events or a WebSocket, and they sync. The demo's "Push
notifications" box does that part.
- **Channels expire.** Open a new one before `expiration`, and close old ones with
`channels.stop`. The first message on a channel says `sync`, and needs no action.
- **Some are lost.** Google drops notifications now and then, so keep the timer above.
## Write changes back
When someone drags or deletes an event, `onEventChange` works out what to save and hands it to
the store:
```tsx title="components/google-calendar-view.tsx"
async function onEventChange(change: OccurrenceChange) {
let scope: RecurrenceEditScope = "this";
// Google keeps deleted instances as cancelled overrides, which hide occurrences as EXDATEs do.
const options = { overrides: events, timeZone };
if (isRecurringChange(change)) {
const scopes = recurrenceEditScopes(change, adapters, options);
if (scopes.length === 0) {
setStatus("This repeating event can't change that way.");
throw new Error("No scope applies");
}
const picked = await ask({
action: change.cause === "delete" ? "delete" : "edit",
eventTitle: change.event.event.title,
scopes,
});
if (picked === null) throw new DOMException("Cancelled", "AbortError");
scope = picked;
}
const edit = resolveRecurrenceEdit(change, scope, adapters, {
...options,
// Google takes IDs you pick, so a "following" edit's new series is known before it's saved.
newSeriesId: newGoogleId(),
occurrences,
});
if (edit.type === "rejected") {
setStatus(edit.message);
throw new Error(edit.message);
}
setStatus("Saving…");
try {
// The change shows, pending, until Google answers. Throwing rolls it back.
await sync.save(edit, timeZone);
} catch (error) {
setStatus(`Not saved: ${reasonOf(error)}`);
throw error;
}
setStatus("Saved.");
if (edit.type === "series") {
setSelection((current) => renamed(current, edit.occurrenceIds));
setFocus((current) => renamed(current, edit.occurrenceIds));
}
}
```
```ts title="lib/google-calendar-sync.ts"
async function saveNow(edit: GoogleEdit, timeZone: string) {
try {
if (edit.type === "event") await saveEvent(edit.change, timeZone);
else await saveSeries(edit, timeZone);
} finally {
// Picks up what Google did, such as the newer version a 412 refused to overwrite.
await syncNow().catch((error: unknown) => console.warn("Google Calendar sync failed", error));
changed();
}
}
/** A new event, or a change to a one-off event. */
async function saveEvent(
change: CalendarEventChange,
timeZone: string,
) {
if (change.cause === "create") {
const times = toGoogleTimes(change.proposed, timeZone);
await insert({ id: newGoogleId(), summary: "New event", ...times });
return;
}
// The etag of the version on screen: if someone changed it since, Google answers 412.
const { data } = change.event;
if (change.cause === "delete") {
await remove(data, data.etag);
return;
}
const times = toGoogleTimes(change.proposed, data.start?.timeZone ?? timeZone);
apply([await api.patch(data.id, times, data.etag)]);
}
/** Inserts an event with the ID it names. A 409 means a try whose answer was lost got there. */
async function insert(event: GoogleEventWrite) {
try {
apply([await api.insert(event)]);
} catch (error) {
if (!isStatus(error, 409)) throw error;
}
}
/** Deletes an event, which Google keeps as cancelled. One already gone is done. */
async function remove(event: GoogleEvent, etag: string | undefined) {
if (event.status === "cancelled") return;
try {
await api.remove(event.id, etag);
} catch (error) {
if (!isStatus(error, 404, 410)) throw error;
}
// Google's answer to a delete has no body, so the cancelled one's etag isn't known.
apply([{ ...event, etag: undefined, status: "cancelled" }]);
}
```
- **Optimistic, with rollback.** The calendar shows the change as pending while `onEventChange`
runs, and keeps it until the events change. If it throws, the calendar puts the event back and
announces that the change wasn't saved. There's no copy of the events to restore by hand.
- **Etags.** Every Google event has an `etag` that changes on every write. Writes send the etag of
the version on screen as `If-Match`. A change to a recurring event syncs first, and stops with a
412 if the series changed in Google since the user saw it: for "This event", the occurrence
itself.
The instances it then rewrites and clears go without an etag.
- **412 Precondition Failed.** Someone changed the event since it loaded. The write is refused,
the sync after it brings in their version, and the drag rolls back onto it. The footer says what
happened. To try it: turn off push notifications, move "Design review" with the button, then drag
it. You could also retry with the new etag when their change didn't touch the times.
- **Rate limits.** The client's backoff waits it out while the change stays pending. Rate-limit two
requests in the demo, then drag an event.
- **Already deleted.** Deleting an event someone else deleted gets a 410, which counts as done.
So is deleting an occurrence someone cancelled, with "This event". Moving one throws a 410
instead, or a 412 for "This and following events" and "All events", so the change rolls back
rather than bring the occurrence back.
- **New events** get an ID from `newGoogleId`. Google takes IDs you pick, so you know an event's ID
before it's saved, as you do for "This and following events". If an insert gets a 5xx after
Google stored it, the retry gets a 409, and the event is there.
The footer under the calendar says what happened to the last change, in words:
```tsx title="components/google-calendar-view.tsx"
/** Why Google refused a request, for the user. */
function reasonOf(error: unknown): string {
if (!(error instanceof GoogleApiError)) return error instanceof Error ? error.message : "";
if (error.status === 412) return "it changed in Google Calendar. This is the latest.";
if (error.status === 410) return "it was deleted in Google Calendar.";
const rateLimited = ["rateLimitExceeded", "userRateLimitExceeded"].includes(error.reason ?? "");
if (error.status === 429 || rateLimited) return "Google is busy. Try again in a minute.";
return error.message;
}
```
### This, following and all events
A series edit from `resolveRecurrenceEdit` says what to write: the master, a new series, the edited
occurrence and the series' other changed occurrences. In Google, those are these calls:
| Scope | The edit | The Calendar API |
| ------------------------- | ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| 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. |
| This event, deleted | `series` with a new exception date | Delete the instance. Google keeps it as cancelled, and the master stays as it was. |
| 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. |
| All events | `series` | Patch the master's `start`, `end` and `recurrence`. |
| All events, deleted | `series: "delete"` | Delete the master. Google deletes its changed and cancelled occurrences with it. |
```ts title="lib/google-calendar-sync.ts"
async function saveSeries(
edit: RecurrenceSeriesEdit,
timeZone: string,
) {
const { newSeries, override, series, seriesId } = edit;
const zoneOf = (event: GoogleEvent) => event.start?.timeZone ?? timeZone;
// Google deletes a series' changed and cancelled occurrences with it.
if (series.action === "delete") {
await remove(series.event.data, series.event.data.etag);
return;
}
// The writes below replace instances the store read, some without etags. So sync first, and
// stop if the series changed in Google since the user saw it: the master and the changed
// occurrences, or for "this", the occurrence's own instance. The edit holds what they saw of
// the master and the edited occurrence; the store may have newer versions already.
const only = edit.scope === "this" ? edit.recurrenceId : undefined;
const edited = override?.action === "create" ? undefined : override?.event;
const before = versions(seriesId, only);
if (only !== undefined) before.clear();
// The edited occurrence as the user saw it: its exception, or none.
else for (const id of versions(seriesId, edit.recurrenceId).keys()) before.delete(id);
if (series.action === "update" && only === undefined) {
before.set(seriesId, series.event.data.etag);
}
if (edited !== undefined) before.set(edited.data.id, edited.data.etag);
await syncNow();
const after = versions(seriesId, only);
if (only !== undefined) {
// Cancelled in Google meanwhile: a delete is done, and a move would bring it back.
const now = events.find(
(event) => event.override?.seriesId === seriesId && after.has(event.data.id),
);
if (now?.override?.cancelled === true && before.get(now.data.id) !== now.data.etag) {
if (edit.cause === "delete") return;
throw new GoogleApiError(410, "deleted", "The occurrence was deleted in Google Calendar.");
}
}
const changedInGoogle = [...after].some(([id, etag]) => {
if (!before.has(id)) return true;
// Undefined: cancelled here, and Google's answer to a delete has no etag.
const seen = before.get(id);
return seen !== undefined && seen !== etag;
});
if (changedInGoogle || (before.has(seriesId) && !after.has(seriesId))) {
throw new GoogleApiError(412, "conditionNotMet", "The series changed in Google Calendar.");
}
// "This event" deletes cancel the occurrence's instance, as Google does, and leave the master.
if (edit.scope === "this" && edit.cause === "delete") {
const write: OccurrenceWrite = {
from: edited,
placement: "cancel",
recurrenceId: edit.recurrenceId,
seriesId,
};
await writeOccurrences([write], [], timeZone);
return;
}
// The new `recurrence` is written from what `fromGoogleEvents` read, which would drop the
// lines it couldn't, such as EXRULE.
const master = series.action === "update" ? series.event.data : undefined;
if (master !== undefined && readGoogleRecurrence(master.recurrence ?? []).problems.length > 0) {
throw new Error("This series has rules the app can't write back. Change it in Google.");
}
// The series' other changed and cancelled occurrences, which the edit moves or ends.
const others = events
.filter((event) => event.override?.seriesId === seriesId && event.data.id !== edited?.data.id)
.map((event) => ({ event, next: recurrenceOverrideEdit(edit, event.override!.recurrenceId) }))
.filter(({ next }) => next.action !== "keep");
// "This and following events" is Google's split: a new series from the occurrence on, and the
// old one ended before it. The new one goes first, so a failure leaves the old one whole.
const newSeriesId = newSeries?.id ?? newGoogleId();
if (newSeries !== undefined) {
const zone = zoneOf(newSeries.from.data);
await insert({
...contentOf(newSeries.from.data),
id: newSeriesId,
...toGoogleTimes(newSeries.placement, zone),
recurrence: toGoogleRecurrence(newSeries.recurrence, zone),
});
}
if (series.action === "update") {
const zone = zoneOf(series.event.data);
const fields = {
...toGoogleTimes(series.placement, zone),
recurrence: toGoogleRecurrence(series.recurrence, zone),
};
try {
apply([await api.patch(seriesId, fields, series.event.data.etag)]);
} catch (error) {
// With the old series still whole, the new one would repeat it: take it back.
if (newSeries !== undefined) {
await remove({ id: newSeriesId }, undefined).catch(() => undefined);
}
throw error;
}
}
// The edited occurrence, and the others, which follow the series' new times or end with it.
const writes: OccurrenceWrite[] = [];
const left: GoogleCalendarEvent[] = [];
if (override?.action === "create") {
writes.push({ placement: override.placement, recurrenceId: override.recurrenceId, seriesId });
} else if (override?.action === "update") {
writes.push({
from: override.event,
placement: override.cancelled ? "cancel" : override.placement,
recurrenceId: override.recurrenceId,
seriesId: override.series === "new" ? newSeriesId : seriesId,
});
} else if (override?.action === "delete") {
left.push(override.event);
}
for (const { event, next } of others) {
if (next.action === "delete") left.push(event);
if (next.action !== "update") continue;
writes.push({
from: event,
placement: event.override!.cancelled ? "cancel" : event,
recurrenceId: next.recurrenceId,
seriesId: next.series === "new" ? newSeriesId : seriesId,
});
}
await writeOccurrences(writes, left, timeZone);
}
/**
* Writes each occurrence to the instance at its series and original start, then clears the
* instances the moved ones leave. Google names an exception by its series and original start,
* and neither can change, so an occurrence that moves to another original start is written to
* the instance there. One may land where another leaves, so every write comes first.
*/
async function writeOccurrences(
writes: readonly OccurrenceWrite[],
left: readonly GoogleCalendarEvent[],
timeZone: string,
) {
const written = new Set();
const vacated = [...left];
for (const { from, placement, recurrenceId, seriesId } of writes) {
written.add(keyOf(seriesId, recurrenceId));
const stays =
from?.override !== undefined &&
keyOf(from.override.seriesId, from.override.recurrenceId) === keyOf(seriesId, recurrenceId);
// The etag of the version on screen, or of the instance just read.
let instance: GoogleEvent;
try {
instance = stays ? from.data : await api.instance(seriesId, recurrenceId.toString());
} catch (error) {
// An occurrence to cancel whose series is gone is gone too.
if (placement === "cancel" && !stored.has(seriesId) && isStatus(error, 404, 410)) continue;
throw error;
}
// Cancelled in Google since it loaded: a change to it would bring it back.
if (from === undefined && instance.status === "cancelled" && placement !== "cancel") {
throw new GoogleApiError(410, "deleted", "The occurrence was deleted in Google Calendar.");
}
if (placement === "cancel") await remove(instance, instance.etag);
// The moved occurrence's own title, color and the rest, not the instance's.
else await replace(instance, from?.data ?? instance, placement, instance.etag, timeZone);
if (from !== undefined && !stays) vacated.push(from);
}
for (const { data, override } of vacated) {
if (override === undefined || written.has(keyOf(override.seriesId, override.recurrenceId))) {
continue;
}
// No etags: the edit replaces these, whatever changed on them since.
const master = stored.get(override.seriesId);
const occurrence = master && occurrenceAt(master, override.recurrenceId);
// The series' rule still has an occurrence there, so it shows as the series has it.
if (master !== undefined && occurrence !== undefined) {
await replace(data, master, occurrence, undefined, timeZone);
} else {
await remove(data, undefined);
}
}
}
/**
* Replaces `instance` with `content` at `interval`: all of it, with `events.update`, so nothing
* of what was there before stays.
*/
async function replace(
instance: GoogleEvent,
content: GoogleEvent,
interval: CalendarEventInterval,
etag: string | undefined,
timeZone: string,
) {
const fields: GoogleEventWrite = {
...contentOf(content),
...toGoogleTimes(interval, content.start?.timeZone ?? timeZone),
originalStartTime: instance.originalStartTime,
recurringEventId: instance.recurringEventId,
// A cancelled instance comes back.
status: content.status === "tentative" ? "tentative" : "confirmed",
};
try {
apply([await api.update(instance.id, fields, etag)]);
} catch (error) {
// An instance the edit clears may be gone already.
if (etag !== undefined || !isStatus(error, 404, 410)) throw error;
}
}
```
- **Changed occurrences can't move.** Google names an occurrence by its series and original start,
and neither can change. When "All events" moves a series, a changed occurrence keeps its own
time and content, but its original start moves with the series. So the store writes it to the
instance at the new original start, with `events.update`, which replaces the whole instance:
nothing of what was there stays. Then it clears the instance it left: back to the series'
occurrence if the new rule still has one there, else cancelled. Every write comes before the
clearing, since one occurrence may land where another leaves.
- **"This event" deletes** cancel the instance instead of adding an EXDATE line. That's what
Google does, and it leaves the master as it was.
- **Lines it can't write.** `fromGoogleEvents` doesn't read EXRULE or RDATE periods, so writing a
master back would drop them. The store refuses series changes to such a master, and the change
rolls back.
- **What a copy keeps.** A new series, and an occurrence written to another instance, copy
everything but the fields Google sets and the ones that name the event.
- **Several requests.** A series edit is a few writes in a row. If one fails partway, the writes
before it stay in Google, the sync after it shows them, and the dragged occurrence rolls back
onto what Google has.
### Limits
- **Changed occurrences out of view.** The store knows the changed occurrences from the first date
on screen on, and in the earlier ranges it has loaded. A series edit doesn't move the ones before
those. An occurrence moved to a date more than a day before what the store has loaded shows at its
original time until the date it moved to loads.
- **Everything ahead.** The first list returns every event from the first date on screen on. See
[Load the dates on screen](#load-the-dates-on-screen) for calendars with years of them.
## Put it together
The page's calendar creates one sync store for as long as it's mounted, with the client pointed at
your route. Choose the time zone on the server, as the [Next.js guide](https://time.molten.sh/docs/react/guides/nextjs.md) says:
```tsx title="components/google-calendar-view.tsx"
/** The calendar a page renders, with one sync store for as long as it's mounted. */
export function SyncedCalendar({ timeZone }: { readonly timeZone: string }) {
// The browser calls your route, which adds the user's access token.
const [sync] = useState(() =>
createGoogleCalendarSync(createGoogleCalendarApi({ baseUrl: "/api/google-calendar" })),
);
return ;
}
```
## Sync on the server
This guide syncs in the browser, which suits a calendar the user looks at. When your server needs
the events too, for reminders, booking pages or other people's availability, run the same sync
there into your database, with a token per calendar, and let push notifications start it. The
browser then loads the dates on screen from your own API, with the same `onVisibleRangeChange`, as
[Load events with TanStack Query](https://time.molten.sh/docs/react/guides/tanstack-query.md) does.
# Load events with TanStack Query
Fetch the dates the calendar shows with useQuery, and save its changes with useMutation and optimistic updates.
Source: https://time.molten.sh/docs/react/guides/tanstack-query
> Live example: see it at https://time.molten.sh/docs/react/guides/tanstack-query
These events come from a pretend server that takes 0.7 seconds to answer. Go to another week or
month and the calendar keeps its events on screen while the next ones load. Drag an event and it
moves at once, then saves. Tick "Make requests fail" to see the error and the rollback.
Time never fetches or saves events. It tells you which dates it shows through
`onVisibleRangeChange`, and proposes changes through `onEventChange`. This guide connects both to
[TanStack Query](https://tanstack.com/query): one query per window of months, and a mutation that
shows a change before it's saved and undoes it if the save fails.
## Install
**pnpm**
```bash
pnpm add @tanstack/react-query
```
**npm**
```bash
npm install @tanstack/react-query
```
**yarn**
```bash
yarn add @tanstack/react-query
```
**bun**
```bash
bun add @tanstack/react-query
```
Put a `QueryClientProvider` above the calendar, as TanStack Query's
[quick start](https://tanstack.com/query/latest/docs/framework/react/quick-start) does.
## The API
The example talks to an API with four requests. Its events are JSON, with ISO strings for times:
```ts title="query-api.ts"
import type { CalendarEventColor } from "@/components/calendar/event-colors";
/** An event as the API sends it: JSON, with ISO strings for its times. */
export interface ApiEvent {
readonly id: string;
readonly title: string;
readonly color: CalendarEventColor;
/** Dates such as `2026-10-12` when `allDay`, otherwise instants such as `2026-10-12T07:30:00Z`. */
readonly start: string;
/** Exclusive, as the calendar's ends are. */
readonly end: string;
readonly allDay: boolean;
/** Goes up with every saved change. */
readonly version: number;
}
/** The dates one query loads, from `start` up to `end`, in a time zone. */
export interface EventsWindow {
readonly start: string;
readonly end: string;
readonly timeZone: string;
}
export interface EventsApi {
/** The events that overlap the window, also those that start before it or end after it. */
listEvents(dates: EventsWindow, signal?: AbortSignal): Promise;
createEvent(event: ApiEvent): Promise;
updateEvent(event: ApiEvent): Promise;
deleteEvent(id: string): Promise;
}
```
`listEvents` returns the events that overlap the dates, not only those that start in them, so a
trip that started on Friday still shows on Monday. A timed event overlaps when it starts before the
window's last midnight and ends after its first, in the window's time zone. An all-day event is
compared by its dates:
```ts title="query-api.ts"
/**
* Whether an event overlaps the window. Timed events are compared as instants, between the
* window's first and last midnight in its time zone; all-day events as dates.
*/
export function overlapsWindow(event: ApiEvent, { end, start, timeZone }: EventsWindow): boolean {
if (event.allDay) {
return (
Temporal.PlainDate.compare(event.start, end) < 0 &&
Temporal.PlainDate.compare(start, event.end) < 0
);
}
const from = Temporal.PlainDate.from(start).toZonedDateTime(timeZone).toInstant();
const to = Temporal.PlainDate.from(end).toZonedDateTime(timeZone).toInstant();
return (
Temporal.Instant.compare(event.start, to) < 0 && Temporal.Instant.compare(from, event.end) < 0
);
}
```
The preview's server is `createFakeEventsApi`, in the same file. It keeps events in memory and
answers after a delay. In your app, these four functions call your server.
## Read the records as they are
The cache keeps events as the API sends them, and the event adapter reads their times:
```tsx title="query-calendar.tsx"
import { createCalendar, defineEventAdapter, weekRange } from "@moltenship/calendar";
import { keepPreviousData, usePrefetchQuery, useQuery } from "@tanstack/react-query";
import { useMemo, useState } from "react";
import { calendarAnnouncements } from "@/components/calendar/announcements";
import { CalendarToolbar } from "@/components/calendar/calendar-toolbar";
import { createMonthView } from "@/components/calendar/month-view/month-view";
import { createDayView, createWeekView } from "@/components/calendar/time-grid-view/time-grid-view";
import { ViewSwitcher } from "@/components/calendar/view-switcher";
import { Button } from "@/components/ui/button";
import type { ApiEvent, EventsApi } from "./query-api";
import { eventsQuery, eventsWindow, shiftWindow, useSaveEvent, writeOf } from "./query-events";
/** Reads the API's records as they are, so the cache can keep plain JSON. */
export const eventAdapter = defineEventAdapter()({
getId: (event) => event.id,
getTitle: (event) => event.title,
getInterval: (event) =>
event.allDay
? {
kind: "all-day",
start: Temporal.PlainDate.from(event.start),
end: Temporal.PlainDate.from(event.end),
}
: {
kind: "timed",
start: Temporal.Instant.from(event.start),
end: Temporal.Instant.from(event.end),
},
getResourceIds: () => [],
});
const getEventColor = (event: ApiEvent) => event.color;
export const Calendar = createCalendar()({
eventAdapter,
views: [
createWeekView({ dayView: "day", getEventColor }),
createDayView({ getEventColor }),
createMonthView({ getEventColor }),
],
});
```
- **Plain JSON in the cache.** When a reload brings nothing new, TanStack Query's structural
sharing keeps the same array, so the calendar has nothing to redo. JSON also survives
dehydration, for [server rendering](#server-rendering).
- **No `getRevision`.** A change shown before it's saved keeps the record's old `version`. The
calendar skips a record whose revision it has seen, so it would keep the old times.
## Key the query by the dates
`onVisibleRangeChange` reports the dates the view shows, `range`, and the dates to have events
for, `loadRange`. Keep `loadRange` in state, and turn it into the window a query loads:
```ts title="query-events.ts"
/** Whole months from one date's month to another's. */
const monthsBetween = (from: Temporal.PlainDate, to: Temporal.PlainDate) =>
from.with({ day: 1 }).until(to.with({ day: 1 }), { largestUnit: "months" }).months;
/**
* The window to load for the calendar's `loadRange`: the month holding its middle day, with whole
* months either side, at least one and as many as the load range reaches.
*/
export function eventsWindow(loadRange: PlainDateInterval, timeZone: string): EventsWindow {
const { end, start } = loadRange;
const middle = start.add({ days: Math.floor(start.until(end).days / 2) }).with({ day: 1 });
const months = Math.max(
1,
monthsBetween(start, middle),
monthsBetween(middle, end.subtract({ days: 1 })),
);
return {
end: middle.add({ months: months + 1 }).toString(),
start: middle.subtract({ months }).toString(),
timeZone,
};
}
/** The window `months` later, or earlier when negative. */
export function shiftWindow({ end, start, timeZone }: EventsWindow, months: number): EventsWindow {
return {
end: Temporal.PlainDate.from(end).add({ months }).toString(),
start: Temporal.PlainDate.from(start).add({ months }).toString(),
timeZone,
};
}
```
```ts title="query-events.ts"
/** The start of every events query's key, so changes can find them all. */
export const eventsKey = ["events"] as const;
export function eventsQuery(api: EventsApi, dates: EventsWindow) {
return queryOptions({
queryKey: [...eventsKey, dates],
queryFn: ({ signal }) => api.listEvents(dates, signal),
// Going back to dates seen in the last minute shows them without asking again.
staleTime: 60_000,
});
}
```
- **Whole months.** The calendar's dates change with each step. A key made of them would load
again on every step, and cache each week apart. The window is the month that holds the middle of
the load range, with a month on either side, so the weeks of a month share one query, and so do
a month view's six weeks.
- **One month on.** When the next week or month moves the middle into the next month, the window
moves by exactly one month, so `shiftWindow` names the windows to
[prefetch](#prefetch-the-next-window).
- **Long load ranges.** A [scrolling view](https://time.molten.sh/docs/react/views/scrolling.md) loads a page on either side of
what it shows. The window grows to hold its load range, such as a scrolling month's eighteen weeks.
- **ISO strings and the time zone.** The key is JSON, which TanStack Query hashes. The same dates
are other instants in another time zone, so the zone is part of the key.
## Show what's loading
```tsx title="query-calendar.tsx"
const weekRules = { firstDay: 1, minimalDays: 4, weekend: [6, 7] } as const;
const noEvents: readonly ApiEvent[] = [];
export interface EventsCalendarProps {
readonly api: EventsApi;
readonly timeZone: string;
}
export function EventsCalendar({ api, timeZone }: EventsCalendarProps) {
const [today] = useState(() => Temporal.Now.plainDateISO(timeZone));
// The calendar reports its dates after its first render, so start from the week it opens on.
const [loadRange, setLoadRange] = useState(() =>
weekRange(today, { weekStartsOn: weekRules.firstDay }),
);
const dates = useMemo(() => eventsWindow(loadRange, timeZone), [loadRange, timeZone]);
// Until the next window loads, keep the last one's events on screen.
const events = useQuery({ ...eventsQuery(api, dates), placeholderData: keepPreviousData });
// Load the windows either side too, so the next or previous month shows at once.
usePrefetchQuery(eventsQuery(api, shiftWindow(dates, -1)));
usePrefetchQuery(eventsQuery(api, shiftWindow(dates, 1)));
const saveEvent = useSaveEvent(api);
return (
setLoadRange(range.loadRange)}
// The change shows as pending until the save settles, and rolls back if it fails.
onEventChange={async (change) => {
await saveEvent.mutateAsync(writeOf(change));
}}
defaultAnchorDate={today}
timeZone={timeZone}
locale="en-US"
weekRules={weekRules}
>
{saveEvent.isError ? (
// No live role: the calendar's announcer already says the change was undone.
Couldn't save the change, so it was undone.
Dismiss
) : events.isError ? (
Couldn't load events.
void events.refetch()} size="sm">
Try again
) : null}
);
}
```
`LoadingIndicator` and `CalendarViewSwitcher` are small components in the same file: a spinner, and
the registry's view switcher.
- **The first render.** The calendar reports its dates after it renders, and never on the server,
so the state starts from the week it opens on, from `weekRange`. The window rounds both to the
same months, so the first load is the one the calendar asks for. If it opens on a month view,
start from its grid instead.
- **`placeholderData: keepPreviousData`.** While the next window loads, `data` keeps the last
window's events, and the dates that both windows hold keep theirs. Without it, the grid would
empty for every load.
- **Loading.** `isFetching` turns on the spinner in the toolbar, and `aria-busy` on the viewport,
for every load of the window on screen, also a reload after a save.
- **Errors.** TanStack Query retries a failed load three times by default before `isError` shows
the message; the preview retries once. "Try again" calls `refetch`. A window that fails to load
has no events to keep, so the grid behind the message is empty. A failed save shows its own
message first, since it answers what the user just did, and the calendar announces it.
- **Strict Mode.** `onVisibleRangeChange` reports each change once, also when Strict Mode runs
effects twice. Setting the same range again would do nothing anyway.
### Prefetch the next window
`usePrefetchQuery` starts loading the windows a month before and after the one on screen, while
the calendar renders. It skips windows the cache already has, so it doesn't load them on every
render. Stepping into the next month then shows its events at once.
## Save changes
The calendar proposes changes and your app commits them. `onEventChange` above hands each change
to a mutation and waits for it. Until the save settles, the change shows as pending; if it fails,
the change rolls back. A change becomes a write: the event's record before and after it:
```ts title="query-events.ts"
export type ApiEventChange = CalendarEventChange;
/** What a change writes: the event's record before and after it, or `null` where there's none. */
export interface EventWrite {
readonly id: string;
readonly before: ApiEvent | null;
readonly after: ApiEvent | null;
}
/** `event` at the placement the calendar proposes. */
function placed(
event: Omit,
placement: CalendarEventPlacement,
): ApiEvent {
if (placement.kind === "floating") throw new Error("Events need a time zone.");
return {
...event,
allDay: placement.kind === "all-day",
end: placement.end.toString(),
start: placement.start.toString(),
};
}
export function writeOf(change: ApiEventChange): EventWrite {
switch (change.cause) {
case "create": {
// Picked here, so the event shown while it saves and the saved one share it.
const id = crypto.randomUUID();
const event = { color: "blue", id, title: "New event", version: 0 } as const;
return { after: placed(event, change.proposed), before: null, id };
}
case "delete":
return { after: null, before: change.event, id: change.eventId };
default:
return {
after: placed(change.event, change.proposed),
before: change.event,
id: change.eventId,
};
}
}
```
A new event gets its ID here, so the event shown while it saves and the saved one are the same
event, with no temporary ID to swap. The calendar keeps no pending copy of a new event: it shows
once it's in the cache. The record goes into every cached window it overlaps:
```ts title="query-events.ts"
/**
* Puts `event` in every cached window it overlaps, in place of the event with this `id`, and takes
* that event out of the others. `null` takes it out everywhere.
*/
export function putEvent(queryClient: QueryClient, id: string, event: ApiEvent | null): void {
const cached = queryClient.getQueriesData({ queryKey: eventsKey });
for (const [queryKey, events] of cached) {
if (events === undefined) continue;
// Keys come from `eventsQuery`: the window follows `eventsKey`.
const dates = queryKey[eventsKey.length] as EventsWindow;
const index = events.findIndex((candidate) => candidate.id === id);
let next = events;
if (event !== null && overlapsWindow(event, dates)) {
next = index === -1 ? [...events, event] : events.with(index, event);
} else if (index !== -1) {
next = events.toSpliced(index, 1);
}
if (next !== events) queryClient.setQueryData(queryKey, next);
}
}
```
And the mutation updates the cache before the save, and puts it back if the save fails:
```ts title="query-events.ts"
/**
* Reloads the events after the last save. Loads still on their way read before it, so they're
* cancelled first, and windows off screen that never loaded go, to be prefetched again.
*/
async function reloadEvents(queryClient: QueryClient): Promise {
await queryClient.cancelQueries({ queryKey: eventsKey });
queryClient.removeQueries({
queryKey: eventsKey,
predicate: (query) => query.state.data === undefined,
type: "inactive",
});
await queryClient.invalidateQueries({ queryKey: eventsKey });
}
export function useSaveEvent(api: EventsApi) {
const queryClient = useQueryClient();
return useMutation({
mutationKey: eventsKey,
// Saves reach the server one at a time, in the order they were made. Each shows at once.
scope: { id: "events" },
mutationFn: async ({ after, before, id }: EventWrite) => {
if (after === null) await api.deleteEvent(id);
else if (before === null) await api.createEvent(after);
else await api.updateEvent(after);
},
onMutate: async ({ after, id }) => {
// A reload on its way could bring back what it read before the change. Loads with nothing
// cached yet carry on, and the reload after the save replaces them.
await queryClient.cancelQueries({
queryKey: eventsKey,
predicate: (query) => query.state.data !== undefined,
});
putEvent(queryClient, id, after);
},
// Put the event back as it was, in every window. Other changes that are saving stay.
onError: (_error, { before, id }) => putEvent(queryClient, id, before),
onSettled: (_data, error) => {
// Reload once the last save settles, so a reload between two saves can't undo the second.
if (queryClient.isMutating({ mutationKey: eventsKey }) !== 1) return;
const reload = reloadEvents(queryClient);
// A saved change stays pending until the reload shows it; a failed one rolls back now.
return error === null ? reload : undefined;
},
});
}
```
1. **`scope`** sends the saves one at a time, in the order they were made, so a server never
applies an older move after a newer one. `onMutate` still runs at once for each.
2. **`onMutate`** cancels reloads on their way, which could bring back what they read before the
change, and puts the new record in the cache. A move from October to December leaves the
windows that held October and shows in those that hold December, before it's saved. Loads of
windows with nothing cached yet carry on, so prefetches aren't lost.
3. **`onError`** puts the old record back the same way. It writes only this event, rather than a
copy of the whole cache from before the change, so another change that's still saving stays.
4. **`onSettled`** reloads the events once the last save has settled. A reload between two saves
would show the first without the second. Loads still on their way read before the save, so
`reloadEvents` cancels them, drops windows off screen that never loaded (the ones next to the
window on screen are prefetched again), and then marks every events query stale, which reloads
the ones on screen. After a save,
returning the reload's promise keeps the change pending until the reload shows it. After a
failure, it returns nothing, so the change rolls back at once.
If two changes to one event both fail, the second puts back the record the first one left, which
the server never had. The next load that succeeds shows what the server has.
`mutateAsync` rejects when the save fails, after `onError` has put the old record back, so
`onEventChange` rejects too and the calendar rolls back the change.
## Server rendering
The [Next.js guide](https://time.molten.sh/docs/react/guides/nextjs.md) explains how to render the calendar on the server. With
TanStack Query, prefetch the first window on the server under the same key, and pass the cache to
the browser with TanStack Query's
[`HydrationBoundary`](https://tanstack.com/query/latest/docs/framework/react/guides/advanced-ssr).
The cache holds JSON, not Temporal objects, so it serializes as it is. Start from the same dates on
both sides, so the keys match.
# Drag tasks in with dnd-kit
Drag a backlog of your own into the calendar, and meetings back out, with dnd-kit and @moltenship/calendar-dnd-kit.
Source: https://time.molten.sh/docs/react/guides/dnd-kit
> Live example: see it at https://time.molten.sh/docs/react/guides/dnd-kit
Drag a task from the backlog onto the week: the week shows the slots it would take, from the slot
under the pointer, and it becomes a meeting there when you let go. Drag a meeting onto the backlog
and it becomes a task again. The all-day row turns red under a task, because a policy only takes
timed meetings.
Your app already uses [dnd-kit](https://dndkit.com) for its own lists, so the backlog's cards are
ordinary dnd-kit draggables. `@moltenship/calendar-dnd-kit` connects them to the calendar: a drop
goes through the calendar's slots, policies and `onEventChange` like any drag. The calendar's own
drags, moving and resizing meetings inside the week, stay on its own pointer layer. The
[API reference](https://time.molten.sh/docs/react/api/dnd-kit.md) lists every export and option.
## Install
**pnpm**
```bash
pnpm add @moltenship/calendar-dnd-kit @dnd-kit/react @dnd-kit/dom
```
**npm**
```bash
npm install @moltenship/calendar-dnd-kit @dnd-kit/react @dnd-kit/dom
```
**yarn**
```bash
yarn add @moltenship/calendar-dnd-kit @dnd-kit/react @dnd-kit/dom
```
**bun**
```bash
bun add @moltenship/calendar-dnd-kit @dnd-kit/react @dnd-kit/dom
```
The adapter takes dnd-kit 0.5, its current packages. Like the calendar, it's on npm as a release
candidate for 1.0.0.
## The calendar
The example's meetings are timed. A policy rejects any change that would make one all-day, so the
week's all-day row takes no task, and its preview shows that:
```tsx title="backlog-calendar.tsx"
import { createCalendar, defineEventAdapter, type CalendarEventChange } from "@moltenship/calendar";
import {
CalendarDndKit,
calendarDropData,
calendarEventOf,
calendarEventType,
isCalendarTarget,
} from "@moltenship/calendar-dnd-kit";
import { Accessibility } from "@dnd-kit/dom";
import { DragDropProvider, useDragDropMonitor, useDraggable, useDroppable } from "@dnd-kit/react";
import { useCallback, useMemo, useState } from "react";
import { calendarAnnouncements } from "@/components/calendar/announcements";
import { createWeekView } from "@/components/calendar/time-grid-view/time-grid-view";
export interface Meeting {
readonly end: Temporal.Instant;
readonly id: string;
readonly start: Temporal.Instant;
readonly title: string;
}
export interface Task {
readonly id: string;
readonly minutes: number;
readonly title: string;
}
export const Calendar = createCalendar()({
eventAdapter: defineEventAdapter()({
getId: (meeting) => meeting.id,
getInterval: ({ end, start }) => ({ end, kind: "timed", start }),
getResourceIds: () => [],
getTitle: (meeting) => meeting.title,
}),
views: [createWeekView()],
});
export type MeetingChange = CalendarEventChange;
/** Meetings have times: the all-day row takes no drop, and its preview says so. */
function timedOnly({ proposed }: Pick) {
return proposed !== null && proposed.kind !== "timed"
? ({ reason: "timed-only", type: "reject" } as const)
: ({ type: "accept" } as const);
}
const policies = [timedOnly];
```
## A task becomes a meeting
Each card spreads `calendarDropData` into its `data`: the record the task becomes, how long it
takes, and a title for screen readers. The record's times are placeholders; the drop decides when
the meeting is.
```tsx title="backlog-calendar.tsx"
/** The meeting a task becomes, under the task's ID. The drop decides when it is. */
export function meetingFromTask(task: Task): Meeting {
const start = Temporal.Instant.fromEpochMilliseconds(0);
return { end: start.add({ minutes: task.minutes }), id: task.id, start, title: task.title };
}
function TaskCard({ task }: { readonly task: Task }) {
const data = useMemo(
() => ({
task,
...calendarDropData({
duration: { minutes: task.minutes },
event: meetingFromTask(task),
title: task.title,
}),
}),
[task],
);
const { ref } = useDraggable({ data, id: task.id });
return (
{task.title}
,
{task.minutes} min
);
}
```
Put one `DragDropProvider` around both the backlog and the calendar, and `CalendarDndKit` inside
it. `onEventChange` gets a dropped task as a create whose `event` is the record. A range dragged
out in the week is a create without one, which this example leaves alone:
```tsx title="backlog-calendar.tsx"
const weekRules = { firstDay: 1, minimalDays: 4, weekend: [6, 7] } as const;
export interface BacklogCalendarProps {
readonly anchorDate: Temporal.PlainDate;
readonly initialMeetings: readonly Meeting[];
readonly initialTasks: readonly Task[];
readonly timeZone: string;
}
export function BacklogCalendar({
anchorDate,
initialMeetings,
initialTasks,
timeZone,
}: BacklogCalendarProps) {
const [meetings, setMeetings] = useState(initialMeetings);
const [tasks, setTasks] = useState(initialTasks);
const save = useCallback((change: MeetingChange) => {
if (change.cause === "delete") {
setMeetings((current) => current.filter(({ id }) => id !== change.eventId));
return;
}
const { proposed } = change;
if (proposed.kind !== "timed") return;
const { end, start } = proposed;
if (change.cause === "create") {
// A range dragged out in the week has no record; only dropped tasks carry one.
const dropped = change.event;
if (dropped === null) return;
setMeetings((current) => [...current, { ...dropped, end, start }]);
setTasks((current) => current.filter(({ id }) => id !== dropped.id));
return;
}
setMeetings((current) =>
current.map((meeting) =>
meeting.id === change.eventId ? { ...meeting, end, start } : meeting,
),
);
}, []);
const unscheduled = useCallback((task: Task) => setTasks((current) => [task, ...current]), []);
return (
{/* One provider around the backlog and the calendar; CalendarDndKit connects them. */}
);
}
```
The create runs through the root's policies first, so the drop on the all-day row is rejected and
the task stays in the backlog. The calendar's `Announcer` names the task as it moves over the week
and says where it was added.
## A meeting goes back to the backlog
While a meeting is dragged out of the week, it's a dnd-kit drag of type `calendarEventType`, so the
backlog takes it with `accept`, and lights up with `isDropTarget`. Dropped there, the drag ends on
the backlog and the calendar proposes nothing. The backlog proposes the delete itself, so the
policies run and the meeting hides while it saves, and turns it into a task once it's saved:
```tsx title="backlog-calendar.tsx"
/** The tasks, and a drop zone that takes meetings back off the calendar. */
function Backlog({
onUnscheduled,
tasks,
}: {
readonly onUnscheduled: (task: Task) => void;
readonly tasks: readonly Task[];
}) {
const actions = Calendar.useCalendarActions();
const { isDropTarget, ref } = useDroppable({ accept: calendarEventType, id: "backlog" });
useDragDropMonitor(
useMemo(
() => ({
onDragEnd: ({ canceled, operation }) => {
const dragged = calendarEventOf(operation.source);
if (canceled || dragged === null || operation.target?.id !== "backlog") return;
const { end, id, start, title } = dragged.event;
// Through the calendar, so policies run and the meeting hides while it saves.
void actions
.proposeEventChange({ cause: "delete", eventId: id }, { input: "pointer" })
.then((result) => {
if (result.status !== "committed") return;
onUnscheduled({ id, minutes: start.until(end).total({ unit: "minutes" }), title });
});
},
}),
[actions, onUnscheduled],
),
);
return (
{tasks.map((task) => (
))}
);
}
```
Any other end of that drag, a drop in the week or Escape, ends it as `canceled`.
## Keyboard and touch
- dnd-kit's keyboard sensor drags tasks in: focus a card, press Space, move it with the arrow
keys, Shift for bigger steps, and press Space again to drop it. The week previews and announces
each step. Meetings can't be dragged out by keyboard, so give tasks and meetings a button of their
own too, as the [demo](https://moltenship-time-demo.vercel.app) does: "Schedule" on a task opens
the event editor, and "Unschedule" in a meeting's popover moves it back.
- On a touch screen, cards use dnd-kit's touch activation and meetings the calendar's long-press.
- dnd-kit's own announcements name draggables by ID. The example gives its `Accessibility` plugin
announcements that name tasks and meetings, and stay quiet where the calendar's `Announcer`
speaks for itself:
```tsx title="backlog-calendar.tsx"
type Entity = { readonly data?: unknown; readonly id: string | number } | null;
type Announced = { readonly operation: { readonly source: Entity; readonly target: Entity } };
const taskOf = (source: Entity) => (source?.data as { task?: Task } | undefined)?.task;
const meetingOf = (source: Entity) => calendarEventOf(source)?.event;
/**
* What dnd-kit says, by name rather than its default IDs. Over the week, and for meetings until
* they reach the backlog, the calendar's own Announcer speaks instead.
*/
const announcements = {
dragstart: ({ operation }: Announced) => {
const task = taskOf(operation.source);
return task && `Picked up ${task.title}.`;
},
dragover: ({ operation }: Announced) =>
operation.target === null || isCalendarTarget(operation.target)
? undefined
: meetingOf(operation.source) && "Over the backlog.",
dragend: ({ canceled, operation }: Announced & { readonly canceled: boolean }) => {
const task = taskOf(operation.source);
if (task)
return canceled || operation.target === null
? `${task.title} stays in the backlog.`
: undefined;
const meeting = meetingOf(operation.source);
return meeting === undefined || canceled
? undefined
: `${meeting.title} is back in the backlog.`;
},
};
/** dnd-kit's default plugins, with these announcements. */
function plugins(defaults: readonly TPlugin[]) {
return [
...defaults.filter((plugin) => plugin !== (Accessibility as unknown)),
Accessibility.configure({ announcements }),
];
}
```
# Animate with Motion
Grow a clicked meeting into its card and let a card follow each drag, with Motion and the calendar's own hooks.
Source: https://time.molten.sh/docs/react/guides/motion
> Live example: see it at https://time.molten.sh/docs/react/guides/motion
Click a meeting: its chip grows into a card, and its title flies into the card's heading. Close
the card and it shrinks back into the meeting. Drag a meeting: a copy of it trails the pointer on a
spring, tilting with its speed, shows the time it would land at, and settles into the slot when
you let go, or flies back after Escape.
The calendar doesn't animate any of this itself. [Motion](https://motion.dev) does, through hooks
the calendar keeps for it:
- Every event is a `[data-event-id]` button, and its title is marked
`data-slot="calendar-event-title"` in every view, so a transition can find both.
- `monitorCalendarDrags` tells a follower where the pointer is, what the preview shows, and where
the drop landed.
You don't edit the calendar's code, and the calendar's packages don't depend on Motion.
## Install
**pnpm**
```bash
pnpm add motion
```
**npm**
```bash
npm install motion
```
**yarn**
```bash
yarn add motion
```
**bun**
```bash
bun add motion
```
## A meeting grows into its card
Motion's [`animateView`](https://motion.dev/docs/animate-view) runs a state update inside a view
transition, and `.add(from, to)` morphs one element into another. `grow` morphs the clicked chip
into the card and the chip's title into the card's heading, and `shrink` morphs them back:
```tsx title="motion-calendar.tsx"
// Settles in about half a second.
const spring = { bounce: 0.1, type: "spring", visualDuration: 0.3 } as const;
const reducedMotion = () => matchMedia("(prefers-reduced-motion: reduce)").matches;
const chipTitle = '[data-slot="calendar-event-title"]';
const card = '[data-slot="meeting-card"]';
const cardTitle = '[data-slot="meeting-card-title"]';
/** An element on the page now, and what it becomes: an element, or a selector found after. */
type Pair = readonly [from: Element | null, to: Element | string | null];
/**
* Runs `update` in a view transition that morphs a box into another, on a spring, and a title
* into another. What's inside the box swaps at `swapAt` seconds, while it's small, so neither
* side's contents stretch. Under reduced motion, or in a browser without view transitions, it
* only runs `update`.
*/
function morph(update: () => void, [box, title]: readonly [Pair, Pair], swapAt: number) {
if (reducedMotion()) return update();
const view = animateView(
async () => {
flushSync(update);
// Base UI places a popover a task after it mounts.
await new Promise((resolve) => setTimeout(resolve));
},
// A new morph, such as opening again right after Escape, cuts the last one short. Start one
// per event: Motion runs morphs started in the same task as one, without the wait above.
{ interrupt: "immediate" },
);
const swap = { delay: swapAt, duration: 0.15 };
if (box[0] !== null && box[1] !== null) {
view
.add(box[0], box[1])
.layout(spring)
.old({ opacity: [1, 0] }, swap)
.new({ opacity: [0, 1] }, swap);
}
if (title[0] !== null && title[1] !== null) {
// Uncropped, with `.morph-text` in your CSS, so each side of the text keeps its size.
view.add(title[0], title[1]).crop(false).class("morph-text").layout(spring);
}
}
/** The meeting's chip grows into the card, and its title into the card's heading. */
function grow(chip: Element, update: () => void) {
morph(
update,
[
[chip, card],
[chip.querySelector(chipTitle), cardTitle],
],
0,
);
}
/** The card shrinks back into the chip, and swaps back once it's small. */
function shrink(chip: Element, update: () => void) {
const popup = document.querySelector(card);
morph(
update,
[
[popup, chip],
[popup?.querySelector(cardTitle) ?? null, chip.querySelector(chipTitle)],
],
0.2,
);
}
```
- The update runs in `flushSync`, so React has rendered the card when the browser captures the new
state, and then waits a task, because Base UI places a popover just after it mounts.
- The box grows on a spring while what's inside it swaps with a short fade: early when it opens,
late when it closes, so neither the chip's text nor the card's is ever stretched.
- In a browser without view transitions, `animateView` only runs the update, and the card opens
at once.
A view transition draws each side of a morph as a picture stretched to the moving box. That suits
the card, whose insides swap while it's small, but would blow the title's text up as its box
widens. The title's morph gets the class `morph-text`, and one rule in your CSS keeps each side of
it at its own size:
```css title="app.css"
::view-transition-old(.morph-text),
::view-transition-new(.morph-text) {
width: auto;
height: auto;
}
```
The card is an ordinary Base UI popover. Its `data-slot`s are what `grow` looks for, and closing it
calls `shrink`:
```tsx title="motion-calendar.tsx"
interface Opened {
readonly anchor: HTMLElement;
readonly meeting: Meeting;
}
function MeetingCard({ onClose, opened }: { opened: Opened | null; onClose: () => void }) {
const close = () => {
if (opened !== null) shrink(opened.anchor, onClose);
};
return (
!open && close()}>
{opened !== null && (
opened.anchor}
data-slot="meeting-card"
data-color={opened.meeting.color}
className="flex w-72 flex-col gap-1 rounded-xl border-s-4 border-calendar-event-border bg-calendar-event p-4 text-calendar-event-foreground shadow-xl outline-none"
>
{opened.meeting.title}
{formatWhen(opened.meeting)}
Close
)}
);
}
```
Open the card from a click on the viewport. Every view renders events as `[data-event-id]`
buttons, so one listener opens any of them, and `eventIdOf` reads the meeting's ID:
```tsx title="motion-calendar.tsx"
type MeetingChange = CalendarEventChange;
function moveMeeting(meetings: readonly Meeting[], change: MeetingChange): readonly Meeting[] {
if (change.cause === "create" || change.cause === "delete") return meetings;
if (change.proposed.kind !== "timed") return meetings;
const { end, start } = change.proposed;
return meetings.map((meeting) =>
meeting.id === change.eventId ? { ...meeting, end, start } : meeting,
);
}
export function MotionCalendar() {
const [meetings, setMeetings] = useState(initialMeetings);
const [opened, setOpened] = useState(null);
const viewport = useRef(null);
// Views render each meeting as a `[data-event-id]` button, so one listener opens any of them.
const openClicked = (click: MouseEvent) => {
const anchor =
click.target instanceof Element ? click.target.closest("[data-event-id]") : null;
const meeting = meetings.find(({ id }) => anchor !== null && id === eventIdOf(anchor));
if (anchor === null || meeting === undefined) return;
grow(anchor, () => setOpened({ anchor, meeting }));
};
return (
setMeetings((current) => moveMeeting(current, change))}
defaultAnchorDate={Temporal.PlainDate.from("2026-10-08")}
defaultTimeZone="Europe/Berlin"
locale="en-US"
weekRules={weekRules}
>
setOpened(null)} />
);
}
```
While a view transition runs, about half a second, the page takes no clicks. That suits
opening a card. It doesn't suit the calendar's own navigation, which you click through quickly, so
leave paging and view switches without transitions.
## A card follows each drag
`monitorCalendarDrags` hears each meeting a view starts to move, and the follower you return
hears the rest of the drag:
| Follower method | Called |
| ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `move(point)` | On every pointer move, with the pointer in viewport coordinates |
| `preview(preview)` | Whenever the view's preview changes, or moves as the view scrolls: its boxes (`rects`), the time it shows (`label`), and whether a policy would reject or flag it (`validity`). `null` when the view shows none |
| `end(dropped, landing)` | When the drag ends. `landing` is the preview the release proposed the move at, or `null` when it proposed nothing, as after Escape. No `preview(null)` comes first |
The follower here has no `claims`, so it only watches: the drag works as it would without it. The
card is a Motion element whose position follows the pointer through a spring, and whose rotation
follows the spring's speed. When the drag ends, it flies to the landing's first box, or back to
the meeting when nothing was dropped or a policy would reject the drop. It follows only drags in
its own calendar, should the page have another:
```tsx title="motion-calendar.tsx"
interface Held {
readonly color: string | undefined;
readonly height: number;
readonly title: string;
readonly width: number;
}
const follow = { damping: 30, stiffness: 400 } as const;
/**
* A copy of each meeting moved in `within` that trails the pointer on a spring and tilts with its
* speed, over the calendar's own preview, which marks the slot. It lands where the drop is, or
* flies back.
*/
function DragCard({ within }: { readonly within: RefObject }) {
const [held, setHeld] = useState(null);
const [time, setTime] = useState(null);
const [landed, setLanded] = useState(false);
const x = useMotionValue(0);
const y = useMotionValue(0);
const springX = useSpring(x, follow);
const springY = useSpring(y, follow);
const rotate = useTransform(useVelocity(springX), [-1500, 0, 1500], [-8, 0, 8], {
clamp: true,
});
useEffect(
() =>
monitorCalendarDrags(({ element, event, origin }) => {
// Drags in other calendars on the page are theirs. Under reduced motion the calendar's
// preview alone follows the pointer.
if (within.current?.contains(element) !== true || reducedMotion()) return;
const box = element.getBoundingClientRect();
const grab = { x: origin.x - box.x, y: origin.y - box.y };
const moveTo = ({ x: left, y: top }: Pick) => {
x.set(left);
y.set(top);
};
for (const [value, at] of [
[x, box.x],
[springX, box.x],
[y, box.y],
[springY, box.y],
] as const) {
value.jump(at);
}
setLanded(false);
setTime(null);
setHeld({
color: element.dataset.color,
height: box.height,
title: event.title,
width: box.width,
});
// No `claims`: this follower only watches, and the drag goes on as before.
return {
move: (point) => moveTo({ x: point.x - grab.x, y: point.y - grab.y }),
preview: (preview) => setTime(preview?.label ?? null),
end: (_dropped, landing) => {
// Into the slot it was dropped in, or back to where it started.
const slot = landing?.validity === "invalid" ? undefined : landing?.rects[0];
moveTo(slot ?? element.getBoundingClientRect());
setLanded(true);
},
};
}),
[springX, springY, within, x, y],
);
if (held === null) return null;
return createPortal(
{
if (landed) setHeld((current) => (current === held ? null : current));
}}
>
{held.title}
{time !== null && {time} }
,
document.body,
);
}
```
The calendar's own preview still marks the slot under the card. The viewport above makes it faint
and drops its shadow, through the preview's custom properties.
## Without JavaScript
The preview itself takes CSS. The pointer layer moves it with `transform`, so the independent
`scale`, `rotate` and `translate` properties add to that rather than replace it. This lifts and
tilts it as it's picked up, with no Motion at all:
```css title="app.css"
@media (prefers-reduced-motion: no-preference) {
[data-calendar-ghost="event"] {
rotate: -2deg;
scale: 1.05;
transition:
rotate 150ms ease-out,
scale 150ms ease-out;
@starting-style {
rotate: 0deg;
scale: 1;
}
}
}
```
The media query keeps the preview still for people who ask for less motion.
`--calendar-ghost-opacity`, `--calendar-ghost-shadow`, `--calendar-ghost-background` and
`--calendar-ghost-radius` restyle it, and `data-invalid` and `data-warning` mark a drop the
policies would reject or flag.
## Reduced motion and accessibility
- `morph` checks `prefers-reduced-motion` and only runs the update when it's set. `DragCard`
follows no drag then, and the calendar's preview does the job alone.
- Focus never waits on an animation. Base UI moves focus into the card as it opens and back to the
meeting as it closes, and the calendar's `Announcer` speaks each drag as it happens.
- The drag card is `aria-hidden`: it repeats what the preview and the announcements already say.
## Cost
Motion is your app's dependency, not the calendar's. What this page's code bundles, minified and
gzipped:
| Code | Size |
| -------------------------------------------------------- | -------- |
| `grow` and `shrink`: `animateView` from `motion` | 6.6 KiB |
| `DragCard`: `motion.div` and springs from `motion/react` | 45.8 KiB |
| Both | 49.6 KiB |
If your app already uses Motion, they cost nothing more. With
[`LazyMotion`](https://motion.dev/docs/react-lazy-motion), `m.div` and `domAnimation`, the drag card
takes 31.8 KiB.
# Performance
Where Time does its work, and how to keep that work small.
Source: https://time.molten.sh/docs/react/guides/performance
Time does its work in two steps, and caches each one:
1. **Reading events.** `Root` runs your records through the adapter into a snapshot. This happens
again only when the records change.
2. **Projecting the view.** `Root` calls the active view's `project` with the snapshot and the
visible range. This happens again only when the snapshot, range, options, resources,
environment, or today's date change.
Everything else is a normal React render. These habits keep both steps rare and cheap.
## Replace records, don't mutate them
`Root` compares `events` item by item. A new array with the same record objects in the same order
counts as unchanged, so you can filter or map inline, as in `events={meetings.filter((meeting) => !meeting.cancelled)}`.
When the array changes, Time reads every record through the adapter again, except those with an
unchanged [revision](#add-a-revision-to-your-adapter); if every record comes out the same, in the
same order, it keeps its interval indexes. Update records immutably: replace the changed record with
a new object. A record changed in place keeps its identity, so if nothing else in the array changed,
the item-by-item comparison sees no change and the calendar doesn't update.
## Add a revision to your adapter
When you refetch, your data layer usually creates new objects for every record, even unchanged ones.
`getRevision` lets Time skip those. Return anything that changes whenever the record changes, such as
an `updatedAt` timestamp or a version number:
```ts
const bookingAdapter = defineEventAdapter()({
getId: (booking) => booking.id,
getTitle: (booking) => booking.summary,
getInterval: (booking) => ({ kind: "timed", start: booking.startsAt, end: booking.endsAt }),
getResourceIds: (booking) => booking.roomIds,
getRevision: (booking) => booking.updatedAt,
});
```
Records with the same ID and revision as last time reuse their earlier result. The revision must
change whenever anything the adapter reads changes; otherwise Time keeps showing the old title or
time.
## Do the heavy work in project
A view's `project` runs only when its inputs change, while its `Renderer` re-renders like any component. Put filtering, sorting, and layout in `project`, and keep the Renderer to drawing.
Inside `project`, ask the snapshot for the visible range instead of looping over every event:
```ts
project: ({ snapshot, instantRange }) => snapshot.queryTimed(instantRange),
```
Queries use an interval index, so they don't scan every event. Each snapshot also remembers the
results of its last 128 distinct queries, so asking again for the same range returns the same
array.
## Keep functions in options stable
`Root` compares `locale`, `weekRules`, `now` and a controlled `anchorDate`, `timeZone` or `view` by
value, and each view's options key by key, so an inline options object is fine. Its values are
compared by identity, though: a new function or nested object, such as a time grid's `annotations`,
is a new value.
A `getEventColor` written inline in `viewOptions` makes the view project again on
every render of the component that renders `Root`. Define it once instead:
```tsx
// At module scope, outside the component that renders Root:
const getEventColor = (meeting: Meeting) => (meeting.title === "Standup" ? "green" : "blue");
// Then, on Root:
viewOptions={{ agenda: { getEventColor } }}
```
The same goes for a `clock` object. Change handlers and `onDiagnosticsChange` can be inline: `Root`
reads them when it needs them.
## Subscribe to what you use
`useCalendarState()` and `useCalendar()` re-render their component whenever any state changes. For a
component that needs one value, use a selector:
```tsx
function ViewName() {
const view = Calendar.useCalendarSelector((state) => state.view);
return {view} ;
}
```
The component re-renders only when the selected value changes. If your selector builds a new object
each time, pass `isEqual` so equal results don't count as changes:
```ts
const position = Calendar.useCalendarSelector(
(state) => ({ view: state.view, anchorDate: state.anchorDate }),
{ isEqual: (a, b) => a.view === b.view && a.anchorDate.equals(b.anchorDate) },
);
```
# Overview
What @moltenship/calendar-recurrence is, how to install it, and a first expansion of a rule into dates.
Source: https://time.molten.sh/docs/react/recurrence
`@moltenship/calendar-recurrence` handles events that repeat. A series is stored the way
iCalendar, Google Calendar and Outlook store it: one master event with a rule, plus events that
replace single occurrences. The package does two things with a series:
- **It expands it** into the occurrences inside a range of dates, usually the dates on screen.
- **It turns a change to one occurrence into what to save** for "this event", "this and following
events" or "all events".
## Use it without the calendar
The package imports no UI framework. It depends on `@moltenship/calendar-core` and
`@moltenship/ics`, which import none either, so it expands a series on a server, in a worker or in
a script as it does in a browser.
The calendar doesn't need it, and doesn't re-export it. Occurrences reach a calendar as ordinary
events, through an adapter, so views, dragging and the event engine work the same with or without
it.
## Install
**pnpm**
```bash
pnpm add @moltenship/calendar-recurrence
```
**npm**
```bash
npm install @moltenship/calendar-recurrence
```
**yarn**
```bash
yarn add @moltenship/calendar-recurrence
```
**bun**
```bash
bun add @moltenship/calendar-recurrence
```
The package is versioned with the calendar. Keep it on the same version as the calendar, so both share one copy of
the engine.
It needs a runtime with `Temporal`, or a polyfill loaded first, and TypeScript's `ESNext` library.
[Installation](https://time.molten.sh/docs/react/installation.md#temporal) shows both.
## From a rule to dates
`parseRecurrenceRule` reads a rule as iCalendar writes it, and `expandRecurrenceRule` lists the
starts it gives from a first occurrence:
```ts title="starts.ts"
import { expandRecurrenceRule, parseRecurrenceRule } from "@moltenship/calendar-recurrence";
/** The starts of a meeting that repeats by `rrule`, a rule as iCalendar writes it. */
export function startsOf(first: Temporal.ZonedDateTime, rrule: string): string[] {
// Never throws: text without a usable rule gives no rule, and says why in `issues`.
const { rule } = parseRecurrenceRule(rrule);
if (rule === undefined) return [];
const { dates } = expandRecurrenceRule(rule, {
kind: "timed",
start: first.toInstant(),
end: first.add({ minutes: 30 }).toInstant(),
// The series repeats on this zone's wall clock.
sourceTimeZone: first.timeZoneId,
});
return dates.map((date) => date.toString());
}
export const mondays = startsOf(
Temporal.ZonedDateTime.from("2026-10-19T09:00[Europe/Berlin]"),
"FREQ=WEEKLY;BYDAY=MO;COUNT=3",
);
```
`mondays` holds three instants:
```text
2026-10-19T07:00:00Z
2026-10-26T08:00:00Z
2026-11-02T08:00:00Z
```
Each is 09:00 in Berlin. The clocks there go back on October 25, so the instant moves by an hour
and the meeting stays at 09:00. A timed series repeats on the wall clock of its own time zone.
The expansion covers RFC 5545: every `FREQ`, every `BY` part, `BYSETPOS`, `WKST`, `COUNT` and
`UNTIL`. A rule without an end is endless, so pass a window of dates as the third argument, as
[The engine](https://time.molten.sh/docs/react/recurrence/reference.md#the-engine) shows.
## From events to occurrences
A rule alone has no exceptions and no moved occurrences. For those, the package reads your own
events through two adapters and expands them together:
- `createOccurrenceExpander(adapters)` returns an expander. `expander.expand(events, range)`
returns every occurrence that overlaps the range, with exception dates left out and overrides in
place. One-off events pass through.
- `recurringEventsFromIcs(calendar.events)` groups events parsed by
[`@moltenship/ics`](https://time.molten.sh/docs/react/ics.md) into masters, overrides and one-off events, ready for the
expander.
- `resolveRecurrenceEdit` and `applyRecurrenceEdit` turn a moved, resized or deleted occurrence
into the events to write.
[Series and occurrences](https://time.molten.sh/docs/react/recurrence/model.md) explains the model these share.
## Next
- [Series and occurrences](https://time.molten.sh/docs/react/recurrence/model.md): Masters, exception dates and overrides, occurrence IDs, and what each edit scope changes.
- [Show and edit recurring events](https://time.molten.sh/docs/react/recurrence/calendar.md): Expand the dates on screen, ask which events a change applies to, and save the edit.
- [API reference](https://time.molten.sh/docs/react/recurrence/reference.md): Adapters, expansion, occurrence IDs, rules, the ICS bridge and edits.
# Series and occurrences
Series, exceptions and overrides, how each series keeps its own time, occurrence IDs, and what "this", "following" and "all" change.
Source: https://time.molten.sh/docs/react/recurrence/model
The calendar shows events, and knows nothing about series. `@moltenship/calendar-recurrence` sits
beside it: it expands each series into its occurrences for the dates on screen, and the calendar
shows those as ordinary events. Views, drag and drop, and the event engine work the same with or
without it, and apps that don't import it pay nothing for it.
This page explains the model. The [API reference](https://time.molten.sh/docs/react/recurrence/reference.md) lists every export.
[Show and edit recurring events](https://time.molten.sh/docs/react/recurrence/calendar.md) wires the model into a calendar.
## Series
Apps store repeating events the way iCalendar, Google Calendar and Outlook do:
- **A master event**, placed at the series' first occurrence, with its recurrence: a **rule**, such
as "every weekday" (RRULE), **exception dates**, occurrences that don't happen (EXDATE), and
**extra dates**, occurrences the rule doesn't give (RDATE).
- **Overrides**: separate events that each replace one occurrence, such as a meeting moved to
another time. An override names its series and the occurrence's original start
(RECURRENCE-ID). A **cancelled** override removes the occurrence, as Google's API and ICS feeds
record a deleted one.
- **One-off events**: everything else.
```text
Stand-up (master) Mon 19 Oct, 09:00–09:15 every weekday
exception date Wed 21 Oct, 09:00 no stand-up that day
Stand-up (override) replaces Thu 22 Oct, 09:00 at 10:00–10:15
Occurrences, 19–23 Oct: Mon 09:00, Tue 09:00, Thu 10:00, Fri 09:00
```
Your events keep their own shape. A recurrence adapter, beside your event adapter, reads the
recurrence of a master and what an override replaces, as an [event adapter](https://time.molten.sh/docs/react/concepts/events.md)
reads titles and times. Series can be endless, so occurrences exist only for the dates you expand,
usually the dates the calendar shows.
## Each series keeps its own time
Every date of a series has the kind of its first occurrence: an instant for a timed series, a date
for an all-day one, and a wall time for a floating one. That includes exception dates, extra dates,
the rule's end, and the original starts overrides name. A date of another kind converts, as real
feeds need: a date-only exception on a timed series excludes every occurrence that day, and a
date-only end lasts through that day.
A timed series repeats on the wall clock of its own time zone, the `sourceTimeZone` of its first
occurrence. So a 09:00 meeting stays at 09:00 across daylight saving time, and its instant moves by
an hour instead. A stand-up at 09:00 in Berlin is at 03:00 in New York most weeks, and at 04:00 in
the weeks between the two cities' clock changes. A floating series repeats at the same wall time in
every zone, and an all-day series on the same dates.
Some times and dates don't exist on a series' calendar:
- A start in a daylight saving gap, such as 02:30 on the night clocks go forward, moves forward by
the gap and still counts. A start the clock repeats takes its first instant.
- Dates no month has, such as 30 February or the fifth Friday of a month with four, are skipped and
don't count.
- The first occurrence is always one and counts toward the rule's COUNT, even when the rule
wouldn't give it. Occurrences an exception date removes still count.
## Occurrence IDs
An occurrence's ID is its series' ID and its original start: `standup::2026-10-22T07:00:00Z`.
Instants are written in UTC, and dates and wall times as they are. The ID stays the same across
views, time zones and reloads, so you can store it, select it, and link to it.
An override keeps the original start of the occurrence it replaces, so an occurrence moved on its
own keeps its ID, and with it its selection and focus. An override shows under the same ID before
its master loads. One-off events keep their own IDs.
Changing the following occurrences, or all of them, changes their original starts, and so their
IDs. The edit's `occurrenceIds` maps old IDs to new ones, so your selection can follow.
See [Keep the selection](https://time.molten.sh/docs/react/recurrence/calendar.md#keep-the-selection).
## Editing a series
When someone moves, resizes or deletes an occurrence, the app asks which events the change applies
to, then saves what that means for the series:
| Scope | A move or resize | A delete |
| ------------------------- | ------------------------------------------------------------------------ | ------------------------------- |
| This event | An override for that occurrence, or a change to its override | An exception date on the master |
| This and following events | The series ends before it, and a new series starts where it was dropped | The series ends before it |
| All events | The whole series moves or stretches by the same change, on its own clock | The master and its overrides go |
- **All events** moves the rule with the change, such as Monday to Tuesday in a weekly rule, and
moves exception dates, extra dates and the original starts overrides name, so deleted occurrences
stay deleted and moved ones don't appear twice. Overrides keep their own times.
- **This and following events** splits the series, as Google Calendar and Outlook on the web do:
later exception dates, extra dates and overrides move to the new series.
- Only scopes that can apply are offered. The first occurrence has no "This and following events",
since that's all of them, and a rule that can't follow the change, such as "the 28th of each
month" dragged to a 29th, offers only "This event".
## While the change saves
The change stays pending, and visible, while the app asks for the scope and saves it. Cancelling
the question rolls it back.
Only the occurrence that was dragged shows the change while it's pending. The calendar keeps
pending changes per event and knows nothing about series, so the rest of a series moves once your
events change and the series is expanded again.
## Limits
- **RANGE=THISANDFUTURE** isn't part of the model. Google Calendar and Outlook split series
instead, and the ICS bridge splits a series at such an override the same way, so Apple's "this and
future" changes show on every later occurrence. When the rule can't follow the change, as a
BYSETPOS rule moved to another day can't, the bridge reports it and the override replaces only its
own occurrence.
- **Drags use the calendar's clock.** In a time zone whose daylight saving time changes on other
dates than the series' zone, a drag, resize or editor change with "All events" or "This and
following events" moves the series by an hour more or less than the user did, unless the edit
gets the calendar's `timeZone`. With it, the change is replayed on the series' clock.
[The guide](https://time.molten.sh/docs/react/recurrence/calendar.md#ask-which-events-a-change-applies-to) passes it.
- **A repeated hour.** A rule can't say "the later 02:30" of the night clocks go back, so with "All
events" a start dropped on the later of two equal wall times gets an override there, and the rest
of the series repeats at the earlier one.
- **Cancelled first occurrences.** Edits read one occurrence and its series. When cancelled overrides
hide the first occurrences, "This and following events" from the next still splits the series,
unless the edit gets the series' overrides as `overrides`.
- **The ISO calendar.** Rules repeat in the ISO calendar, iCalendar's Gregorian one: a monthly series
steps by Gregorian months even when its dates use another calendar.
# Show and edit recurring events
Expand series for the dates on screen, and ask which events a change applies to.
Source: https://time.molten.sh/docs/react/recurrence/calendar
> Live example: see it at https://time.molten.sh/docs/react/recurrence/calendar
These events repeat: a stand-up every weekday, with Wednesday's skipped and Thursday's moved an
hour later, a 1:1 every other week, planning on eight Mondays, and a release day every Friday. Drag
an occurrence, or select one and delete it, and the calendar asks whether the change applies to
this event, this and following events, or all events. The change waits on screen while it asks.
This guide builds that calendar with `@moltenship/calendar-recurrence`. It expands each series into
its occurrences for the dates on screen, and turns a change to one occurrence into what to save.
[Recurring events](https://time.molten.sh/docs/react/recurrence/model.md) explains the model behind it.
## Install
The recurrence package is separate from the calendar. It doesn't use React, so you can also expand
series on a server.
**pnpm**
```bash
pnpm add @moltenship/calendar-recurrence
```
**npm**
```bash
npm install @moltenship/calendar-recurrence
```
**yarn**
```bash
yarn add @moltenship/calendar-recurrence
```
**bun**
```bash
bun add @moltenship/calendar-recurrence
```
The dialog that asks for the scope is UI source, like the views. Add it with the shadcn CLI, as
described in [UI source](https://time.molten.sh/docs/react/installation.md#ui-source-optional). It brings shadcn's `button` and
`dialog`:
```bash
npx shadcn@latest add https://time.molten.sh/r/recurrence-scope-dialog.json
```
## Wire the adapters
The calendar shows occurrences, not your events. A `RecurrenceOccurrence` is one occurrence of a
series, or a one-off event passed through, and `createOccurrenceAdapter` turns your event adapter
into the calendar's adapter for them. A recurrence adapter beside it reads what makes an event a
series' master, or an override of one occurrence. Together, they're your `RecurrenceAdapters`.
An app without an event type of its own can store `RecurringCalendarEvent`s: core's
[`CalendarEvent`](https://time.molten.sh/docs/react/concepts/events.md#records-in-times-own-shape) with an optional `recurrence`
and `override`. `createCanonicalRecurrenceAdapter` returns both adapters for them:
```tsx title="recurrence-calendar.tsx"
"use client";
import { createCalendar } from "@moltenship/calendar";
import {
createCanonicalRecurrenceAdapter,
createOccurrenceAdapter,
type RecurrenceOccurrence,
type RecurringCalendarEvent,
} from "@moltenship/calendar-recurrence";
import type { CalendarEventColor } from "@/components/calendar/event-colors";
import { createWeekView } from "@/components/calendar/time-grid-view/time-grid-view";
export interface TeamEventData {
readonly color: CalendarEventColor;
}
/**
* A series' master has a `recurrence`, an event that replaces one of its occurrences has an
* `override`, and any other event happens once.
*/
export type TeamEvent = RecurringCalendarEvent;
/** What the calendar shows: one occurrence of a series, or a one-off event. */
export type TeamOccurrence = RecurrenceOccurrence;
export const adapters = createCanonicalRecurrenceAdapter();
/** Lucide's "repeat" icon, for the chips of repeating events. */
const repeatIcon = (
);
export const Calendar = createCalendar()({
// Occurrences are the calendar's events. It reads their titles through your adapter.
eventAdapter: createOccurrenceAdapter(adapters.event),
views: [
createWeekView({
// The icon marks a repeating event on screen, and the description says so to screen readers.
describeEvent: (occurrence) => (occurrence.recurrence ? "repeating event" : undefined),
getEventColor: (occurrence) => occurrence.event.data.color,
getEventIcon: (occurrence) => (occurrence.recurrence ? repeatIcon : null),
}),
],
});
```
Views receive occurrences, so `getEventColor` reads the color from `occurrence.event`, the event
the occurrence shows: the master, the override, or the one-off event. `occurrence.recurrence` is set
on occurrences of a series, so `getEventIcon` marks their chips with a repeat icon, and
`describeEvent` adds "repeating event" to their accessible names, since the icon is decorative.
### Your own event type
With your own event type, write the recurrence adapter yourself. `getRecurrence` returns a master's
rule, exception dates and extra dates, and `getOverride` returns the series and original start an
override replaces:
```ts title="meetings.ts"
import { createCalendar, defineEventAdapter } from "@moltenship/calendar";
import {
createOccurrenceAdapter,
parseRecurrenceRule,
type RecurrenceAdapters,
type RecurrenceOccurrence,
} from "@moltenship/calendar-recurrence";
export interface Meeting {
readonly id: string;
readonly title: string;
readonly start: Temporal.Instant;
readonly end: Temporal.Instant;
/** Where it was booked. A series repeats on this zone's wall clock. */
readonly timeZone: string;
/** On a series' first meeting: an RRULE, such as "FREQ=WEEKLY;BYDAY=MO,WE". */
readonly repeats?: string;
/** Starts of meetings the series skips. */
readonly skips?: readonly Temporal.Instant[];
/** On a meeting that replaces one of a series: the series, and the start it replaces. */
readonly replaces?: { readonly seriesId: string; readonly start: Temporal.Instant };
}
export const adapters: RecurrenceAdapters = {
event: defineEventAdapter()({
getId: (meeting) => meeting.id,
getTitle: (meeting) => meeting.title,
getInterval: (meeting) => ({
kind: "timed",
start: meeting.start,
end: meeting.end,
sourceTimeZone: meeting.timeZone,
}),
getResourceIds: () => [],
}),
recurrence: {
getRecurrence: (meeting) =>
meeting.repeats === undefined
? undefined
: { rule: parseRecurrenceRule(meeting.repeats).rule, exceptionDates: meeting.skips },
getOverride: (meeting) =>
meeting.replaces && {
seriesId: meeting.replaces.seriesId,
recurrenceId: meeting.replaces.start,
},
},
};
export const Calendar = createCalendar>()({
eventAdapter: createOccurrenceAdapter(adapters.event),
});
```
- A master's `getInterval` is its first occurrence. A timed series repeats on the wall clock of
`sourceTimeZone`, so a 09:00 meeting stays at 09:00 across daylight saving time.
- `parseRecurrenceRule` reads RRULE text, with or without the `RRULE:` prefix. It never throws:
check its `issues` when you save the text, and show an error then.
- The expander reads each event once while it's the same object, so parsing in the adapter is
cheap. Replace events rather than changing them.
## Expand the dates on screen
A series can be endless, so expand it only for the dates the calendar needs. The calendar reports
them through `onVisibleRangeChange`:
```ts title="use-occurrences.ts"
import type { CalendarVisibleRange, PlainDateInterval } from "@moltenship/calendar";
import { createOccurrenceExpander } from "@moltenship/calendar-recurrence";
import { useMemo, useState } from "react";
import { adapters, type TeamEvent } from "./recurrence-calendar";
/**
* The occurrences of `events` on the dates the calendar asks for. Pass `occurrences` to `events`
* on `Root`, and `onVisibleRangeChange` to the prop of that name.
*/
export function useOccurrences(
events: readonly TeamEvent[],
timeZone: string,
// The dates the calendar opens on, so its first render isn't empty.
initialRange: PlainDateInterval,
) {
// One expander for as long as the calendar is mounted: it keeps its work for series that
// didn't change, and returns the same occurrence objects for them.
const [expander] = useState(() => createOccurrenceExpander(adapters));
const [range, setRange] = useState(initialRange);
const expansion = useMemo(
() => expander.expand(events, { range, timeZone }),
[expander, events, range, timeZone],
);
return {
issues: expansion.issues,
occurrences: expansion.occurrences,
onVisibleRangeChange: ({ loadRange }: CalendarVisibleRange) => setRange(loadRange),
};
}
```
- **One expander.** Create it once, in `useState` as here or at module scope. It keeps its work for
each series between calls, and gives back the same occurrence objects for events that didn't
change, so the calendar and its views skip them.
- **`useMemo` over events and range.** Expansion runs again only when your events or the dates
change. A new array holding the same event objects is cheap: unchanged series reuse their work.
- **`loadRange`, not `range`.** Scrolling views render a page of days on either side of the ones
they show, so a swipe never reveals empty days. `loadRange` includes those pages; `range` is only
what's visible. In paged views the two are the same.
- **The first render.** The calendar reports its range after it first renders, so the hook starts
from the week it opens on, from `weekRange`. Without a first guess, the first frame has no
events.
- **Time zones.** `timeZone` is the calendar's zone, which places the range's dates for timed
series. Series don't repeat in it. They repeat in their own `sourceTimeZone`, or, for events
without one, in the expander's `defaultTimeZone`, which is UTC unless you set it.
`expansion.issues` lists what the expander couldn't read, such as an invalid rule or an override
whose series isn't loaded, with each event and its position. Bad data never throws: the rest of
the series and the other events still show. Log the issues, as you would
[diagnostics](https://time.molten.sh/docs/react/concepts/events.md#invalid-records).
## Ask which events a change applies to
When someone drags an occurrence, the calendar calls `onEventChange` with a change whose `event` is
the occurrence. `useRecurrenceScopePrompt` from the dialog you added returns `ask`, which opens the
dialog and resolves with the scope picked, and `dialog`, to render once:
```tsx title="team-calendar.tsx"
async function onEventChange(change: OccurrenceChange) {
// A new event, or a change to a one-off event, needs no question.
let scope: RecurrenceEditScope = "this";
if (isRecurringChange(change)) {
const scopes = recurrenceEditScopes(change, adapters, { timeZone });
// None applies, so there's nothing to ask: tell the user why instead. Throwing rolls the
// change back.
if (scopes.length === 0) throw new Error("This repeating event can't change that way.");
const picked = await ask({
action: change.cause === "delete" ? "delete" : "edit",
eventTitle: change.event.event.title,
scopes,
});
// An `AbortError` is announced as a cancel, not as a change that couldn't be saved.
if (picked === null) throw new DOMException("Cancelled", "AbortError");
scope = picked;
}
const edit = resolveRecurrenceEdit(change, scope, adapters, {
// Picked now, so the IDs of a "following" edit's new series are known.
newSeriesId: crypto.randomUUID(),
occurrences,
// The zone the calendar moves occurrences on, so a series dragged by days keeps its time.
timeZone,
});
if (edit.type === "rejected") throw new Error(edit.message);
// Save the edit on your server here. The change stays pending until this function returns.
if (edit.type === "event") {
setEvents((current) => applyEventChange(current, edit.change));
return;
}
setEvents((current) =>
applyRecurrenceEdit(current, edit, { createId: () => crypto.randomUUID() }),
);
// "following" and "all" give the occurrences new IDs. The selection and keyboard focus
// follow them, and the calendar moves focus to the occurrence under its new ID.
setSelection((current) => renamed(current, edit.occurrenceIds));
setFocus((current) => renamed(current, edit.occurrenceIds));
}
```
1. **`isRecurringChange`** says whether the change is to an occurrence of a series. A new event, or
a change to a one-off event, needs no question.
2. **`ask`** opens the dialog. `action` picks its wording for an edit or a delete, and `scopes`
comes from **`recurrenceEditScopes`**, which offers only the scopes that apply: no "This and
following events" on a series' first occurrence, and only "This event" when the rule can't
follow the change, such as the 28th of each month dragged to a 29th. When none applies, the list
is empty and there's nothing to ask: tell the user why, and roll the change back.
3. **Cancel** resolves `null`. Throwing rolls the change back, as any error in `onEventChange`
does. Throw an `AbortError`, as the handler does, and the calendar's announcements say the
change was cancelled rather than that it couldn't be saved.
4. **`resolveRecurrenceEdit`** turns the change into an edit: what to save for that scope. Pass
the calendar's `timeZone` to it and to `recurrenceEditScopes`, so the change is replayed on the
series' own clock: a series dragged by days keeps its time of day when the calendar's zone and
the series' change DST on different dates, and one dragged an hour later moves an hour. If you
keep deleted occurrences as cancelled overrides, as Google's API does, pass them as `overrides`
too. A
change that needs no scope comes back as `type: "event"`, with your event unwrapped from the
occurrence, to apply as you would without recurrence. A scope that can't apply comes back as
`type: "rejected"`, with a `reason` and a `message`.
5. **Save** the edit, below. The change stays pending until `onEventChange` returns.
While the dialog is open, the change waits on screen as pending: the dragged occurrence shows where
it was dropped. Only that occurrence shows the change. The calendar keeps pending changes per event
and knows nothing about series, so for "This and following events" or "All events" the rest of the
series moves when your events change, and the calendar keeps showing the change until then.
### Deleting
The views don't delete events; your own UI does, with `proposeEventChange`. The change goes through
the same `onEventChange`, and `ask` uses the dialog's wording for a delete:
```tsx title="team-calendar.tsx"
/** The selected occurrence's title, and a button that deletes it through `onEventChange`. */
function SelectedEvent({ occurrence }: { readonly occurrence: TeamOccurrence | undefined }) {
const { proposeEventChange } = Calendar.useCalendarActions();
return (
{occurrence === undefined ? (
Click an event to select it.
) : (
<>
{occurrence.event.title}
void proposeEventChange({ cause: "delete", eventId: occurrence.id })}
size="sm"
variant="outline"
>
Delete
>
)}
);
}
```
## Save the edit
A series edit lists its writes as plain data, so you can send it to a server as it is or apply it
to your own store. If your events are `RecurringCalendarEvent`s, `applyRecurrenceEdit` applies it
and returns the new array, as `onEventChange` above does. `createId` names the events it creates:
overrides, and the series a "This and following events" edit starts when you didn't pick its ID.
With your own event type or a database, write the same steps yourself:
| Field | What to write |
| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `series` | `"update"`: the master at `placement`, its first occurrence, with `recurrence` in place of the stored one. `"delete"`: remove the master. |
| `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. |
| `override` | The edited occurrence's override: `"create"` one from the master `from`, `"update"` the stored one, or `"delete"` it. |
| `otherOverrides` | Call `recurrenceOverrideEdit(edit, recurrenceId)` for each override of `seriesId` you store, loaded or not, and keep, delete or rekey it. |
The edit describes placement and recurrence only. If the change also edited the event's title or
other fields, copy them yourself. [The reference](https://time.molten.sh/docs/react/recurrence/reference.md#recurrenceedit) describes
each write.
A "This event" delete adds the occurrence's start to the master's exception dates, which every
iCalendar store understands. Google's API records a deleted occurrence as a cancelled instance
instead; this package reads both.
## Keep the selection
An occurrence's ID is its series' ID and its original start, such as
`standup::2026-10-14T07:30:00Z`. It's stable across views, time zones and reloads, and when "This
event" moves the occurrence, since its override keeps the original start.
"This and following events" and "All events" change the original starts, and so the IDs.
`edit.occurrenceIds` maps old IDs to new ones, and the handler above moves the selection and the
keyboard focus with it: select an occurrence in the preview, drag it with "All events", and it
stays selected.
- Control `focus` with `onFocusChange`, and map it before `onEventChange` returns. `ask` resolves
once the dialog has closed and focus is back on the occurrence, and the calendar then moves focus
to the occurrence under its new ID. Left alone, focus would name the old ID, which no longer
shows.
- Pass `occurrences`, the expansion you give the calendar, so the map covers every occurrence on
screen, not only the dragged one.
- Pass `newSeriesId` for "This and following events", so the map can name the new series'
occurrences. Pick it before you save, as you would for an optimistic create.
- Map anything else that holds occurrence IDs the same way, such as an open details panel or a URL.
- Read an occurrence's series from `occurrence.recurrence`, which keeps the series ID's type. Use
`parseOccurrenceId` only for IDs you stored.
## Put it together
The whole calendar: the occurrences go to `events`, the handlers to `Root`, and the dialog renders
beside it. Clicks on events select them, through the `data-event-id` every view puts on its
events, and `SelectedEvent` is the component from [Deleting](#deleting).
```tsx title="team-calendar.tsx"
"use client";
import {
eventIdOf,
weekRange,
type CalendarEventChange,
type CalendarFocus,
type CalendarSelection,
type EventId,
} from "@moltenship/calendar";
import {
applyRecurrenceEdit,
isRecurringChange,
recurrenceEditScopes,
resolveRecurrenceEdit,
type RecurrenceEditScope,
} from "@moltenship/calendar-recurrence";
import { useState, type MouseEvent } from "react";
import { calendarAnnouncements } from "@/components/calendar/announcements";
import { CalendarToolbar } from "@/components/calendar/calendar-toolbar";
import { useRecurrenceScopePrompt } from "@/components/calendar/recurrence-scope-dialog/use-recurrence-scope-prompt";
import { Button } from "@/components/ui/button";
import { adapters, Calendar, type TeamEvent, type TeamOccurrence } from "./recurrence-calendar";
import { useOccurrences } from "./use-occurrences";
type OccurrenceChange = CalendarEventChange;
/** A selection or focus on an occurrence, moved to the occurrence's new ID after an edit. */
function renamed(
current: T | null,
ids: ReadonlyMap,
): T | null {
return current?.kind === "event"
? { ...current, eventId: ids.get(current.eventId) ?? current.eventId }
: current;
}
const weekRules = { firstDay: 1, minimalDays: 4, weekend: [6, 7] } as const;
interface TeamCalendarProps {
readonly initialEvents: readonly TeamEvent[];
readonly timeZone: string;
}
export function TeamCalendar({ initialEvents, timeZone }: TeamCalendarProps) {
const [today] = useState(() => Temporal.Now.plainDateISO(timeZone));
const [events, setEvents] = useState(initialEvents);
const [selection, setSelection] = useState(null);
const [focus, setFocus] = useState(null);
const { occurrences, onVisibleRangeChange } = useOccurrences(
events,
timeZone,
weekRange(today, { weekStartsOn: weekRules.firstDay }),
);
const { ask, dialog } = useRecurrenceScopePrompt();
async function onEventChange(change: OccurrenceChange) {
// A new event, or a change to a one-off event, needs no question.
let scope: RecurrenceEditScope = "this";
if (isRecurringChange(change)) {
const scopes = recurrenceEditScopes(change, adapters, { timeZone });
// None applies, so there's nothing to ask: tell the user why instead. Throwing rolls the
// change back.
if (scopes.length === 0) throw new Error("This repeating event can't change that way.");
const picked = await ask({
action: change.cause === "delete" ? "delete" : "edit",
eventTitle: change.event.event.title,
scopes,
});
// An `AbortError` is announced as a cancel, not as a change that couldn't be saved.
if (picked === null) throw new DOMException("Cancelled", "AbortError");
scope = picked;
}
const edit = resolveRecurrenceEdit(change, scope, adapters, {
// Picked now, so the IDs of a "following" edit's new series are known.
newSeriesId: crypto.randomUUID(),
occurrences,
// The zone the calendar moves occurrences on, so a series dragged by days keeps its time.
timeZone,
});
if (edit.type === "rejected") throw new Error(edit.message);
// Save the edit on your server here. The change stays pending until this function returns.
if (edit.type === "event") {
setEvents((current) => applyEventChange(current, edit.change));
return;
}
setEvents((current) =>
applyRecurrenceEdit(current, edit, { createId: () => crypto.randomUUID() }),
);
// "following" and "all" give the occurrences new IDs. The selection and keyboard focus
// follow them, and the calendar moves focus to the occurrence under its new ID.
setSelection((current) => renamed(current, edit.occurrenceIds));
setFocus((current) => renamed(current, edit.occurrenceIds));
}
// Apps open an event by delegating clicks on `[data-event-id]`.
function selectClicked(event: MouseEvent) {
const element = (event.target as Element).closest("[data-event-id]");
const eventId = element === null ? null : eventIdOf(element);
setSelection(eventId === null ? null : { eventId, kind: "event" });
}
const selected =
selection?.kind === "event"
? occurrences.find((occurrence) => occurrence.id === selection.eventId)
: undefined;
return (
<>
{dialog}
>
);
}
/** A change to a one-off event, or a new event, as any calendar applies it. */
function applyEventChange(
events: readonly TeamEvent[],
change: CalendarEventChange,
): readonly TeamEvent[] {
if (change.cause === "delete") return events.filter((event) => event.id !== change.eventId);
const { resourceIds: _resourceIds, ...placement } = change.proposed;
if (change.cause === "create") {
const id = crypto.randomUUID();
return [...events, { data: { color: "blue" }, id, title: "New event", ...placement }];
}
return events.map((event) =>
event.id === change.eventId
? { data: event.data, id: event.id, title: event.title, ...placement }
: event,
);
}
```
## The dialog
The dialog shows one button per scope offered, always in the same order, then Cancel. Focus starts
on the narrowest scope offered, usually "This event".
| Key | What it does |
| -------------- | ------------------------------------------------------------------------ |
| Arrow keys | Move between the scopes, wrapping at the ends. Left and Right follow RTL |
| Tab, Shift+Tab | Move through the scopes and Cancel, and stay inside the dialog |
| Enter, Space | Pick the focused scope, or cancel |
| Escape | Cancel |
When it closes, focus goes back to where it was, such as the event, and only then does `ask`
resolve. Safari skips buttons on Tab unless a setting says otherwise, so the arrow keys reach every
scope there. The wording, English, is in `recurrence-scope.ts` beside the dialog, to edit or
translate.
## Recipes
- [Google Calendar events](https://time.molten.sh/docs/react/guides/google-calendar.md): Read masters, changed and cancelled occurrences, and RRULE, EXDATE and RDATE lines from the Calendar API.
- [An ICS feed](https://time.molten.sh/docs/react/ics/feed.md#recurring-events): Group a parsed feed into series with recurringEventsFromIcs, and expand it.
# API reference
Everything @moltenship/calendar-recurrence exports. Series and adapters, expansion, occurrence IDs, rules, the ICS bridge and edits.
Source: https://time.molten.sh/docs/react/recurrence/reference
Everything on this page is exported from `@moltenship/calendar-recurrence`. The
[Overview](https://time.molten.sh/docs/react/recurrence.md) has the install command and a first example, and
[Series and occurrences](https://time.molten.sh/docs/react/recurrence/model.md) explains the model.
[Show and edit recurring events](https://time.molten.sh/docs/react/recurrence/calendar.md) wires the package into a calendar.
## Series
A series is a master event, which sits at the series' first occurrence, and any number of override
events. The package reads both through a [`RecurrenceAdapter`](#adapters). Events with neither are
one-off events, and pass through.
Every date of a series has the kind of its first occurrence. That's a `RecurrenceDate`:
| The series is | Its dates are | Its occurrence IDs end in |
| ------------- | ------------------------ | ------------------------- |
| Timed | `Temporal.Instant` | `2026-10-28T08:00:00Z` |
| All-day | `Temporal.PlainDate` | `2026-10-28` |
| Floating | `Temporal.PlainDateTime` | `2026-10-28T09:00:00` |
A date of another kind is converted with [`coerceRecurrenceDate`](#dates-of-another-kind), or
dropped with an issue when it can't be.
### EventRecurrence
An `EventRecurrence` is what makes an event a series' master: its RRULE, EXDATE, RDATE and
DURATION.
| Name | Type | Description |
| ----------------- | ------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `rule` | `RecurrenceRule` | RRULE. A series without one has only its first occurrence and its `recurrenceDates`. |
| `exceptionDates` | `readonly RecurrenceDate[]` | EXDATE: original starts of occurrences that don't happen, the first one included. A `PlainDate` on a timed or floating series excludes every occurrence that starts that day. Excluded occurrences still count toward COUNT. |
| `recurrenceDates` | `readonly (RecurrenceDate \| RecurrencePeriod)[]` | RDATE: extra occurrences. A date starts one that lasts as long as the first occurrence. A `RecurrencePeriod`, with a `start` and an `end`, keeps its own length. |
| `duration` | `Temporal.Duration` | DURATION, such as `P1D`, which keeps each occurrence's wall-clock length across DST. Without it, occurrences last exactly as long as the first. |
| `wallStart` | `Temporal.PlainDateTime` | A timed series' first start as written, when it fell in a DST gap and so resolved later. Later occurrences repeat at this wall time. Ignored unless it resolves to the first start. ICS gives it as `wallTime`. |
A `RecurrencePeriod` is an extra occurrence with its own `start` and `end`, both in the series'
kind.
`RecurrenceRule` is `@moltenship/ics`'s [`IcsRecurrenceRule`](https://time.molten.sh/docs/react/ics/reference.md#recurrence), with
`until` as a `RecurrenceDate`: `frequency`, `interval`, `count`, `until`, `byDay`, `byMonth`,
`byMonthDay`, `bySetPosition`, `weekStart` and the rest. UNTIL is inclusive. With COUNT too, the
series ends at whichever comes first.
### RecurrenceOverride
A `RecurrenceOverride` is what makes an event replace one occurrence of a series, as RECURRENCE-ID
does.
| Name | Type | Default | Description |
| -------------- | ---------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `seriesId` | `TEventId` | | Required. The master's ID. |
| `recurrenceId` | `RecurrenceDate` | | Required. The original start of the occurrence it replaces, in the series' kind. The override keeps it when it moves, and so keeps the occurrence's ID. |
| `cancelled` | `boolean` | `false` | The occurrence doesn't happen, as Google's cancelled instances and ICS overrides with STATUS:CANCELLED say. It hides the occurrence and doesn't show itself. |
An event that is both a master and an override is read as the override, with a
`conflicting-recurrence` issue.
### RecurringCalendarEvent
`RecurringCalendarEvent` is core's [`CalendarEvent`](https://time.molten.sh/docs/react/concepts/events.md#records-in-times-own-shape)
with an optional `recurrence: EventRecurrence` and `override: RecurrenceOverride`. Use it when your
app has no event type of its own, with [`createCanonicalRecurrenceAdapter`](#adapters). It's also
what [`recurringEventsFromIcs`](#ics-bridge) returns and
[`applyRecurrenceEdit`](#applyrecurrenceedit) changes.
## Adapters
A `RecurrenceAdapter` reads recurrence from your events, beside the `EventAdapter` that reads their
IDs, titles and intervals. A master's `getInterval` is its first occurrence, as DTSTART and DTEND
are. Timed series repeat on the wall clock of the interval's `sourceTimeZone`.
| Name | Type | Description |
| --------------- | -------------------------------------------- | ---------------------------------------------------------------------------- |
| `getRecurrence` | `(event) => EventRecurrence \| undefined` | Required. The recurrence of a series' master; undefined for any other event. |
| `getOverride` | `(event) => RecurrenceOverride \| undefined` | Which occurrence an override replaces; undefined for any other event. |
`RecurrenceAdapters` holds both: `{ event, recurrence }`. The
expander and the edit functions take it.
- `createCanonicalRecurrenceAdapter()` returns the adapters for
`RecurringCalendarEvent`: core's `createCanonicalEventAdapter`, and a recurrence adapter that reads
`recurrence` and `override`.
- `createOccurrenceAdapter(eventAdapter)` returns the `EventAdapter` you give the calendar, whose
events are occurrences. IDs and intervals come from the occurrence. Titles, resources, read-only
and busy state come from the event it shows, through `eventAdapter`. `isBusy` and `isReadOnly`
exist only when `eventAdapter` has them, so core's defaults still apply.
```ts
import {
createCanonicalRecurrenceAdapter,
createOccurrenceAdapter,
type RecurrenceOccurrence,
type RecurringCalendarEvent,
} from "@moltenship/calendar-recurrence";
type Event = RecurringCalendarEvent<{ color: string }>;
type Occurrence = RecurrenceOccurrence;
const adapters = createCanonicalRecurrenceAdapter<{ color: string }>();
// `createCalendar()` takes this as its `eventAdapter`.
const eventAdapter = createOccurrenceAdapter(adapters.event);
```
An occurrence's revision combines the revisions of its event and its series' master with its
interval. Without `getRevision` on your adapter, an event's revision is its object identity, so
replace events rather than changing them.
## Expansion
`createOccurrenceExpander(adapters, options)` returns an `OccurrenceExpander`.
`expander.expand(events, range)` returns the occurrences of `events` that overlap `range`:
```ts
import { createOccurrenceExpander } from "@moltenship/calendar-recurrence";
const expander = createOccurrenceExpander(adapters, { defaultTimeZone: "Europe/Berlin" });
const { occurrences, issues } = expander.expand(events, {
range: visibleRange.loadRange,
timeZone: "Europe/Berlin",
});
```
Create one expander and keep it, in `useState` or at module scope. It reuses its work for events
that are the same objects as last time: each series keeps its last four ranges and eight rule
windows, and an occurrence that comes out the same keeps its object, so memoized views don't
render again. Treat events as immutable.
`options` is an `OccurrenceExpanderOptions`:
| Name | Type | Default | Description |
| ----------------- | -------- | ---------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `defaultTimeZone` | `string` | `"UTC"` | Where timed series without `sourceTimeZone` repeat, and the zone instants are read in for all-day and floating series. Weekdays and DST follow it. A zone that isn't one reports `invalid-time-zone` for each date that needs it. |
| `maxIterations` | `number` | `DEFAULT_MAX_ITERATIONS (100,000)` | Most loop steps one series may take per expansion. A series that runs out reports `iteration-limit`. Must be a positive integer, or `createOccurrenceExpander` throws a `RangeError`. |
### OccurrenceRange
`expand` takes the dates as an `OccurrenceRange`:
| Name | Type | Description |
| ---------- | -------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `range` | `{ start: Temporal.PlainDate; end: Temporal.PlainDate }` | Required. Half-open. Pass the `loadRange` that `onVisibleRangeChange` reports, not its `range`, so the pages a scrolling view keeps ready have their occurrences. |
| `timeZone` | `string` | Required. The calendar's time zone. It places the range's dates for timed series; all-day series compare dates and floating ones wall times. |
An occurrence overlapping the range is included, even one that starts before it. Overrides and
one-off events pass through whatever the range, since your app chose to load them.
### OccurrenceExpansion
`expand` returns an `OccurrenceExpansion`: `{ occurrences, issues }`. `occurrences` holds a `RecurrenceOccurrence` for each
occurrence in the range, each override that isn't cancelled, and each one-off event. They come in
the input order of their events, and each series' in time order. IDs are unique. Each one has:
| Name | Type | Description |
| ------------ | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id` | `TEventId \| string` | Required. `occurrenceId(seriesId, recurrenceId)` for an occurrence or an override, and the event's own ID for a one-off event. See [Occurrence IDs](#occurrence-ids). |
| `interval` | `CalendarEventInterval` | Required. Where it is: the generated start and the series' length, or the override's own interval. |
| `event` | `TEvent` | Required. The event it shows: the override, the series' master, or the one-off event. |
| `recurrence` | `OccurrenceRecurrence` | Its place in its series. Absent on one-off events. |
`OccurrenceRecurrence` has the `seriesId`, the `recurrenceId` (the original start, which names the
occurrence and stays put when it moves), the `series` master and the `override` that replaces the
occurrence, when there is one. `series` is absent for an override whose master isn't among the
events, such as an invitation to one occurrence. It keeps its ID, so it matches once the master
loads.
### Issues
Bad data becomes an issue, with the event and its position in the input, rather than an
exception. A problem with one date drops only that date; the series stays.
| `code` | Meaning |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------ |
| `adapter-error` | An adapter function threw. The event is left out, and `message` names the function. |
| `date-kind-mismatch` | A date that `coerceRecurrenceDate` can't bring into the series' kind, such as a date-only RDATE on a timed series. |
| `conflicting-recurrence` | An event is both a master and an override. It's read as the override. |
| `duplicate-event-id` | Two items have the same ID, such as series `42` and `"42"`. The later one is left out. |
| `duplicate-override` | Two overrides replace the same occurrence. The later one in the input wins. |
| `invalid-rule` | The rule can't be expanded. The series still shows its first occurrence and its RDATEs. |
| `invalid-time-zone` | `sourceTimeZone` or `defaultTimeZone` isn't a time zone. Dates that need it are dropped. |
| `iteration-limit` | A series ran out of `maxIterations` before it finished the range. |
| `missing-series` | An override's master isn't among the events. It shows on its own, under its occurrence ID. |
| `unsupported-rule` | A valid RFC 5545 construct the engine doesn't handle, such as a sub-daily FREQ on an all-day series. |
Each `RecurrenceIssue` has its `code`, the `event`, its `eventId` when the adapter could read it, its
`index` in the input, and a `message`.
## Occurrence IDs
```ts
import { occurrenceId, parseOccurrenceId, recurrenceKey } from "@moltenship/calendar-recurrence";
occurrenceId("standup", Temporal.Instant.from("2026-10-28T08:00:00Z"));
// "standup::2026-10-28T08:00:00Z"
occurrenceId(42, Temporal.PlainDate.from("2026-10-28")); // "42::2026-10-28"
recurrenceKey(Temporal.Instant.from("2026-10-28T09:00:00+01:00")); // "2026-10-28T08:00:00Z"
parseOccurrenceId("standup::2026-10-28T08:00:00Z");
// { seriesId: "standup", recurrenceKey: "2026-10-28T08:00:00Z" }
parseOccurrenceId("standup"); // undefined
```
- `occurrenceId(seriesId, recurrenceId)` is `::`: the series and the
occurrence's original start. It stays the same across views, time zones and reloads, and when
an override moves the occurrence. Edits to the following occurrences or to all of them change
starts, and so IDs.
- `recurrenceKey(recurrenceId)` is the original start in ISO form: instants in UTC, dates and wall
times in the ISO calendar, without a calendar annotation. The format is stable, since apps store
IDs.
- `parseOccurrenceId(id)` splits an ID into the series ID, as a string, and the key, or returns
`undefined` for an ID that doesn't end in a key. Use it only for IDs you stored; an occurrence's
`recurrence` has the series ID with its type.
## Rules
### RRULE text
`parseRecurrenceRule(text)` reads an RRULE as a RECUR value (`FREQ=WEEKLY;BYDAY=MO`) or a content
line (`RRULE:FREQ=WEEKLY;BYDAY=MO`), as the Google Calendar API stores it. It never throws:
```ts
import { formatRecurrenceRule, parseRecurrenceRule } from "@moltenship/calendar-recurrence";
parseRecurrenceRule("RRULE:FREQ=WEEKLY;BYDAY=MO,WE;UNTIL=20261231T225959Z");
// { rule: { frequency: "WEEKLY", byDay: [{ weekday: "MO" }, { weekday: "WE" }],
// until: Temporal.Instant 2026-12-31T22:59:59Z }, issues: [] }
parseRecurrenceRule("INTERVAL=2");
// { issues: [{ severity: "error", code: "invalid-value",
// message: "\"INTERVAL=2\" has no FREQ, which a recurrence rule requires" }] }
formatRecurrenceRule({ frequency: "MONTHLY", byDay: [{ weekday: "TU", ordinal: 2 }], count: 6 });
// "FREQ=MONTHLY;COUNT=6;BYDAY=2TU"
```
- `parseRecurrenceRule` returns a `RecurrenceRuleTextResult`: `rule`, absent when the text holds
no usable rule, and `issues`. Each `RecurrenceRuleTextIssue` has a `severity`, the `code`
`@moltenship/ics` reports it under, and a `message`. Errors leave no rule. Warnings keep a
best-effort one, as when an invalid BYDAY is dropped.
- UNTIL becomes a `PlainDate` for a DATE, an `Instant` for a UTC or zoned DATE-TIME, and a
`PlainDateTime` for a floating one.
- `formatRecurrenceRule(rule)` writes the RECUR value, without `RRULE:`, its parts in RFC 5545's
order. An `Instant` UNTIL is written in UTC and rounded down to the second. It throws a
`RangeError` for an UNTIL outside the years 0 to 9999.
- `recurrenceRuleFromIcs(icsRule)` converts `IcsEvent.recurrenceRule` from `@moltenship/ics`, and
returns a `RecurrenceRuleTextResult`. An UNTIL whose TZID resolved to no time zone is an error,
since the series' end would be unknown. `recurrenceRuleToIcs(rule)` converts back.
### The engine
`expandRecurrenceRule(rule, first, window)` lists a rule's starts. The expander calls it for each
series; call it yourself to list starts without events:
```ts
import { expandRecurrenceRule } from "@moltenship/calendar-recurrence";
const start = Temporal.ZonedDateTime.from("2026-10-19T09:00[Europe/Berlin]");
const { dates, truncated } = expandRecurrenceRule(
{ frequency: "WEEKLY", byDay: [{ weekday: "MO" }] },
{
kind: "timed",
start: start.toInstant(),
end: start.add({ minutes: 30 }).toInstant(),
sourceTimeZone: "Europe/Berlin",
},
{
from: Temporal.Instant.from("2026-10-20T00:00Z"),
before: Temporal.Instant.from("2026-11-10T00:00Z"),
},
);
// dates: 2026-10-26T08:00:00Z, 2026-11-02T08:00:00Z, 2026-11-09T08:00:00Z
// (09:00 in Berlin each Monday, after the switch to winter time); truncated: false
```
It covers RFC 5545: every FREQ, every BY part, BYSETPOS, WKST, COUNT and UNTIL. `first` is a
`RecurrenceRuleStart`: the first occurrence's interval, with an optional `wallStart`. The first
occurrence is always one and counts toward COUNT. Dates that don't exist, such as 30 February,
are skipped and don't count. `window` is a `RecurrenceRuleWindow`:
| Name | Type | Default | Description |
| --------------- | ---------------- | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| `from` | `RecurrenceDate` | | Leaves out starts before this. COUNT still counts them; without COUNT, the engine skips ahead instead of stepping through every earlier period. |
| `before` | `RecurrenceDate` | | Stops before starts at or after this. |
| `maxIterations` | `number` | `DEFAULT_MAX_ITERATIONS` | Most steps to take. A step is one period the engine visits, whether or not it gives a start; periods skipped to reach from don't count. |
It returns a `RecurrenceRuleExpansion`: `dates`, strictly increasing in the kind of the first
occurrence and the ISO calendar, and `truncated`, which is `true` when `maxIterations` ran out while
the rule may still have had starts to give. `DEFAULT_MAX_ITERATIONS` is 100,000.
A rule that can never match again ends after its first occurrence, without `truncated`, when the
engine can tell up front: day parts that meet on no date, such as `BYMONTH=2;BYMONTHDAY=30`, and an
INTERVAL whose steps never reach the BY values of a fixed cycle, such as
`FREQ=MINUTELY;INTERVAL=2;BYMINUTE=1` from an even minute. The cycles are the second, minute and
hour of the day, the weekday of a DAILY rule and the month of a MONTHLY one. Other impossible
rules, such as `FREQ=MONTHLY;BYDAY=MO;BYSETPOS=6`, show only over time: they run to
`maxIterations` and report `truncated`.
For a rule it can't expand, or a `sourceTimeZone` that isn't a time zone, it throws a
`RecurrenceRuleError`, a `RangeError` whose `code` is a `RecurrenceRuleErrorCode`:
`invalid-rule`, `invalid-time-zone` or `unsupported-rule`. The expander reports the same code as an
issue. Window dates of another kind than `first`, and a `maxIterations` that isn't a positive
integer, throw a plain `RangeError`.
### Dates of another kind
Real feeds mix kinds: a UTC UNTIL on an all-day series, a date-only EXDATE on a timed one.
`coerceRecurrenceDate(date, first, role, options)` brings a date into the kind of the series' first
occurrence. It's the one place dates convert, and the expander and the ICS bridge use it.
| On a series that is | A `PlainDate` | A `PlainDateTime` | An `Instant` |
| ------------------- | ------------------------------------------------------------------------------------------- | ------------------------------- | ---------------------------------- |
| Timed | `"exception"`: stays, the whole day. `"until"`: the end of that day. `"start"`: `undefined` | its instant in the series' zone | itself |
| All-day | itself | its date | its date in `defaultTimeZone` |
| Floating | `"exception"`: stays. `"until"`: the end of that day. `"start"`: `undefined` | itself | its wall time in `defaultTimeZone` |
`role` is a `RecurrenceDateRole`: `"exception"` for EXDATE, `"start"` for RDATE and
RECURRENCE-ID, `"until"` for UNTIL. Wall times resolve with `compatible`, as RFC 5545 §3.3.5 says.
`options` is a `CoerceRecurrenceDateOptions` with a `defaultTimeZone`, UTC by default, for timed
series without `sourceTimeZone` and for instants on the other kinds. `undefined` means the date
can't stand for its role; report it and drop only that date.
## ICS bridge
`recurringEventsFromIcs(events, options)` groups the VEVENTs that `@moltenship/ics` parsed into
masters, overrides and one-off events, as `RecurringCalendarEvent`s whose `data` is the `IcsEvent`:
```ts
import {
createCanonicalRecurrenceAdapter,
createOccurrenceExpander,
recurringEventsFromIcs,
} from "@moltenship/calendar-recurrence";
import { parseIcs, type IcsEvent } from "@moltenship/ics";
const calendar = parseIcs(text).calendars[0]!;
const { events, issues } = recurringEventsFromIcs(calendar.events, {
timeZone: calendar.timeZone,
});
const expander = createOccurrenceExpander(createCanonicalRecurrenceAdapter());
```
- Masters and one-off events keep their UID as their ID. An override gets the ID of the occurrence
it replaces, `occurrenceId(uid, recurrenceId)`, with or without its master.
- A UTC DTSTART repeats in UTC, and a zoned one in its zone. A DTSTART in a DST gap keeps its
written time as `recurrence.wallStart`. It moves forward by the gap, as RFC 5545 says; a series
with DTEND in the same zone keeps the length written between them, and a single event its exact
length, unless the gap leaves it none. DURATION without DTEND becomes `recurrence.duration`.
- With `X-MICROSOFT-CDO-ALLDAYEVENT:TRUE`, an event written from midnight to a later midnight, or
from midnight without an end, as older Outlook and Exchange exports write all-day events, is
all-day on the dates written, even when its TZID resolves to no zone. Its series' midnight
EXDATE, UNTIL and RECURRENCE-ID values are those dates. UTC ones read in its DTSTART's zone (UTC
for a UTC one), else in `timeZone`.
- EXDATE, RDATE, UNTIL and RECURRENCE-ID take the series' kind through `coerceRecurrenceDate`.
- A cancelled master or one-off event is left out, with the master's overrides. A cancelled
override comes out with `override.cancelled`, which hides its occurrence.
- Of events with the same UID, or UID and RECURRENCE-ID, the highest SEQUENCE wins, then the later
one.
- RANGE=THISANDFUTURE, as Apple's "this and future" changes write it, applies to the occurrence it
names and every later one (RFC 5545 §3.8.4.4). The series splits as a "this and following" edit
splits it: it ends before the occurrence, and a new series, with the override's ID, VEVENT and
title, starts where the override is, the rest of the rule moved by the same difference. Later
EXDATEs, RDATEs and overrides move to it, and overrides take the IDs of the occurrences they then
replace. Later occurrences are keyed by their new starts, so their `recurrenceId`s aren't the
feed's RECURRENCE-IDs. On the first occurrence the whole series changes instead. A cancelled one
ends the series there, and later overrides stay. When the rule can't follow, as a BYSETPOS rule
moved to another day can't, the override replaces only the occurrence it names, with an
`unsupported-rule` issue.
`options` is an `IcsRecurringEventsOptions`:
| Name | Type | Default | Description |
| ----------------- | ----------------------- | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `timeZone` | `string` | `the feed's most used TZID, else UTC` | The feed's time zone: `calendar.timeZone` (X-WR-TIMEZONE), or one you choose. UTC times on all-day and floating series, such as an UNTIL, are read in it, so they keep the feed's dates. Floating DTSTARTs stay floating. Without it, the zone most of the events' TZIDs resolve to, as feeds without X-WR-TIMEZONE, such as Exchange's, need. Pass `"UTC"` for the reading before that default. |
| `minimumDuration` | `Temporal.DurationLike` | `{ minutes: 30 }` | How long a timed or floating event lasts when DTEND or DURATION make it zero-length or negative. Such all-day events last a day. |
It returns an `IcsRecurringEvents`: `events`, in input order, and `issues`. Bad data becomes an
issue; only invalid options throw, as a `RangeError`. Each `IcsRecurrenceIssue` has its `code`, the
`event`, its `index`, a `message` and the `property` it concerns, such as `EXDATE`:
| `code` (`IcsRecurrenceIssueCode`) | Meaning |
| --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| `date-kind-mismatch` | EXDATE, RDATE, UNTIL or RECURRENCE-ID has another kind than the series, or an unresolved TZID. It was converted, or dropped. |
| `duplicate-event` | Another VEVENT has the same UID, or the same UID and RECURRENCE-ID. The higher SEQUENCE wins, then the later one. |
| `invalid-period` | An RDATE PERIOD that doesn't end after it starts. Only its start is kept. |
| `unresolved-time-zone` | DTSTART, or the RECURRENCE-ID of an override without its master, has a TZID that resolved to no time zone. The event is skipped. |
| `unsupported-rule` | RANGE=THISANDFUTURE the series can't take, or whose series or occurrence isn't in the feed. The override replaces only that one. |
The expander reports its own issues on top, such as a rule it can't expand.
## Edits
When someone moves, resizes or deletes an occurrence, `onEventChange` receives a change whose
`event` is the occurrence: a `RecurrenceOccurrenceChange`. The edit
functions turn it into what to save.
```ts
// `ask` comes from the registry's useRecurrenceScopePrompt.
const scope = isRecurringChange(change)
? await ask({ scopes: recurrenceEditScopes(change, adapters, { timeZone }) })
: "this";
// Rolls the change back, and is announced as a cancel.
if (scope === null) throw new DOMException("Cancelled", "AbortError");
const edit = resolveRecurrenceEdit(change, scope, adapters, { newSeriesId, occurrences, timeZone });
if (edit.type === "rejected") throw new Error(edit.message);
setEvents(
(events) =>
edit.type === "series"
? applyRecurrenceEdit(events, edit, { createId })
: saveOneOff(events, edit.change), // a one-off event, unwrapped: save it as without recurrence
);
```
- `isRecurringChange(change)` is `true` for a change to an occurrence of a series, which needs a
scope. It narrows `change` to a `RecurringOccurrenceChange`. A create, or a change to a one-off
event, needs none.
- `recurrenceEditScopes(change, adapters, options)` lists the `RecurrenceEditScope`s worth
offering, in order: `"this"`, `"following"`, `"all"`. It leaves out those
`resolveRecurrenceEdit` would reject, and `"following"` where it means `"all"`, as on the first
occurrence. It's empty for a change that isn't recurring. Hand it to the dialog that asks for
the scope. [Ask which events a change applies
to](https://time.molten.sh/docs/react/recurrence/calendar.md#ask-which-events-a-change-applies-to) builds one.
- `resolveRecurrenceEdit(change, scope, adapters, options)` returns a `RecurrenceEdit`. It reads its
arguments only: it never changes them or calls your code.
Both take a `ResolveRecurrenceEditOptions`:
| Name | Type | Default | Description |
| ----------------- | --------------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `defaultTimeZone` | `string` | `"UTC"` | Where timed series without `sourceTimeZone` repeat. Pass the expander's `defaultTimeZone`. |
| `newSeriesId` | `TEventId` | | The ID the series a `"following"` edit starts will have, when you pick IDs yourself. With it, `newSeries.id` is set and `occurrenceIds` maps into the new series; without it, those occurrences are left out of the map. |
| `occurrences` | `readonly RecurrenceOccurrence[]` | | The occurrences you show, such as the expansion you give the calendar, so `occurrenceIds` maps their IDs too. |
| `overrides` | `readonly TEvent[]` | | The series' overrides, or all your events: only cancelled overrides of the edited series are read. They then hide occurrences as EXDATEs do, so `"following"` from the first occurrence left to show is `"all"`. Pass them when you keep deleted occurrences as cancelled overrides, as Google's API does. |
| `maxIterations` | `number` | | Most loop steps a `"following"` edit's search for the previous occurrence may take. |
| `timeZone` | `string` | | The calendar's time zone, which occurrences are moved and resized on and the editor shows times in. `"all"` and `"following"` replay the change, calendar days and then exact time, on the series' own clock: a drag by a week keeps its time of day, a drag an hour later moves it an hour, and a resize by days stretches it by days, even in a week when the calendar's zone has changed DST and the series' hasn't. Without it, the calendar is taken to show the series' own zone, and the series takes the instants it proposes, which are an hour off then. An override in another zone replays on its own clock. |
### What each scope does
- **`"this"`.** A move, resize or update creates the occurrence's override, or updates it. Its
`recurrenceId` stays, so the occurrence keeps its ID. A delete adds the original start to the
master's `exceptionDates` and deletes an existing override. An override whose master isn't
loaded is marked `cancelled` instead. Google's API records a deleted instance as a cancelled one;
this package reads those, but writes EXDATE, which every iCalendar store understands.
- **`"following"`.** The master ends before the occurrence: UNTIL becomes the previous
occurrence's start, or COUNT the number of occurrences before it. A new series starts where the
change puts the occurrence, with the rest of the rule moved as `"all"` moves it, and later
EXDATEs, RDATEs and overrides move to it. A delete only ends the series. Google Calendar and
Outlook on the web split a series the same way. When nothing before the occurrence is left to
show, it's `"all"`: EXDATEs count for that, and cancelled overrides when you pass `overrides`.
- **`"all"`.** The change from where the occurrence showed to where it goes, measured on the
series' wall clock, applies to every occurrence. The rule moves with it, such as BYDAY when the
day changes, and so do EXDATEs, RDATEs, UNTIL and every override's `recurrenceId`, so deleted
occurrences stay deleted and moved ones don't appear twice. Overrides keep their own placements.
A move keeps the series' length; a resize changes it. A delete removes the master and its
overrides. An occurrence dropped on the later of two equal wall times, as DST's end repeats an
hour, gets an override there, since a rule can only say the earlier one, where the rest of the
series goes.
A timed occurrence dropped on a day, or an all-day one dropped on a time, works in every scope.
`"following"` and `"all"` change the series' kind and convert its dates; a rule with several times
a day can't become all-day.
### RecurrenceEdit
A `RecurrenceEdit` is one of three types:
- `{ type: "event", change }`, a `RecurrenceEventEdit`: a create, or a change to a one-off event,
with the event unwrapped. Apply `change` as you would without recurrence.
- `{ type: "series", … }`, a `RecurrenceSeriesEdit`, below.
- `{ type: "rejected", reason, message }`, a `RecurrenceEditRejection`: the scope can't apply.
A `RecurrenceSeriesEdit` describes the writes as plain data. Only placement and recurrence are
described; copy anything else an `"update"` changed, such as the title, yourself.
| Name | Type | Description |
| ---------------- | ------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `scope` | `RecurrenceEditScope` | Required. The scope applied. `"following"` on the first occurrence is `"all"`. |
| `cause` | `"move" \| "resize-start" \| "resize-end" \| "update" \| "delete"` | Required. The change's cause. |
| `seriesId` | `TEventId` | Required. The master's ID. |
| `recurrenceId` | `RecurrenceDate` | Required. The edited occurrence's original start. |
| `series` | `RecurrenceSeriesWrite` | Required. The master: `keep`, `update` with its new `placement` (its first occurrence) and whole `recurrence`, or `delete`. |
| `newSeries` | `RecurrenceNewSeries` | The series a `"following"` edit starts: copy `from`, the old master, except its ID, placement and recurrence; give it `placement`, `recurrence`, and `id` when you passed `newSeriesId`. |
| `override` | `RecurrenceOverrideWrite` | The edited occurrence's override: `create` one from the master at `placement`, `update` the existing one (its placement, `recurrenceId`, `cancelled`, and its series when `series` is `"new"`), or `delete` it. |
| `otherOverrides` | `RecurrenceOverridesRule` | Required. What happens to the series' other overrides, as a rule, since you may not have them all loaded. Apply `recurrenceOverrideEdit` to each one you store. |
| `occurrenceIds` | `ReadonlyMap` | Required. Old occurrence IDs to new ones, for your selection: the edited occurrence's and those in `options.occurrences` whose IDs change. Empty for `"this"`. |
`RecurrenceSeriesWrite`, `RecurrenceNewSeries` and `RecurrenceOverrideWrite` are the types of
`series`, `newSeries` and `override`. A placement is a `CalendarEventPlacement`: an interval and its
`resourceIds`.
### recurrenceOverrideEdit
`recurrenceOverrideEdit(edit, recurrenceId)` says what an edit does to one stored override of
`edit.seriesId`, by its `recurrenceId`. It returns a `RecurrenceOverrideRekey`:
- `{ action: "keep" }`, as for the edited occurrence's own override, which `edit.override`
covers;
- `{ action: "delete" }`;
- `{ action: "update", recurrenceId, series }`: its new original start, and `"new"` when it moves
to the series a `"following"` edit starts. Its own placement stays.
`otherOverrides` is a `RecurrenceOverridesRule`: an `action` (`"keep"`, `"rekey"` or `"delete"`),
`after`, the original start after which it applies, `series`, and `shift`, a `RecurrenceKeyShift`
that says how original starts move. Read them through `recurrenceOverrideEdit`; the fields of
`RecurrenceKeyShift` and of its `RecurrenceOrdinalShift`, which moves ordinal weekdays such as the
2nd Tuesday within their month or year, may change.
### Rejections
`RecurrenceEditRejection.reason` is a `RecurrenceEditRejectionReason`:
| `reason` | Meaning |
| -------------------- | -------------------------------------------------------------------------------------------------------- |
| `date-kind-mismatch` | The change's dates don't fit the series' kind. |
| `extra-occurrence` | `"following"` from an occurrence only an RDATE adds, which no rule can continue from. |
| `invalid-rule` | The engine can't expand the rule, or the one the edit would write. |
| `invalid-time-zone` | The series' or the placement's zone isn't one Temporal knows. |
| `iteration-limit` | The search for the previous occurrence ran past `maxIterations`. |
| `missing-series` | `"following"` or `"all"` on an override whose master isn't loaded. |
| `rule-cannot-move` | The rule can't follow the change, such as a BYSETPOS rule moved to another day, or the 28th to the 29th. |
| `unknown-occurrence` | The rule doesn't produce the occurrence any more. |
| `unsupported-rule` | The engine doesn't handle the rule, or the one the edit would write. |
`recurrenceEditScopes` leaves out the scopes that would be rejected, so the dialog offers only
scopes that apply.
### applyRecurrenceEdit
`applyRecurrenceEdit(events, edit, { createId })` applies a series edit to an array of
`RecurringCalendarEvent`s and returns a new array. It updates or deletes the master, adds the
series a `"following"` edit starts, writes the edited occurrence's override, and applies
`recurrenceOverrideEdit` to every other override of the series. Events it doesn't touch stay the
same objects.
`createId(event)`, the one field of `ApplyRecurrenceEditOptions`, returns the ID of an event the
edit creates: an override, or the new series when `newSeries.id` isn't set. It gets the event
without its ID. Apps with their own event type or store write the same steps themselves.
See [Save the edit](https://time.molten.sh/docs/react/recurrence/calendar.md#save-the-edit).
# Overview
What @moltenship/ics is, how to install it, and a first parse of iCalendar text into Temporal values.
Source: https://time.molten.sh/docs/react/ics
`@moltenship/ics` reads iCalendar (RFC 5545), the text format of calendar feeds, invitations and
exports from Google Calendar, Outlook, iCloud and most other calendar apps. ICS text goes in.
Calendars, events, to-dos, journals, free/busy and time zones come out, with dates and times as
`Temporal` values and every problem in the text listed with its line.
## Use it without the calendar
The package imports no other Moltenship package, no UI framework and no dependency. It runs
wherever `Temporal` does: in a browser, on a server, in a worker or in a script. An app that never
renders a calendar can use it to read a feed, check an upload or convert an export.
`@moltenship/calendar` doesn't re-export it, so install it by its own name.
## Install
**pnpm**
```bash
pnpm add @moltenship/ics
```
**npm**
```bash
npm install @moltenship/ics
```
**yarn**
```bash
yarn add @moltenship/ics
```
**bun**
```bash
bun add @moltenship/ics
```
The package is versioned with the calendar.
It needs a runtime with `Temporal`, or a polyfill loaded first, and TypeScript's `ESNext` library.
[Installation](https://time.molten.sh/docs/react/installation.md#temporal) shows both.
## Parse a calendar
`parseIcs` takes the text and returns its calendars. `getEventEnd` works out when an event ends,
from its `DTEND` or its `DURATION`:
```ts title="describe-events.ts"
import { getEventEnd, parseIcs, type IcsDateValue } from "@moltenship/ics";
export const text = `BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Example//Team//EN
BEGIN:VEVENT
UID:planning@example.com
DTSTAMP:20261001T080000Z
DTSTART;TZID=Europe/Berlin:20261012T090000
DURATION:PT45M
SUMMARY:Planning
END:VEVENT
BEGIN:VEVENT
UID:offsite@example.com
DTSTAMP:20261001T080000Z
DTSTART;VALUE=DATE:20261015
DTEND;VALUE=DATE:20261017
SUMMARY:Offsite
END:VEVENT
END:VCALENDAR`;
// A date or a time, as the file wrote it.
function show(value: IcsDateValue): string {
switch (value.kind) {
case "date":
return value.date.toString();
case "utc":
return value.instant.toString();
case "zoned":
return value.zoned.toString();
case "floating":
case "unresolved":
return value.wallTime.toString();
}
}
export function describeEvents(ics: string): string[] {
const { calendars } = parseIcs(ics);
const events = calendars[0]?.events ?? [];
// getEventEnd reads DTEND, or adds DURATION to the start.
return events.map(
(event) => `${event.summary}: ${show(event.start)} to ${show(getEventEnd(event))}`,
);
}
```
`describeEvents(text)` returns these lines:
```text
Planning: 2026-10-12T09:00:00+02:00[Europe/Berlin] to 2026-10-12T09:45:00+02:00[Europe/Berlin]
Offsite: 2026-10-15 to 2026-10-17
```
The first event names a time zone, so its start is a `Temporal.ZonedDateTime`. The second is an
all-day event, so its start is a `Temporal.PlainDate`, and its end is the day after its last day,
as the file wrote it. A start's `kind` says which of five shapes the file used, and
[Dates and times](https://time.molten.sh/docs/react/ics/reference.md#dates-and-times) lists them.
## Try it
Edit the text below to see what `parseIcs` returns. The sample is a Google Calendar feed with a
recurring meeting, an all-day event, an event imported from Outlook, and one date written the way
a careless exporter writes it.
> Live example: see it at https://time.molten.sh/docs/react/ics
## What it does with bad text
Parsing is lenient. The parser keeps what it can read, skips a component it can't type, such as an
event without `UID` or `DTSTART`, and reports each problem in `issues` with its line. Bad text
never throws. With `strict: true`, an error throws an `IcsParseError` instead.
[Read an .ics file](https://time.molten.sh/docs/react/ics/import.md) shows both ways.
## What it doesn't do
- **It doesn't expand recurring events.** A rule is parsed into an `IcsRecurrenceRule`, and its
occurrences aren't listed. [`@moltenship/calendar-recurrence`](https://time.molten.sh/docs/react/recurrence.md) lists them.
- **It doesn't write ICS from typed objects.** `stringifyIcsComponents` writes a syntax tree you
build yourself.
- **It doesn't read bytes.** `parseIcs` takes a string, so decode the bytes as UTF-8 first.
## Next
- [Read an .ics file](https://time.molten.sh/docs/react/ics/import.md): Parse a file a person picks, report its problems, and turn its dates into instants.
- [Show an ICS feed](https://time.molten.sh/docs/react/ics/feed.md): Fetch a feed on the server and show its events in the calendar.
- [API reference](https://time.molten.sh/docs/react/ics/reference.md): Every field of a calendar and an event, time zones, issues, extensions and the lower layers.
# Read an .ics file
Parse an iCalendar file a person picks or uploads, report its problems with their lines, and turn its dates into instants.
Source: https://time.molten.sh/docs/react/ics/import
A person exports a calendar from Google Calendar or Outlook and gives your app the `.ics` file.
This page reads it in the browser, tells the person what the file got wrong, and checks an upload
on a server. Nothing here needs the calendar or a UI framework.
## Read the file
`readIcsFile` takes the `File` from an ` ` or a drop, and the viewer's time
zone. It returns the events with their times as instants, and a line for each problem:
```ts title="read-ics-file.ts"
import { getEventEnd, parseIcs, type IcsDateValue, type IcsIssue } from "@moltenship/ics";
export interface ImportedEvent {
readonly id: string;
readonly title: string;
readonly allDay: boolean;
readonly start: Temporal.Instant;
readonly end: Temporal.Instant;
}
export interface ImportResult {
readonly events: readonly ImportedEvent[];
/** What to tell the person about the file, one line per problem. */
readonly problems: readonly string[];
}
export async function readIcsFile(file: File, viewerTimeZone: string): Promise {
// `File.text()` decodes the bytes as UTF-8, the encoding iCalendar files use.
const { calendars, issues } = parseIcs(await file.text());
const events = calendars.flatMap((calendar) => {
// Times without a zone are read in the file's X-WR-TIMEZONE, else in the viewer's zone.
const timeZone = calendar.timeZone ?? viewerTimeZone;
return calendar.events.map((event) => ({
id: event.uid,
title: event.summary ?? "Untitled",
allDay: event.start.kind === "date",
start: toInstant(event.start, timeZone),
end: toInstant(getEventEnd(event), timeZone),
}));
});
return { events, problems: issues.filter(isError).map(describe) };
}
```
`parseIcs` takes a string, not bytes. `File.text()` decodes the file as UTF-8, which is the
encoding RFC 5545 names as the default. Read a `Response` with `response.text()`, and other bytes
with `new TextDecoder().decode(bytes)`.
A file can hold more than one VCALENDAR, so the function reads every calendar in `calendars`.
## Turn dates into instants
An ICS start is one of five shapes, and `kind` says which. Two of them are instants already. The
other three need a time zone, which you choose:
```ts title="read-ics-file.ts"
function toInstant(value: IcsDateValue, timeZone: string): Temporal.Instant {
switch (value.kind) {
case "utc":
return value.instant;
case "zoned":
return value.zoned.toInstant();
case "date":
// An all-day event starts when its date starts in the chosen zone.
return value.date.toZonedDateTime(timeZone).toInstant();
case "floating":
case "unresolved":
return value.wallTime.toZonedDateTime(timeZone).toInstant();
}
}
```
| `kind` | The file wrote | How the function reads it |
| ------------ | ------------------------------------- | -------------------------------------------- |
| `utc` | A time in UTC, ending in `Z` | The instant itself |
| `zoned` | A time with a `TZID` the parser knows | The instant in that zone |
| `date` | A date, for an all-day event | The start of that date in the zone you chose |
| `floating` | A time with no zone | That wall time in the zone you chose |
| `unresolved` | A time with a `TZID` nobody knows | That wall time in the zone you chose |
The parser never falls back to the host's time zone, so the choice is in your code. This function
uses the calendar's `X-WR-TIMEZONE`, which Google Calendar writes, and the viewer's zone when the
file has none. [Time zones](https://time.molten.sh/docs/react/ics/reference.md#time-zones) lists how a `TZID` is resolved,
Outlook's Windows names included.
`getEventEnd` returns the end in the start's kind: the file's `DTEND`, or the start plus
`DURATION`. An event with neither ends the next day when it's all-day, and when it starts when it's
timed, so give such an event a length of your own before you show it.
An all-day event keeps its date in `event.start.date`. Keep that `Temporal.PlainDate` instead of
an instant if your app shows all-day events on a date, as the calendar does.
## Tell the person what went wrong
The parser is lenient. It keeps every event it can read and lists what it couldn't in `issues`. An
issue with the severity `"error"` dropped a value or a whole component, and one with `"warning"`
kept a value read leniently. Each has the line it came from, when it came from one:
```ts title="read-ics-file.ts"
function isError(issue: IcsIssue): boolean {
return issue.severity === "error";
}
function describe(issue: IcsIssue): string {
return issue.line === undefined ? issue.message : `Line ${issue.line}: ${issue.message}`;
}
```
For a file whose second event has no `DTSTART`, `problems` holds one line, and `events` holds the
other events:
```text
Line 9: VEVENT has no DTSTART; skipped
```
[Issues and strict mode](https://time.molten.sh/docs/react/ics/reference.md#issues-and-strict-mode) lists every code.
## Refuse a file with errors
To import all of a file or none of it, parse with `strict: true`. The parser then throws an
`IcsParseError` when the text has an error. Its `message` is the first error's, with a count of the
others, and its `issues` lists them all. Warnings never throw:
```ts title="read-strictly.ts"
import { IcsParseError } from "@moltenship/ics";
/** The file's calendars, or the reason the file is refused. */
export function readStrictly(text: string) {
try {
return { ok: true as const, calendars: parseIcs(text, { strict: true }).calendars };
} catch (error) {
if (!(error instanceof IcsParseError)) throw error;
return { ok: false as const, reason: error.message, issues: error.issues };
}
}
```
Text without a VCALENDAR is an error too, so this also refuses a file that isn't a calendar.
## Check an upload on a server
A parser is a [Standard Schema](https://standardschema.dev): its `validate` fails with the errors,
or succeeds with the parse result. A value that isn't a string fails as well, so a form without a
file gets the same answer as a bad file. This handler runs wherever `Request` and `Response` do:
```ts title="route.ts"
import { createIcsParser } from "@moltenship/ics";
const parser = createIcsParser();
/** A route handler for a form with an ` `. */
export async function POST(request: Request): Promise {
const file = (await request.formData()).get("calendar");
const body = file instanceof File ? await file.text() : undefined;
// A parser is a Standard Schema: it fails with the errors, or succeeds with the result.
const result = await parser["~standard"].validate(body);
if (result.issues) {
return Response.json({ errors: result.issues.map((issue) => issue.message) }, { status: 400 });
}
const events = result.value.calendars.flatMap((calendar) => calendar.events);
return Response.json({ imported: events.length });
}
```
Anything that takes a Standard Schema takes the parser the same way, such as a form library or a
router's body validation.
## Recurring events
A recurring event arrives as one event with a `recurrenceRule`, and each changed occurrence as
another event with the same `uid` and a `recurrenceId`. So `uid` alone doesn't identify an event
in a file with series. [`@moltenship/calendar-recurrence`](https://time.molten.sh/docs/react/recurrence.md) groups such events
into series with `recurringEventsFromIcs` and lists their occurrences for a range of dates.
# Show an ICS feed
Parse a Google, Outlook or iCloud feed on the server and show its events in the calendar.
Source: https://time.molten.sh/docs/react/ics/feed
> Live example: see it at https://time.molten.sh/docs/react/ics/feed
These events come from an ICS feed, the iCalendar text that Google Calendar, Outlook and iCloud
publish. The feed was written for this week, parsed in your browser with `@moltenship/ics`, and
shown in your time zone. Each title says where its time came from: a New York time zone, an Outlook
zone name, UTC, a date, or a floating time with no zone at all. Open the source to compare.
This guide does the same in a Next.js app: the server fetches and parses the feed, and the browser
shows it. The [Next.js guide](https://time.molten.sh/docs/react/guides/nextjs.md) covers the rules for server rendering that apply
here too.
## Install
The parser is a separate package. It reads iCalendar text into Temporal values and doesn't depend
on the calendar, so it works on its own too.
**pnpm**
```bash
pnpm add @moltenship/ics
```
**npm**
```bash
npm install @moltenship/ics
```
**yarn**
```bash
yarn add @moltenship/ics
```
**bun**
```bash
bun add @moltenship/ics
```
It needs `Temporal`, as the calendar does: Node.js 26 has it, and the browser may need the
[polyfill](https://time.molten.sh/docs/react/installation.md#temporal).
## Fetch and parse on the server
A Server Component fetches the feed, parses it with `parseIcs`, and maps the events to plain JSON
for the client:
```tsx title="page.tsx"
// app/team/page.tsx (a Server Component)
import { parseIcs } from "@moltenship/ics";
import { cacheLife } from "next/cache";
import { connection } from "next/server";
import { Suspense } from "react";
import { FeedCalendar } from "./feed-calendar";
import { toFeedEvents, type FeedEventJson } from "./feed-events";
const feedUrl = "https://calendar.example.com/team/basic.ics";
async function getFeedEvents(timeZone: string): Promise {
"use cache";
cacheLife("hours"); // fetch the feed again at most once an hour
const response = await fetch(feedUrl);
if (!response.ok) throw new Error(`The feed answered ${response.status}`);
const { calendars, issues } = parseIcs(await response.text());
for (const issue of issues) {
console.warn(`${feedUrl}, line ${issue.line ?? "?"}: ${issue.message}`);
}
return calendars.flatMap((calendar) => toFeedEvents(calendar, timeZone));
}
export default function TeamPage() {
return (
Loading the team calendar…}>
);
}
async function TeamFeed() {
await connection(); // render on each request, for a fresh `now`
// The viewer's time zone, for example from their profile or a cookie.
const timeZone = "Europe/Berlin";
const events = await getFeedEvents(timeZone);
return (
);
}
```
- **Caching.** Feeds change slowly, and providers limit how often you fetch them. `"use cache"`
with `cacheLife("hours")` keeps the result for an hour. The time zone is an argument, so each
time zone gets its own entry. Without
[Cache Components](https://nextjs.org/docs/app/getting-started/caching), pass
`{ next: { revalidate: 3600 } }` to `fetch` instead.
- **Issues.** `parseIcs` doesn't throw on bad data. It keeps what it can and lists each problem in
`issues`, with its line. The page logs them; see [Issues](#issues) for more.
- **The current time.** `connection()` renders the calendar on each request, so `now` is today
rather than the day you built the app. That makes it request-time data, so it sits in a
`` boundary: the rest of the page still prerenders, and the build doesn't stop on it.
Temporal values can't cross from a Server Component to a Client Component, so `toFeedEvents` returns
ISO 8601 strings. The client turns them back into Temporal values:
```tsx title="feed-calendar.tsx"
// app/team/feed-calendar.tsx
"use client";
import { createCalendar, defineEventAdapter } from "@moltenship/calendar";
import { useMemo } from "react";
import { CalendarToolbar } from "@/components/calendar/calendar-toolbar";
import type { CalendarEventColor } from "@/components/calendar/event-colors";
import { createWeekView } from "@/components/calendar/time-grid-view/time-grid-view";
import type { FeedEventJson } from "./feed-events";
export type FeedEvent = {
readonly id: string;
readonly title: string;
readonly color: CalendarEventColor;
} & (
| { readonly kind: "timed"; readonly start: Temporal.Instant; readonly end: Temporal.Instant }
| {
readonly kind: "all-day";
readonly start: Temporal.PlainDate;
readonly end: Temporal.PlainDate;
}
);
/** Turns the strings from the server back into Temporal values. */
export function fromFeedJson({ kind, start, end, ...event }: FeedEventJson): FeedEvent {
return kind === "timed"
? { ...event, kind, start: Temporal.Instant.from(start), end: Temporal.Instant.from(end) }
: { ...event, kind, start: Temporal.PlainDate.from(start), end: Temporal.PlainDate.from(end) };
}
const Calendar = createCalendar()({
eventAdapter: defineEventAdapter()({
getId: (event) => event.id,
getTitle: (event) => event.title,
// A FeedEvent is already an interval: its kind, start and end.
getInterval: (event) => event,
getResourceIds: () => [],
}),
views: [createWeekView({ getEventColor: (event) => event.color })],
});
const weekRules = { firstDay: 1, minimalDays: 4, weekend: [6, 7] } as const;
interface FeedCalendarProps {
readonly events: readonly FeedEventJson[];
readonly now: string;
readonly timeZone: string;
}
export function FeedCalendar({ events, now, timeZone }: FeedCalendarProps) {
const feedEvents = useMemo(() => events.map(fromFeedJson), [events]);
const nowInstant = Temporal.Instant.from(now);
return (
);
}
```
## Map ICS events to calendar events
ICS writes times in five ways, and the parser keeps them apart as `start.kind`. `toFeedEvent` turns
each into an event the calendar can show:
```ts title="feed-events.ts"
// app/team/feed-events.ts
import { getEventEnd, type IcsCalendar, type IcsDateValue, type IcsEvent } from "@moltenship/ics";
import type { CalendarEventColor } from "@/components/calendar/event-colors";
/** A feed event as plain JSON, ready to pass from a Server Component to a Client Component. */
export interface FeedEventJson {
readonly id: string;
readonly title: string;
readonly color: CalendarEventColor;
readonly kind: "timed" | "all-day";
/** An instant, such as "2026-10-12T07:00:00Z", or a date for an all-day event. */
readonly start: string;
readonly end: string;
}
// The calendar needs an end after the start; ICS allows events that take no time.
const minimumLength = { minutes: 30 };
/** The zone for floating and unresolved times: the feed's X-WR-TIMEZONE, else the viewer's. */
export function feedTimeZone(calendar: IcsCalendar, viewerTimeZone: string): string {
return calendar.timeZone ?? viewerTimeZone;
}
function toInstant(value: IcsDateValue, timeZone: string): Temporal.Instant {
switch (value.kind) {
case "utc":
return value.instant;
case "zoned":
return value.zoned.toInstant();
case "date":
return value.date.toZonedDateTime(timeZone).toInstant();
case "floating":
case "unresolved":
return value.wallTime.toZonedDateTime(timeZone).toInstant();
}
}
/** One event for the calendar, or `undefined` for a cancelled one. */
export function toFeedEvent(event: IcsEvent, timeZone: string): FeedEventJson | undefined {
if (event.status === "CANCELLED") return undefined;
const end = getEventEnd(event); // DTEND, else DTSTART + DURATION, in the start's kind
let times: Pick;
if (event.start.kind === "date") {
const start = event.start.date;
const endDate = end.kind === "date" ? end.date : start;
const isAfter = Temporal.PlainDate.compare(endDate, start) > 0;
times = {
kind: "all-day",
start: start.toString(),
end: (isAfter ? endDate : start.add({ days: 1 })).toString(),
};
} else {
const start = toInstant(event.start, timeZone);
// A DTEND in UTC or a time zone keeps its instant, even after a floating start.
const absoluteEnd = event.end?.kind === "utc" || event.end?.kind === "zoned";
const endInstant = toInstant(absoluteEnd ? event.end! : end, timeZone);
const isAfter = Temporal.Instant.compare(endInstant, start) > 0;
times = {
kind: "timed",
start: start.toString(),
end: (isAfter ? endInstant : start.add(minimumLength)).toString(),
};
}
return {
// An override (RECURRENCE-ID) shares its series' UID, so its start keeps the ID unique.
id: event.recurrenceId === undefined ? event.uid : `${event.uid}/${times.start}`,
title: event.summary ?? "Busy",
// Free time (TRANSP:TRANSPARENT) and tentative events are gray, the rest blue.
color: event.transparency === "TRANSPARENT" || event.status === "TENTATIVE" ? "gray" : "blue",
...times,
};
}
/** Every event of a parsed calendar, ready for the client. */
export function toFeedEvents(
calendar: IcsCalendar,
viewerTimeZone: string,
): readonly FeedEventJson[] {
const timeZone = feedTimeZone(calendar, viewerTimeZone);
return calendar.events.flatMap((event) => toFeedEvent(event, timeZone) ?? []);
}
```
| `kind` | Written as | Shown as |
| ------------ | ------------------------------ | ----------------------------------------------------- |
| `utc` | `DTSTART:20261012T090000Z` | A timed event at that instant |
| `zoned` | `DTSTART;TZID=Europe/Berlin:…` | A timed event at `zoned.toInstant()` |
| `date` | `DTSTART;VALUE=DATE:20261012` | An all-day event |
| `floating` | `DTSTART:20261012T090000` | A timed event at that wall time, in a zone you choose |
| `unresolved` | `DTSTART;TZID=Our Office:…` | The same as floating |
- **Floating times** have a clock time and no zone. A feed's `X-WR-TIMEZONE`, which Google adds,
says which zone the publisher meant, and the parser gives it to you as `calendar.timeZone`.
`feedTimeZone` uses it, and the viewer's time zone when the feed has none. The preview's feed has
none, so its focus time shows at the same clock time wherever you are.
- **The end.** `getEventEnd` returns DTEND, else DTSTART plus DURATION, else the RFC's default: the
next day for a date, the start itself for a time. It's always the same kind as the start.
- **No length.** ICS lets an event end when it starts, but a calendar event's end must come after
its start, so those events show as half an hour long, or one day for a date.
- **Cancelled events.** Feeds keep a cancelled event, with `STATUS:CANCELLED`, so that subscribers
can remove it. `toFeedEvent` skips it.
- **Colors.** Events marked free (`TRANSP:TRANSPARENT`) or tentative are gray, the rest blue. Change
the rule to suit your app, or color each feed differently.
## Recurring events
`@moltenship/ics` reads recurrence but doesn't expand it. A series is one event with its rule in
`recurrenceRule`, the occurrences it removes in `exceptionDates`, and extra ones in
`recurrenceDates`. A change to one occurrence is a separate event with the series' UID and a
`recurrenceId` that names the occurrence it replaces. So the mapping above shows:
- **A recurring event once,** at its DTSTART, which is the first occurrence.
- **A changed occurrence as its own event,** at its new time.
[`@moltenship/calendar-recurrence`](https://time.molten.sh/docs/react/recurrence/reference.md) expands them. `recurringEventsFromIcs`
groups a calendar's events into series masters, overrides and one-off events, and an expander turns
them into the occurrences for the dates on screen. Those dates are known in the browser, so the
server sends the feed's text, a string, instead of mapped events. In the page above, have the
cached function return `await response.text()`, and pass it as `text`:
```tsx title="recurring-feed-calendar.tsx"
// app/team/recurring-feed-calendar.tsx
"use client";
import { createCalendar, weekRange, type PlainDateInterval } from "@moltenship/calendar";
import {
createCanonicalRecurrenceAdapter,
createOccurrenceAdapter,
createOccurrenceExpander,
recurringEventsFromIcs,
type RecurrenceOccurrence,
type RecurringCalendarEvent,
} from "@moltenship/calendar-recurrence";
import { parseIcs, type IcsEvent } from "@moltenship/ics";
import { useMemo, useState } from "react";
import { CalendarToolbar } from "@/components/calendar/calendar-toolbar";
import { createWeekView } from "@/components/calendar/time-grid-view/time-grid-view";
type FeedEvent = RecurringCalendarEvent;
type FeedOccurrence = RecurrenceOccurrence;
const adapters = createCanonicalRecurrenceAdapter();
const Calendar = createCalendar()({
eventAdapter: createOccurrenceAdapter(adapters.event),
views: [createWeekView()],
});
/** The feed's VEVENTs as series masters, overrides and one-off events. */
export function readRecurringFeed(text: string): readonly FeedEvent[] {
const { calendars } = parseIcs(text);
return calendars.flatMap((calendar) => {
// UTC times on all-day and floating series, such as an UNTIL, read in the feed's zone.
const { events, issues } = recurringEventsFromIcs(calendar.events, {
timeZone: calendar.timeZone,
});
for (const issue of issues) console.warn(`${issue.event.uid}: ${issue.message}`);
return events;
});
}
const weekRules = { firstDay: 1, minimalDays: 4, weekend: [6, 7] } as const;
interface RecurringFeedCalendarProps {
/** The feed's ICS text, which the server fetched. */
readonly text: string;
readonly now: string;
readonly timeZone: string;
}
export function RecurringFeedCalendar({ text, now, timeZone }: RecurringFeedCalendarProps) {
const nowInstant = Temporal.Instant.from(now);
const today = nowInstant.toZonedDateTimeISO(timeZone).toPlainDate();
const events = useMemo(() => readRecurringFeed(text), [text]);
const [expander] = useState(() => createOccurrenceExpander(adapters));
const [range, setRange] = useState(() =>
weekRange(today, { weekStartsOn: weekRules.firstDay }),
);
const { occurrences } = useMemo(
() => expander.expand(events, { range, timeZone }),
[expander, events, range, timeZone],
);
return (
setRange(loadRange)}
now={nowInstant}
defaultAnchorDate={today}
defaultTimeZone={timeZone}
locale="en-US"
weekRules={weekRules}
>
);
}
```
- **IDs.** Masters and one-off events keep their UID. An override gets the ID of the occurrence it
replaces, such as `standup@example.com::2026-10-20T07:00:00Z`, so it never collides with its
series.
- **Time zones.** A zoned series repeats on its zone's wall clock, so a 09:00 meeting stays at 09:00
across daylight saving time. Floating and all-day series stay floating and all-day, and the
calendar shows them that way. Pass the feed's `X-WR-TIMEZONE` as `timeZone`, so UTC dates on them,
such as an UNTIL, keep the feed's dates. Feeds without one, such as Exchange's, write the UNTIL of
an all-day series at the owner's midnight in UTC; without `timeZone`, the bridge reads such dates
in the zone most of the feed's TZIDs name, so the last day isn't lost. Pass `timeZone: "UTC"` to
read them in UTC, as the bridge did before.
- **Daylight saving time.** A DTSTART in the hour a zone skips moves forward by the gap. A series
keeps the length written up to DTEND: a weekly Sydney 02:30–03:30 meeting from the night clocks
go forward shows 03:30–04:30 that night, and 02:30–03:30 on later weeks.
- **Outlook's all-day events.** Older Outlook and Exchange exports write an all-day event from
midnight to midnight in a zone, with `X-MICROSOFT-CDO-ALLDAYEVENT:TRUE`. The bridge reads it as
all-day on the dates written, and its series' midnight dates as dates.
- **This and future.** Apple writes a change to an occurrence and every later one as an override
with `RANGE=THISANDFUTURE`. The bridge splits the series there, as Google Calendar does: the new
part starts at the override, with its title, and the rest of the rule moved the same way. Its
occurrences take the new part's IDs.
- **Cancelled events.** A cancelled override, with `STATUS:CANCELLED`, hides its occurrence. A
cancelled master is left out with its overrides.
- **Issues.** `recurringEventsFromIcs` reports what it changed or left out, such as an RDATE with a
date where the series has times, or a `RANGE=THISANDFUTURE` change the rule can't follow, which
then replaces one occurrence. The expander reports its own issues, such as a rule it can't
expand.
To expand on the server instead, call the expander there for a range you choose, and map each
occurrence's `interval` to JSON as `toFeedEvent` maps an event's times. The calendar then shows only
that range. [Show and edit recurring events](https://time.molten.sh/docs/react/recurrence/calendar.md) covers expansion in
more detail.
## Time zones
A TZID is a name the file chooses, and the parser maps it to a time zone Temporal knows: an IANA
name such as `America/New_York`, a Windows or Outlook name such as `W. Europe Standard Time`, the
file's own VTIMEZONE, and a few more. A TZID that matches none of them isn't guessed. The time
stays `unresolved`, with its wall time and TZID, and `issues` gets an `unknown-time-zone` warning.
The mapping above then reads it in the zone you chose, like a floating time.
If you know what a feed's own names mean, say so with `resolveTimeZone`. The parser asks it first;
`undefined` falls through to the built-in rules:
```ts
const { calendars, issues } = parseIcs(text, {
resolveTimeZone: (tzid) => (tzid === "Our Office" ? "Europe/Lisbon" : undefined),
});
```
The [API reference](https://time.molten.sh/docs/react/ics/reference.md) lists every rule, in order.
## Issues
Each issue has a `severity`, a `code`, a `message` and, when it comes from one, a `line`. An error
drops what it concerns, such as an event without DTSTART. A warning keeps a best-effort value.
Feeds you subscribe to break the rules more often than you'd think, so keep showing what parsed.
Log the issues, as the page does, and if people should know, pass a count of the errors to the
client and show it beside the calendar, such as "2 events couldn't be read".
Files that people upload are different: tell them what's wrong instead. `strict: true` throws an
`IcsParseError` with the errors in `issues`:
```ts
import { IcsParseError, parseIcs } from "@moltenship/ics";
function readUpload(text: string) {
try {
return { calendars: parseIcs(text, { strict: true }).calendars };
} catch (error) {
if (!(error instanceof IcsParseError)) throw error;
return { errors: error.issues.map((issue) => `Line ${issue.line ?? "?"}: ${issue.message}`) };
}
}
```
A parser from `createIcsParser` is also a [Standard Schema](https://standardschema.dev), so a form
or router library that takes one can validate the upload. The [API reference](https://time.molten.sh/docs/react/ics/reference.md) covers
both.
# API reference
Everything @moltenship/ics exports. Calendars and events, dates and time zones, issues and strict mode, extensions, and the lower layers.
Source: https://time.molten.sh/docs/react/ics/reference
Everything on this page is exported from `@moltenship/ics`. The [Overview](https://time.molten.sh/docs/react/ics.md) has the
install command and a first example.
To show a feed's events in the calendar, follow [Show an ICS feed](https://time.molten.sh/docs/react/ics/feed.md).
## Parse
```ts
import { parseIcs } from "@moltenship/ics";
const response = await fetch("https://example.com/team.ics");
const { calendars, issues } = parseIcs(await response.text());
for (const event of calendars[0]?.events ?? []) {
console.log(event.summary, event.start);
}
```
`parseIcs(text, options)` returns two lists:
- `calendars`: every VCALENDAR in the text, usually one. Their components keep the order of the
text.
- `issues`: every deviation from RFC 5545 the parser found, with its line. See
[Issues and strict mode](#issues-and-strict-mode).
Parsing is lenient. The parser keeps what it can read, skips components it can't type, such as an
event without `UID` or `DTSTART`, and reports each problem as an issue. Bad data never throws.
Text without a VCALENDAR, empty text included, gives no calendars and an error.
To parse many texts with the same options, create a parser once:
```ts
import { createIcsParser } from "@moltenship/ics";
const parser = createIcsParser({ strict: true });
const { calendars } = parser.parse(text);
```
`parseIcs(text, options)` is the same as `createIcsParser(options).parse(text)`.
### Calendars
Each calendar is an `IcsCalendar`. Optional fields are absent when the file doesn't set them, and
lists are empty.
| Name | Type | Description |
| ----------------- | ------------------------ | ----------------------------------------------------------------------------------------------- |
| `events` | `readonly IcsEvent[]` | Required. VEVENTs, in the order of the text. |
| `todos` | `readonly IcsTodo[]` | Required. VTODOs. |
| `journals` | `readonly IcsJournal[]` | Required. VJOURNALs. |
| `freeBusy` | `readonly IcsFreeBusy[]` | Required. VFREEBUSYs. |
| `timeZones` | `readonly IcsTimeZone[]` | Required. VTIMEZONEs, each with its `tzid` as written and the `timeZone` it resolved to. |
| `name` | `string` | NAME (RFC 7986), else X-WR-CALNAME. |
| `description` | `string` | DESCRIPTION (RFC 7986), else X-WR-CALDESC. |
| `timeZone` | `string` | X-WR-TIMEZONE, resolved to a time zone id. See [Dates and times](#dates-and-times). |
| `refreshInterval` | `Temporal.Duration` | REFRESH-INTERVAL (RFC 7986), else X-PUBLISHED-TTL. |
| `method` | `string` | METHOD, such as PUBLISH, REQUEST or CANCEL. |
| `productId` | `string` | PRODID: the app that wrote the file. |
| `color` | `string` | COLOR (RFC 7986). |
| `extensions` | `object` | Required. The `X-` properties you declared. See [Extensions](#extensions-with-standard-schema). |
| `otherProperties` | `readonly IcsProperty[]` | Required. Properties no field maps, such as other X- properties. |
It also has `calendarScale`, `lastModified`, `source`, `uid`, `url`, `version` and
`otherComponents`.
### Events
Each event is an `IcsEvent`:
| Name | Type | Description |
| ----------------- | ---------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| `uid` | `string` | Required. UID. An event without one is reported and skipped. |
| `start` | `IcsDateValue` | Required. DTSTART: a date or a date-time. See [Dates and times](#dates-and-times). An event without one is reported and skipped. |
| `end` | `IcsDateValue` | DTEND as written. Use [getEventEnd](#ends-of-events) for the effective end. |
| `duration` | `Temporal.Duration` | DURATION as written. |
| `summary` | `string` | SUMMARY, with escapes such as \, and \n decoded. |
| `description` | `string` | DESCRIPTION. |
| `location` | `string` | LOCATION. |
| `status` | `string` | STATUS: CONFIRMED, TENTATIVE or CANCELLED. |
| `transparency` | `string` | TRANSP: OPAQUE (busy) or TRANSPARENT (free). |
| `organizer` | `IcsCalendarUser` | ORGANIZER. |
| `attendees` | `readonly IcsAttendee[]` | Required. ATTENDEE, every occurrence. |
| `recurrenceRule` | `IcsRecurrenceRule` | RRULE. See [Recurrence](#recurrence). |
| `exceptionDates` | `readonly IcsDateValue[]` | Required. EXDATE. |
| `recurrenceDates` | `readonly (IcsDateValue \| IcsPeriod)[]` | Required. RDATE. |
| `recurrenceId` | `IcsDateValue` | RECURRENCE-ID: the occurrence of a series this event replaces. |
| `alarms` | `readonly IcsAlarm[]` | Required. VALARMs. |
| `categories` | `readonly string[]` | Required. CATEGORIES, every value. |
| `stamp` | `Temporal.Instant` | DTSTAMP. Required by RFC 5545, but often missing from exports. |
| `extensions` | `object` | Required. The `X-` properties you declared. See [Extensions](#extensions-with-standard-schema). |
| `otherProperties` | `readonly IcsProperty[]` | Required. Properties no field maps, such as X-MICROSOFT-CDO-BUSYSTATUS. |
Events also have `attachments`, `classification`, `color`, `comments`, `conferences`, `contacts`,
`created`, `geo`, `lastModified`, `priority`, `recurrenceRange`, `relatedTo`, `resources`,
`sequence`, `url` and `otherComponents`.
The organizer and attendees are calendar users. `address` is the value as written, such as
`mailto:ann@example.com`, `email` comes from the `EMAIL` parameter or the address without
`mailto:`, and `name` comes from the `CN` parameter. Attendees add `participationStatus`, `role`, `rsvp` and the other `ATTENDEE`
parameters.
To-dos (`IcsTodo`) and journals (`IcsJournal`) share most of these fields. Every type is
exported, and each field has a doc comment that your editor shows.
## Dates and times
A `DATE` value is a `Temporal.PlainDate`. A `DATE-TIME` value can mean several things, so it's a
union, and `kind` says what the file wrote:
| `kind` | Written as | Fields |
| ------------ | --------------------------------------- | --------------------------------------------------------------------- |
| `date` | `DTSTART;VALUE=DATE:20261016` | `date: Temporal.PlainDate` |
| `utc` | `DTSTART:20261014T080000Z` | `instant: Temporal.Instant` |
| `zoned` | `DTSTART;TZID=Europe/Berlin:20261014T…` | `zoned: Temporal.ZonedDateTime`, `wallTime`, `tzid` |
| `unresolved` | `DTSTART;TZID=Head office:20261014T…` | `wallTime: Temporal.PlainDateTime`, `tzid` |
| `floating` | `DTSTART:20261014T100000` | `wallTime: Temporal.PlainDateTime`: the same clock time in every zone |
`zoned` is a TZID that resolved to a time zone, and `unresolved` one that didn't. See
[Time zones](#time-zones). Switch on `kind` to get what you need, such as an instant:
```ts
import type { IcsDateValue } from "@moltenship/ics";
function startInstant(start: IcsDateValue, timeZone: string): Temporal.Instant {
switch (start.kind) {
case "utc":
return start.instant;
case "zoned":
return start.zoned.toInstant();
case "date":
return start.date.toZonedDateTime(timeZone).toInstant();
case "floating":
case "unresolved":
return start.wallTime.toZonedDateTime(timeZone).toInstant();
}
}
```
The same union holds `DTEND`, `DUE`, `RECURRENCE-ID`, `EXDATE`, `RDATE` and a rule's `UNTIL`.
A wall time that falls in a daylight saving gap or fold resolves the way RFC 5545 §3.3.5 says,
which is Temporal's `compatible` disambiguation: a time in a gap moves forward by the gap's length,
and a time in a fold takes the earlier of the two. `wallTime` keeps what the file wrote:
```ts
// DTSTART;TZID=Europe/Berlin:20260329T023000, in the hour Berlin skips
const { start } = parseIcs(text).calendars[0]!.events[0]!;
if (start.kind === "zoned") {
start.wallTime.toString(); // "2026-03-29T02:30:00"
start.zoned.toString(); // "2026-03-29T03:30:00+02:00[Europe/Berlin]"
}
```
Nothing falls back to the host's time zone, so the result is the same on every machine. A floating
time stays floating. If the calendar has an `X-WR-TIMEZONE`, as Google's feeds do, its resolved id
is `calendar.timeZone`: the zone the publisher meant for floating times. Apply it yourself if you
want it.
## Time zones
Temporal has no custom time zones, so it can't use the definitions inside a file. Instead, the
parser maps each TZID to a time zone Temporal knows. It tries, in order:
1. your `resolveTimeZone(tzid, vtimezone)` option, if it returns an id Temporal knows;
2. IANA ids, such as `Europe/Berlin`;
3. vendor paths, such as `/mozilla.org/20050126_1/Europe/Berlin`;
4. Windows ids and Outlook display names, such as `W. Europe Standard Time` or
`(UTC+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna`, through the Unicode CLDR
mapping;
5. the file's VTIMEZONE: its `X-LIC-LOCATION`, or a fixed offset when it has no daylight saving
time;
6. offset names, such as `GMT+0100` or `UTC`.
A TZID can name a zone that never changes offset while the file's VTIMEZONE has daylight saving
rules. `TZID=EST` on its own is Temporal's fixed −05:00 zone, but a VTIMEZONE called `EST` with
summer rules usually means New York. When the VTIMEZONE observes daylight saving time, steps 2–4
and 6 skip zones that don't, so the wrong fixed zone is never picked.
A TZID that matches none of these stays `unresolved`, with an `unknown-time-zone` warning. The
parser doesn't guess:
```ts
// DTSTART;TZID=Head office:20261014T100000
const { calendars, issues } = parseIcs(text);
calendars[0]!.events[0]!.start;
// { kind: "unresolved", tzid: "Head office", wallTime: 2026-10-14T10:00:00 }
issues[0]!.code; // "unknown-time-zone"
```
If you know what your feeds mean, say so with `resolveTimeZone`. The parser asks it before its own
rules:
```ts
const { calendars } = parseIcs(text, {
resolveTimeZone: (tzid) => (tzid === "Head office" ? "Europe/Lisbon" : undefined),
});
```
The second argument is the file's VTIMEZONE with that TZID, as a raw component, if there is one.
Return an IANA id or a `±HH:MM` offset, or `undefined` to fall through to the rules above. An id
Temporal doesn't know falls through too.
## Ends of events
An event's end can be written as `DTEND`, as `DURATION`, or not at all. `event.end` and
`event.duration` keep what the file says, and `getEventEnd` works out the end:
```ts
import { getEventEnd } from "@moltenship/ics";
const end = getEventEnd(event); // an IcsDateValue of the same kind as event.start
```
- With `DTEND`, it's `DTEND`, converted to the start's kind if it differs. A `DTEND` in another
zone keeps its instant; one without an instant keeps its wall time.
- With `DURATION`, it's the start plus the duration. On a zoned start, days are calendar days and
hours are exact hours, as RFC 5545 §3.3.6 says, so `P1D` across a daylight saving change keeps
the wall time. On a date start, it adds whole days, and a time part rounds up to a day.
- With neither, an all-day event ends the next day and a timed event ends when it starts.
An event with both `DTEND` and `DURATION` keeps `DTEND`, and the parser drops `DURATION` with a
`conflicting-properties` warning.
## Recurrence
A recurring event is one `IcsEvent` with a rule, such as the design review in the playground:
```ts
// RRULE:FREQ=WEEKLY;BYDAY=WE;COUNT=6
// EXDATE;TZID=Europe/Berlin:20261028T100000
event.recurrenceRule;
// { frequency: "WEEKLY", byDay: [{ weekday: "WE" }], count: 6 }
event.exceptionDates;
// [{ kind: "zoned", zoned: 2026-10-28T10:00:00+01:00[Europe/Berlin], … }]
```
- `recurrenceRule` is the `RRULE` as an `IcsRecurrenceRule`, with named parts: `frequency`,
`interval`, `count`, `until`, `byDay`, `byMonth`, `byMonthDay`, `weekStart` and the rest. Parts
the rule doesn't state are absent, and defaults such as an `interval` of 1 aren't filled in.
- `exceptionDates` lists the `EXDATE` values: occurrences that don't happen.
- `recurrenceDates` lists the `RDATE` values: extra occurrences, as dates, date-times or periods.
- `recurrenceId` is set on an override: a separate event with the series' `UID` that replaces one
occurrence, such as a meeting moved to another time. `recurrenceRange` is `"THISANDFUTURE"` when
the override also applies to the occurrences after it.
This package parses rules but doesn't list a series' occurrences.
[`@moltenship/calendar-recurrence`](https://time.molten.sh/docs/react/recurrence.md) does: `recurringEventsFromIcs` groups
parsed events into series masters, overrides and one-off events, and its expander lists the
occurrences for a range of dates. It applies an override with `RANGE=THISANDFUTURE` to the
occurrences after it too, by splitting the series.
See [Recurring events](https://time.molten.sh/docs/react/ics/feed.md#recurring-events) in the feed guide.
## Issues and strict mode
Each issue says what's wrong and where:
```ts
{
severity: "warning",
code: "invalid-value",
message: "DTSTART: a DATE where DATE-TIME is declared; read as DATE",
line: 62,
path: ["calendars", 0, "events", 3, "start"],
component: "VEVENT",
property: "DTSTART",
}
```
- `severity` is `"error"` or `"warning"`. An error drops the value or component it concerns. A
warning keeps a best-effort value, such as the date above.
- `line` is the 1-based line in the text, when the issue comes from one. A component skipped for a
missing property reports its `BEGIN` line; one skipped for an invalid value reports that
property's line.
- `path` is where the issue lands in the result. Indexes count the components that were kept, so
a skipped event's path ends at `events`. It's empty for problems with the text's structure.
- `component` and `property` name the component and property, when there is one.
`code` says what kind of problem it is:
| Code | Severity | Meaning |
| ------------------------ | ---------------- | -------------------------------------------------------------------------------------------------------- |
| `missing-property` | error | A required property, such as `UID` or `DTSTART`, is missing. The component is skipped. |
| `invalid-value` | error or warning | A value doesn't parse as its type, or parses only leniently. |
| `invalid-content-line` | warning | A line isn't `NAME;PARAM=…:value`, or has an invalid parameter. |
| `invalid-structure` | error or warning | An error when there's no VCALENDAR; a warning for an `END` without its `BEGIN` or a component left open. |
| `duplicate-property` | warning | A property that may occur once occurs again. The first one wins. |
| `conflicting-properties` | warning | Properties that exclude each other, such as `DTEND` and `DURATION`. |
| `unknown-time-zone` | warning | A TZID that resolves to no time zone. The value stays `unresolved`. |
| `unsupported` | warning | Something the parser recognizes but doesn't interpret, such as `RSCALE`. |
| `schema` | error | An extension's schema rejected a value. See [Extensions](#extensions-with-standard-schema). |
Pass `strict: true` to throw instead when there's an error. The parser throws an `IcsParseError`
whose `issues` lists the error-severity issues. Warnings never throw.
```ts
import { IcsParseError, parseIcs } from "@moltenship/ics";
function readFeed(text: string) {
try {
return parseIcs(text, { strict: true }).calendars;
} catch (error) {
if (error instanceof IcsParseError) {
console.error(error.message); // "VEVENT has no DTSTART; skipped (and 2 more)"
console.error(error.issues); // every error-severity issue
}
throw error;
}
}
```
The error's `message` is the first issue's message, with a count of the others.
An exception thrown by a function you pass in, `resolveTimeZone` or an extension schema, comes out
of `parse` unchanged, strict or not. That's a bug in your code, not a problem with the text.
## Extensions with Standard Schema
Calendar apps add their own `X-` properties, such as Outlook's busy status. Undeclared, they land
in `otherProperties` as raw text. Declare the ones you rely on with `icsExtension`, and they're
decoded, validated and typed in `extensions`:
```ts
import { createIcsParser, icsExtension } from "@moltenship/ics";
import { z } from "zod";
const extensions = {
event: {
busyStatus: icsExtension("X-MICROSOFT-CDO-BUSYSTATUS", {
schema: z.enum(["FREE", "TENTATIVE", "BUSY", "OOF", "WORKINGELSEWHERE"]),
}),
resourceIds: icsExtension("X-RESOURCE-ID", { multiple: true }),
guests: icsExtension("X-EXAMPLE-GUESTS", { type: "INTEGER" }),
},
};
const parser = createIcsParser({ extensions });
const { calendars } = parser.parse(text);
const event = calendars[0]!.events[0]!;
event.extensions.busyStatus; // "FREE" | "TENTATIVE" | … | undefined
event.extensions.resourceIds; // readonly string[]
event.extensions.guests; // number | undefined
```
`extensions` has a map for each component kind: `calendar`, `event`, `todo` and `journal`. Each
key is the field name in `extensions`, and `icsExtension(name, options)` takes the property's name
and these options:
| Name | Type | Default | Description |
| ---------- | ------------------ | -------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `type` | `IcsValueType` | `"TEXT"` | The RFC 5545 value type to decode the raw value as, such as INTEGER, DATE-TIME or DURATION, whatever the property's VALUE parameter says. |
| `multiple` | `boolean` | `false` | Collect every occurrence and every comma-separated value into an array, which is empty when there's none. |
| `schema` | `StandardSchemaV1` | | Validates or transforms each decoded value: Zod, Valibot, ArkType or any other Standard Schema. Its input type must accept the decoded value. |
The types are inferred: a schema's output type if it has one, else the value type's decoded type,
such as `number` for `INTEGER` or `IcsDateValue` for `DATE-TIME`. Without `multiple`, a property
that's missing gives `undefined`.
A value the schema rejects is dropped with a `schema` issue. That's an error, so strict parsing
throws and [validation](#as-a-standard-schema) fails. Schemas must validate synchronously: a schema
that returns a promise, such as one with an async refinement, drops the value with a `schema` error
too.
To name the result's types in your own code, keep the `extensions` object in a constant, as above.
Every type takes it the same way: `IcsCalendar`, `IcsEvent`.
## As a Standard Schema
A parser is itself a [Standard Schema](https://standardschema.dev) that validates ICS text, so it
plugs into anything that takes one, such as a form library or a router's body validation. It fails
with the error-severity issues, each with its `message` and `path`, or succeeds with the parse
result. Warnings don't fail it.
```ts
import { createIcsParser } from "@moltenship/ics";
const parser = createIcsParser();
async function readUpload(body: unknown) {
const result = await parser["~standard"].validate(body);
if (result.issues) {
return { status: 400, errors: result.issues.map((issue) => issue.message) };
}
return { status: 200, calendars: result.value.calendars };
}
```
A value that isn't a string fails too.
## Lower layers
`parseIcs` is the top of three layers, and each is exported. When the typed model doesn't cover
your data, drop down a layer.
### Syntax
`parseIcsComponents(text)` splits the text into a lossless tree of components and properties, with
values exactly as written, and reports only syntax issues:
```ts
import { parseIcsComponents, stringifyIcsComponents } from "@moltenship/ics";
const { components, issues } = parseIcsComponents(text);
const event = components[0]!.components[0]!;
const start = event.properties.find((property) => property.name === "DTSTART")!;
start.parameters.TZID; // ["Europe/Berlin"]
start.value; // "20261014T100000", as written
const ics = stringifyIcsComponents(components);
```
A component has its `name`, `properties`, nested `components` and `line`. A property has its
`name`, `parameters` (each a list of values), its raw `value` and its `line`. Names are
upper-cased.
`stringifyIcsComponents(tree)` writes a tree back as text, with CRLF line ends and lines folded at
75 octets. It throws a `RangeError` for a name or value that contains a line break, which iCalendar
can't hold; escape line breaks in TEXT values as `\n` first.
### Values
These turn a raw value into a typed one and back, for any RFC 5545 value type:
```ts
import { decodeIcsDateValue, decodeIcsValue, encodeIcsValue } from "@moltenship/ics";
decodeIcsValue("DURATION", "PT1H30M");
// { ok: true, value: Temporal.Duration PT1H30M }
decodeIcsValue("INTEGER", "ten");
// { ok: false, message: "\"ten\" isn't an INTEGER" }
decodeIcsValue("DATE-TIME", "20261014T100000", { tzid: "Europe/Berlin" });
// { ok: true, value: { kind: "zoned", … } }
decodeIcsDateValue("20261019", "DATE-TIME");
// { ok: true, value: { kind: "date", … }, warnings: [{ code: "invalid-value" }] }
encodeIcsValue("TEXT", "Room 4.01, Berlin office"); // "Room 4.01\, Berlin office"
```
- `decodeIcsValue(type, raw, context)` decodes one value. It never throws: it returns
`{ ok: false, message }`, or `{ ok: true, value }` with `warnings` when it read the value
leniently. Each warning has the `code` that `parseIcs` would report it under.
- `context` gives a DATE-TIME its `tzid`, and a `resolveTimeZone(tzid)` function for TZIDs that
aren't IANA ids. Without one, only ids Temporal knows resolve; Windows names stay `unresolved`.
- `decodeIcsDateValue(raw, declared, context)` reads a DATE or DATE-TIME by its shape, as the
typed model does for `DTSTART`, `DTEND` and `EXDATE`, so a date written without `VALUE=DATE`
still reads as a date.
- `splitIcsValues(type, raw)` splits a list value, such as `CATEGORIES` or `EXDATE`, on its
separating commas, leaving escaped commas alone. `decodeIcsValues(type, raw, context)` splits and
decodes each item, so one bad item doesn't lose the others.
- `icsValueTypeOf(property)` says which type a property's value is: its `VALUE` parameter, else
the property's default type in RFC 5545, else TEXT.
- `encodeIcsValue(type, value)` writes a value as raw text. It throws a `RangeError` for values
iCalendar can't write, such as a duration in months. A zoned date-time is written as its wall
time; adding the `TZID` parameter is up to you.
### What the typed model doesn't map
Typed components keep what they don't understand. `otherProperties` holds every property no field
or extension claims, in the order of the text, and `otherComponents` holds unknown subcomponents.
On attendees and the organizer, `otherParameters` holds parameters such as Google's
`X-NUM-GUESTS`. All three are in the raw syntax layer's shapes, so the value functions above decode
them.
## Not included yet
- **Writing ICS from typed objects.** `stringifyIcsComponents` writes a syntax tree, which you
build yourself.
- **Recurrence expansion.** Rules are parsed into `IcsRecurrenceRule`, not expanded into
occurrences. [`@moltenship/calendar-recurrence`](https://time.molten.sh/docs/react/recurrence/reference.md) expands them, so this
package stays free of dependencies.
- **Byte input.** `parseIcs` takes a string. Decode bytes as UTF-8 first, for example with
`response.text()` or `new TextDecoder().decode(bytes)`. A line fold that splits a multi-byte
character can't be repaired after decoding.
# Overview
What @moltenship/calendar-temporal is, how to install it, and a first example of its date ranges.
Source: https://time.molten.sh/docs/react/temporal
`@moltenship/calendar-temporal` is the date math under the calendar: ranges, week and month grids,
rounding and snapping, the real length of a day in a time zone, and what happens to a time when
the clocks change. Dates and times go in and out as native `Temporal` values.
Apart from `createSystemClock`, nothing in it reads the clock, and nothing reads the host's time
zone. Every function takes the date, the time zone and the first day of the week as arguments, so
the same call gives the same answer on a server, in a browser and in a test.
## Use it without the calendar
The package has no dependencies and imports no UI framework. Install it alone for a date picker of
your own, a booking form, a report grouped by week, or any code that needs a correct month grid or
a day that is 23 hours long.
`@moltenship/calendar` re-exports all of it. An app that has the calendar imports these functions
from there, and needs nothing more installed:
```ts
import { plainDateInterval, zonedDayRange } from "@moltenship/calendar";
```
## Install
**pnpm**
```bash
pnpm add @moltenship/calendar-temporal
```
**npm**
```bash
npm install @moltenship/calendar-temporal
```
**yarn**
```bash
yarn add @moltenship/calendar-temporal
```
**bun**
```bash
bun add @moltenship/calendar-temporal
```
The package is versioned with the calendar.
It needs a runtime with `Temporal`, or a polyfill loaded first, and TypeScript's `ESNext` library.
[Installation](https://time.molten.sh/docs/react/installation.md#temporal) shows both.
## A first example
A range has a `start` and an `end`. It includes the start and excludes the end, which is how
nights, bookings and visible dates are counted:
```ts title="stay.ts"
import {
intersectPlainDateIntervals,
plainDateInterval,
weekRange,
} from "@moltenship/calendar-temporal";
const date = (value: string) => Temporal.PlainDate.from(value);
// A stay that arrives on October 9 and leaves on the 14th. A range includes its start and
// excludes its end, so the 14th isn't one of its nights.
export const stay = plainDateInterval(date("2026-10-09"), date("2026-10-14"));
// The week of October 8 that starts on a Monday: October 5 up to the 12th.
export const week = weekRange(date("2026-10-08"), { weekStartsOn: 1 });
// The part of the stay inside that week, or null when they don't overlap.
export const nights = intersectPlainDateIntervals(stay, week);
```
`nights` runs from October 9 up to October 12: the three nights of the stay that fall in that
week. `plainDateInterval` throws an `InvalidHalfOpenIntervalError` when the start isn't before the
end, so a range that exists is valid.
## What's in it
| You need | Use |
| ----------------------------------------------------------- | --------------------------------------------------------------- |
| A range of dates, instants or wall-clock times | `plainDateInterval`, `instantInterval`, `plainDateTimeInterval` |
| Whether two ranges overlap, and where | `plainDateIntervalsIntersect`, `intersectPlainDateIntervals` |
| The week or the month grid around a date | `weekRange`, `monthGrid`, `iteratePlainDates` |
| A time rounded to a grid of minutes | `snapPlainTime`, `snapZonedDateTime`, `snapZonedWallTime` |
| When a date starts and ends in a time zone | `zonedDayRange`, `splitInstantRangeByZonedDay` |
| The instant of a wall-clock time, with gaps and folds named | `resolveZonedWallTime` |
| The rows of a day view | `slotsInZonedDay` |
| A clock you can fix in a test | `createFixedClock`, `createSystemClock` |
## Next
- [Build a month grid](https://time.molten.sh/docs/react/temporal/month-grid.md): The weeks of a month, the weekday names above them, and the days of the months around it.
- [Handle daylight saving time](https://time.molten.sh/docs/react/temporal/daylight-saving-time.md): Days of 23 and 25 hours, times the clocks skip or repeat, and the rows of a day view.
- [API reference](https://time.molten.sh/docs/react/temporal/reference.md): Every function, by what it works on.
# Build a month grid
Lay out the weeks of a month with monthGrid, weekRange and iteratePlainDates, for a date picker or a view of your own.
Source: https://time.molten.sh/docs/react/temporal/month-grid
A month grid needs three answers: which date the first row starts on, how many rows there are,
and which days belong to the months before and after. `monthGrid` gives all three for any date and
any first day of the week. This page builds the grid as data. It imports no UI framework, so the
same rows feed a date picker, a view or a printed report.
## The rows
`monthGrid(date, { weekStartsOn })` returns the month's first day as `month`, the whole visible
range as `range`, and one seven-day range per row as `weeks`. `iteratePlainDates` steps through a
range one date at a time and leaves the range's end out:
```ts title="month-grid.ts"
import {
iteratePlainDates,
monthGrid,
weekRange,
type WeekStartsOn,
} from "@moltenship/calendar-temporal";
export interface GridDay {
readonly date: Temporal.PlainDate;
/** False for the days of the months before and after, which fill the first and last rows. */
readonly inMonth: boolean;
}
/** The rows of a month grid: one array of seven days for each week. */
export function monthRows(date: Temporal.PlainDate, weekStartsOn: WeekStartsOn): GridDay[][] {
const grid = monthGrid(date, { weekStartsOn });
return grid.weeks.map((week) =>
Array.from(iteratePlainDates(week), (day) => ({
date: day,
inMonth: day.year === grid.month.year && day.month === grid.month.month,
})),
);
}
```
`weekStartsOn` is an ISO day number: 1 is Monday and 7 is Sunday. The function takes it as an
argument and reads no locale, so pass the first day your app uses.
A grid has four to six rows. February 2027 starts on a Monday and has 28 days, so with weeks that
start on Monday it has four. August 2026 has six.
## The weekday names
The names above the columns come from any week that starts on the same day. `weekRange` returns
the seven-day range around a date:
```ts title="month-grid.ts"
/** The names above the columns, starting on the grid's first weekday. */
export function weekdayNames(weekStartsOn: WeekStartsOn, locale: string): string[] {
// Any week has the seven weekdays in the grid's order.
const week = weekRange(Temporal.PlainDate.from("2026-01-01"), { weekStartsOn });
return Array.from(iteratePlainDates(week), (day) =>
day.toLocaleString(locale, { weekday: "short" }),
);
}
```
## Draw it
A component maps over the rows. This function writes them as text, which shows the layout without
a framework:
```ts title="month-grid.ts"
/** The grid as text, with the days of other months left blank. */
export function monthText(date: Temporal.PlainDate, weekStartsOn: WeekStartsOn): string {
const cell = (text: string) => text.slice(0, 2).padStart(2);
const rows = monthRows(date, weekStartsOn).map((row) =>
row.map((day) => cell(day.inMonth ? `${day.date.day}` : "")).join(" "),
);
return [weekdayNames(weekStartsOn, "en-US").map(cell).join(" "), ...rows].join("\n");
}
```
`monthText(Temporal.PlainDate.from("2026-10-08"), 1)` returns:
```text
Mo Tu We Th Fr Sa Su
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
```
The first row starts on September 28. Those three days are in the grid with `inMonth` false, so a
component can draw them dimmed, and this function leaves them blank.
## Six rows every month
A grid that changes height as the reader moves through the year makes the page jump. Pass
`fixedWeeks: true` for six rows in every month:
```ts title="month-grid.ts"
/** Six rows for every month, so a grid keeps its height as the reader moves through the year. */
export function sixWeeks(date: Temporal.PlainDate, weekStartsOn: WeekStartsOn) {
return monthGrid(date, { weekStartsOn, fixedWeeks: true });
}
```
For February 2027 the fixed grid runs to March 15, two rows into March.
## Find the events in the grid
`grid.range` is the range of dates to load events for. It includes the days of the months around
the month, since the grid shows them. For events stored as instants, turn the range's dates into
instants in the viewer's time zone with `zonedDayRange`, as
[Handle daylight saving time](https://time.molten.sh/docs/react/temporal/daylight-saving-time.md#which-events-are-on-a-date) shows.
The calendar's own month view does this for you. Its strategy calls `projectMonth`, which lays out
events on these rows with their lanes and overflow: see [Month view](https://time.molten.sh/docs/react/views/month.md) and
[Custom views](https://time.molten.sh/docs/react/views/custom-views.md).
# Handle daylight saving time
Days of 23 and 25 hours, wall-clock times the clocks skip or repeat, and the rows of a day view, with @moltenship/calendar-temporal.
Source: https://time.molten.sh/docs/react/temporal/daylight-saving-time
Twice a year, in a zone with daylight saving time, a date isn't 24 hours long. In Berlin the
clocks go from 02:00 to 03:00 on March 29, 2026, so that date lasts 23 hours and 02:15 never
happens. On October 25 they go from 03:00 back to 02:00, so the date lasts 25 hours and 02:15
happens twice. Code that adds 24 hours to midnight, or that turns "02:15" into an instant without
looking, is wrong on those two dates.
The functions on this page take the time zone as an argument and never read the host's.
## How long a date is
`zonedDayRange(date, timeZone)` returns the real start and end of a date in a zone, and its length:
```ts title="daylight-saving-time.ts"
import {
resolveZonedWallTime,
slotsInZonedDay,
snapZonedWallTime,
zonedDayRange,
} from "@moltenship/calendar-temporal";
/** How many hours a date lasts in a time zone: 23, 24 or 25 in most of them. */
export function hoursInDay(date: Temporal.PlainDate, timeZone: string): number {
return zonedDayRange(date, timeZone).duration.total("hours");
}
```
In `Europe/Berlin`, `hoursInDay` returns 23 for March 29, 2026, 25 for October 25 and 24 for
October 8.
## Which events are on a date
`interval` on the result is the range of instants to compare events with. Compare with it, and not
with midnight plus 24 hours:
```ts title="daylight-saving-time.ts"
/** Whether an event's instants overlap a date in a time zone. */
export function isOnDate(
event: { readonly start: Temporal.Instant; readonly end: Temporal.Instant },
date: Temporal.PlainDate,
timeZone: string,
): boolean {
const day = zonedDayRange(date, timeZone);
// A few zones have skipped a whole date. Such a date has no instants to compare with.
if (day.kind === "skipped") return false;
return (
Temporal.Instant.compare(event.start, day.interval.end) < 0 &&
Temporal.Instant.compare(event.end, day.interval.start) > 0
);
}
```
An event from 22:30 to 23:00 UTC on October 8 is on October 9 in Berlin, where it starts at 00:30,
and on October 8 in New York.
`kind` is `"skipped"` in the rare case where a zone skips a whole date, as Samoa did on December
30, 2011. Such a date has no instants, and `interval` is `null`.
For an event that crosses midnight, `splitInstantRangeByZonedDay(range, timeZone)` cuts its range
into one piece per date, and each piece says whether the event continues before or after that
date.
## The rows of a day view
A day view shows the wall clock: 24 rows labelled 00:00 to 23:00, on every date. `slotsInZonedDay`
returns those rows with the instants behind each:
```ts title="daylight-saving-time.ts"
export interface HourRow {
/** The time on the wall clock, such as "02:00". */
readonly label: string;
/** "gap" for an hour the clocks skip, "fold" for one they repeat, else "unique". */
readonly kind: string;
/** When the row starts: no instant in a gap, two in a fold. */
readonly starts: readonly Temporal.Instant[];
}
/** The hour rows of a day view. Every day has the same 24 labels, whatever its length. */
export function hourRows(date: Temporal.PlainDate, timeZone: string): HourRow[] {
const { slots } = slotsInZonedDay(date, {
timeZone,
disambiguation: "compatible",
slotDuration: { hours: 1 },
});
return slots.map((slot) => ({
label: slot.wallRange.start.toPlainTime().toString({ smallestUnit: "minute" }),
kind: slot.kind,
starts: slot.segments.flatMap((segment) =>
segment.occurrences.map((occurrence) => occurrence.interval.start),
),
}));
}
```
On March 29 in Berlin the 02:00 row is a gap and has no instant. On October 25 it is a fold and
has two:
```text
March 29, 2026 October 25, 2026
01:00 unique 2026-03-29T00:00:00Z 01:00 unique 2026-10-24T23:00:00Z
02:00 gap 02:00 fold 2026-10-25T00:00:00Z 2026-10-25T01:00:00Z
03:00 unique 2026-03-29T01:00:00Z 03:00 unique 2026-10-25T02:00:00Z
```
A slot that a clock change cuts through is split at the change: its `kind` is `"transition"` and it
has one segment for each part. The function throws a `RangeError` when a day would have more than
10,000 slots, and `limit` raises that.
## A time a person typed
A form gives a date and a time with no zone. `resolveZonedWallTime` turns them into an instant and
says what it found: `kind` is `"unique"`, `"gap"` or `"fold"`.
```ts title="daylight-saving-time.ts"
export type PickedTime =
| { readonly ok: true; readonly instant: Temporal.Instant }
| { readonly ok: false; readonly reason: string };
/** The instant of a date and time a person typed into a form. */
export function pickTime(wallTime: Temporal.PlainDateTime, timeZone: string): PickedTime {
const result = resolveZonedWallTime(wallTime, { timeZone, disambiguation: "compatible" });
if (result.status === "rejected") return { ok: false, reason: "That time can't be used." };
if (result.kind === "gap") {
// The clocks skipped this time. `adjustment` has the time "compatible" moved it to.
const moved = result.adjustment?.resolvedWallTime.toPlainTime().toString({
smallestUnit: "minute",
});
return { ok: false, reason: `The clocks skip that time. Did you mean ${moved}?` };
}
// In a fold the time happens twice, and `selected` is the first of `occurrences`.
return { ok: true, instant: result.selected.instant };
}
```
With Berlin as the zone:
| The person typed | `pickTime` returns |
| ----------------- | --------------------------------------------------- |
| October 8, 02:15 | The instant `2026-10-08T00:15:00Z` |
| March 29, 02:15 | "The clocks skip that time. Did you mean 03:15?" |
| October 25, 02:15 | The instant `2026-10-25T00:15:00Z`, the first 02:15 |
`disambiguation` takes Temporal's four values. `"compatible"` moves a skipped time later by the
length of the gap and picks the earlier of two repeated times. `"reject"` gives a result whose
`status` is `"rejected"` for both. In a fold, `occurrences` holds both instants, so a form can ask
which one the person meant.
## A pointer on a time grid
A drag gives a wall-clock time that needs rounding to the grid. `snapZonedWallTime` rounds it and
resolves it in one step:
```ts title="daylight-saving-time.ts"
/** A pointer's position on a day view, rounded to the 15-minute grid. */
export function snapToGrid(wallTime: Temporal.PlainDateTime, timeZone: string) {
return snapZonedWallTime(wallTime, { timeZone, increment: 15, smallestUnit: "minute" });
}
```
09:07 on October 8 snaps to 09:00. 02:10 on March 29 has no 02:00 or 02:15 to snap to, so it lands
on 03:00, the moment the clocks change. `mode` is `"nearest"` by default, or `"floor"` or `"ceil"`,
and `fold` picks the earlier or the later of two repeated times.
The calendar's week and day views are built on these functions, so they draw a 23-hour day and a
repeated hour without code of yours. [Time and time zones](https://time.molten.sh/docs/react/concepts/time.md) describes what a
reader sees.
# API reference
Everything @moltenship/calendar-temporal exports. Ranges, date and time grids, rounding, day boundaries, daylight saving time, keys and clocks.
Source: https://time.molten.sh/docs/react/temporal/reference
Everything on this page is exported from `@moltenship/calendar-temporal`. The
[Overview](https://time.molten.sh/docs/react/temporal.md) has the install command and a first example.
`@moltenship/calendar` re-exports all of it, so a React app imports from either.
Dates and times go in and out as native Temporal values. Apart from `createSystemClock`, nothing
reads the clock, and nothing reads the host time zone.
## Ranges
A range has a `start` and an `end`. The start is included and the end is excluded, and the start
must come before the end.
```ts
import { plainDateInterval, plainDateIntervalContains } from "@moltenship/calendar-temporal";
const october = plainDateInterval(
Temporal.PlainDate.from("2026-10-01"),
Temporal.PlainDate.from("2026-11-01"),
);
plainDateIntervalContains(october, Temporal.PlainDate.from("2026-10-31")); // true
plainDateIntervalContains(october, Temporal.PlainDate.from("2026-11-01")); // false
```
`instantInterval`, `plainDateInterval`, and `plainDateTimeInterval` create frozen ranges and throw
`InvalidHalfOpenIntervalError` when the start isn't before the end. To get a result object instead
of an error, use `validateHalfOpenInterval`.
There's one function per operation and type:
| Operation | `Temporal.Instant` | `Temporal.PlainDate` | `Temporal.PlainDateTime` |
| ---------------- | --------------------------------- | ----------------------------------- | --------------------------------------- |
| Contains a point | `instantIntervalContains` | `plainDateIntervalContains` | `plainDateTimeIntervalContains` |
| Contains a range | `instantIntervalContainsInterval` | `plainDateIntervalContainsInterval` | `plainDateTimeIntervalContainsInterval` |
| Overlaps | `instantIntervalsIntersect` | `plainDateIntervalsIntersect` | `plainDateTimeIntervalsIntersect` |
| Overlapping part | `intersectInstantIntervals` | `intersectPlainDateIntervals` | `intersectPlainDateTimeIntervals` |
| Split at a point | `splitInstantInterval` | `splitPlainDateInterval` | `splitPlainDateTimeInterval` |
Ranges that only touch don't overlap. The overlapping part is `null` when there's no overlap.
Splitting returns two ranges when the point is strictly inside, and the original range otherwise.
`compareInstants`, `comparePlainDates`, `comparePlainDateTimes`, and `comparePlainTimes` are the
matching sort functions.
## Days, weeks, and months
```ts
import { iteratePlainDates, monthGrid, weekRange } from "@moltenship/calendar-temporal";
const date = Temporal.PlainDate.from("2026-10-08");
weekRange(date, { weekStartsOn: 1 }); // 2026-10-05 to 2026-10-12, Monday start
const grid = monthGrid(date, { weekStartsOn: 1 });
grid.weeks.length; // 5 weeks shown for October 2026
for (const day of iteratePlainDates(grid.range)) {
// every date in the visible grid, end excluded
}
```
- `weekRange(date, { weekStartsOn })` returns the seven-day range containing `date`. `weekStartsOn`
is 1 (Monday) to 7 (Sunday).
- `monthGrid(date, options)` returns the month's first day (`month`), the full visible `range`, and
one range per week (`weeks`). It has four to six weeks; pass `fixedWeeks: true` for always six.
- `iteratePlainDates(range, { stepDays })` and `iterateInstants(range, { step })` step through a
range lazily. They throw a `RangeError` rather than yield more than 10,000 values; raise `limit` for
longer ranges.
## Rounding and snapping
```ts
import { snapPlainTime, snapZonedDateTime } from "@moltenship/calendar-temporal";
snapPlainTime(Temporal.PlainTime.from("23:50"), {
increment: 30,
mode: "ceil",
smallestUnit: "minute",
}); // { time: 00:00, days: 1 }
snapZonedDateTime(Temporal.ZonedDateTime.from("2026-03-29T01:50+01:00[Europe/Berlin]"), {
increment: 15,
mode: "ceil",
smallestUnit: "minute",
}); // 2026-03-29T03:00:00+02:00[Europe/Berlin]: 02:00 doesn't exist that night
```
The snap functions round to a wall-clock grid that starts at midnight, with `mode` set to
`"nearest"` (the default), `"floor"`, or `"ceil"`:
- `snapPlainTime(time, options)` returns `{ time, days }`. `days` is `1` when rounding up passed
midnight, so a late end time isn't mistaken for an early one.
- `snapZonedDateTime(value, options)` rounds in the value's own time zone. In a repeated hour it
keeps the same occurrence. If the result lands in a skipped hour, it moves to the moment the clocks
change, so `floor` never moves later and `ceil` never moves earlier.
- `snapZonedWallTime(wallTime, { timeZone, fold, ...options })` does the same for a wall-clock time
with no zone yet, such as a pointer position. `fold` picks `"earlier"` (the default) or `"later"`
for a repeated time.
`roundPlainTime` and `roundInstant` take Temporal's full set of rounding modes. Instant rounding
starts at the Unix epoch.
## Days in a time zone
```ts
import { zonedDayRange } from "@moltenship/calendar-temporal";
const day = zonedDayRange(Temporal.PlainDate.from("2026-03-29"), "Europe/Berlin");
day.kind; // "available"
day.duration.toString(); // "PT23H": the clocks go forward that night
```
- `zonedDayRange(date, timeZone)` returns the real start and end of a date in a zone. Its
`interval` is the instant range to query with. In the rare case where a time zone skips a whole
date, `kind` is `"skipped"` and `interval` is `null`.
- `splitInstantRangeByZonedDay(range, timeZone)` cuts an instant range into one piece per day, for
events that cross midnight. Each piece says whether the event continues before or after that day.
- `zonedDayTransitions(date, timeZone)` lists the offset changes on a date, with whether each is a
gap or a fold and which wall-clock times it affects.
## Wall-clock times
```ts
import { resolveZonedWallTime } from "@moltenship/calendar-temporal";
const result = resolveZonedWallTime(Temporal.PlainDateTime.from("2026-03-29T02:15"), {
timeZone: "Europe/Berlin",
disambiguation: "compatible",
});
result.status; // "resolved"
result.kind; // "gap": 02:15 doesn't exist that day
result.adjustment?.resolvedWallTime.toString(); // "2026-03-29T03:15:00"
```
`resolveZonedWallTime(wallTime, { timeZone, disambiguation })` turns a wall-clock time into an
instant and tells you what happened: `kind` is `"unique"`, `"gap"`, or `"fold"`. For a gap,
`adjustment` says how far the time moved; with `disambiguation: "reject"`, `status` is `"rejected"`
instead. For a fold, `occurrences` has both instants. `projectInstantToZonedTime(instant, timeZone)`
goes the other way.
## Time slots
`slotsInZonedDay(date, { timeZone, disambiguation, slotDuration })` splits a day into wall-clock
slots, such as 30-minute rows for a day view. Slots in a skipped hour have no instant. Slots in a
repeated hour have two. A slot that a DST change cuts through is split at the change. It throws a
`RangeError` when the day would have more than 10,000 slots; raise `limit` for finer grids.
## Keys
`instantKey`, `plainDateKey`, `plainDateTimeKey`, `zonedDayKey`, and `zonedWallTimeKey` return
strings for use as list keys or cache keys. Two moments in a repeated hour share a wall-clock key,
so key those by `instantKey`. Time zone names are compared case-insensitively, but aliases such as
`Asia/Calcutta` and `Asia/Kolkata` produce different keys.
## Clocks
`createFixedClock(instant)` and `createSystemClock()` return objects for `Root`'s `clock` prop. A fixed
clock always returns the same instant, which helps in tests.
# Customization
How much of the calendar's UI is yours to change, from its tokens to every element on screen, built on the unstyled parts and hooks.
Source: https://time.molten.sh/docs/react/customization
Time is a headless core and one ready-made UI on top of it.
- **The core is the npm packages.** They hold the engine, the calendar's state and actions, and
parts and hooks that render plain elements. They ship no CSS.
- **The UI is the registry.** It's a set of React source files built on those packages: the views,
the toolbar, a kit of controls and a theme, in Tailwind CSS on shadcn/ui's tokens or in
[StyleX](https://time.molten.sh/docs/react/stylex.md). `shadcn add` copies them into your app, and from then on
they are your code.
Nothing in the packages depends on the registry. So every part of that UI is yours to change or
replace, and an app on MUI, Mantine or its own design system uses the same packages without it.
There are four levels, from the least work to the most:
| Level | You change | Where | What it costs |
| -------------------- | -------------------------------------------- | ------------------------- | ------------------------------------------------------------------- |
| 1. Set tokens | Colors, the event palette, sizes | Your global CSS | Nothing |
| 2. Edit the files | Markup, classes, layout, a view's behaviour | `components/calendar/` | A merge when a file you edited gets an update |
| 3. Swap the controls | The buttons, tooltips, popovers and the rest | `components/calendar/ui/` | That merge, and an agent sees less of your controls |
| 4. Build your own UI | Everything on screen | Your own components | You write the views, with their keyboard support and their dragging |
[What each level costs](#what-each-level-costs) has the details.
The levels mix. One calendar can show the registry's month view, a toolbar you edited and a view
you wrote.
## Level 1: set tokens
The registry's views read their colors and sizes from CSS variables. Override them in your own
CSS:
```css title="globals.css"
:root {
--calendar-today: oklch(0.55 0.17 150);
--calendar-hour-height: 4rem;
}
.dark {
--calendar-today: oklch(0.72 0.15 150);
}
```
Most calendar tokens derive from the shadcn tokens, so an app with its own shadcn theme gets a
calendar in its colors before it writes a rule. [Theming](https://time.molten.sh/docs/react/theming.md) lists every token, and the
[Theme builder](https://time.molten.sh/docs/react/theme-builder.md) shows your changes live and gives you the CSS to paste. The
StyleX items have the same tokens as StyleX variables, which
[Change the tokens](https://time.molten.sh/docs/react/stylex.md#change-the-tokens) covers.
You keep everything, updates included. `shadcn add` writes the theme's own block again each time,
and your rules sit outside that block. Tokens change colors, the event palette, the hour height
and the event padding. They don't change markup or layout.
## Level 2: edit the files you added
`shadcn add` puts source files in `components/calendar/`: a folder for each view, the toolbar,
the view switcher and the event chip beside them, and the controls in `ui/`. Open a file and
change it. The toolbar's tooltips open after 400 ms, for example. To open them sooner, change the
default in the tooltip's file:
```ts title="components/calendar/ui/tooltip.styles.ts"
export const tooltipDefaults = { delay: 150, sideOffset: 4 } as const;
```
The same goes for a view's markup, the toolbar's layout in `calendar-toolbar.tsx`, and a control's
classes in its `*.styles.ts` file.
### Updates
The files are copies, so a fix in the registry reaches your app when you add the item again:
```bash
npx shadcn@latest add https://time.molten.sh/r/month-view.json
```
The command goes through the item's files and the files of the items it builds on. It writes a
file your app doesn't have, skips a file that matches the registry's, and asks before it replaces
a file that differs. Answer no to keep yours. `--overwrite` replaces every file without asking,
with any edits you made.
To see what the command would do before it writes anything, add `--dry-run`. It lists each file
as `create`, `skip (identical)` or `overwrite`, which marks a file that differs. `--diff` with a
path from that list prints the difference between your file and the registry's, and writes
nothing either:
```bash
npx shadcn@latest add https://time.molten.sh/r/month-view.json --dry-run
npx shadcn@latest add https://time.molten.sh/r/month-view.json \
--diff components/calendar/month-view/month-view.tsx
```
The diff compares the two files as they are now, so it shows your edits and the registry's changes
together. To separate them, commit your work, let `shadcn add` replace the file, and put your edits
back from `git diff`.
You keep the registry's UI and everything it does. You take on that merge for each file you
edited. Files you didn't touch update without a question.
## Level 3: swap the controls
The Tailwind views take their controls from `button.tsx`, `badge.tsx`, `tooltip.tsx`,
`select.tsx`, `popover.tsx`, `dialog.tsx` and `toast.tsx` in `components/calendar/ui/`: the
buttons, badges, tooltips, view select, popovers, the recurrence dialog and the undo toast. Since
2.0 those controls are built on [ui-sdk](https://ui-sdk.dev), and they are a default. The views import them from
those files only and use them through a short list of props. To use a control of your own,
replace the body of its file and keep the names it exports. With shadcn's button:
```tsx title="components/calendar/ui/button.tsx"
import type { ComponentProps } from "react";
import { Button as AppButton, buttonVariants } from "@/components/ui/button";
export type ButtonProps = ComponentProps;
export function Button(props: ButtonProps) {
return ;
}
export { buttonVariants };
```
Every view now renders your button, and no view's file changes.
[Use your own controls](https://time.molten.sh/docs/react/theming.md#use-your-own-controls) lists what the views import from each
file and the props they pass, and how to give a shadcn popover the handle that one popover for
many triggers needs.
This is an edit like any other, so `shadcn add` asks before it replaces the file. Swapping also
has [two costs of its own](#what-each-level-costs).
## Level 4: build your own UI
Your app adds nothing from the registry at this level. It installs the packages, writes its own
markup or uses any library's components, and connects them to the calendar through parts and
hooks:
- **Parts.** `Frame`, `Toolbar`, `Title`, `Viewport` and the previous, next and today triggers
each render one plain element with a `data-calendar-part` attribute. They take `className`,
`style`, `ref` and event handlers, and bring no class or style of their own.
[Components](https://time.molten.sh/docs/react/api/components.md#components) lists them.
- **Hooks.** `useCalendarActions()` returns `navigateNext`, `setView`, `proposeEventChange` and
the other [actions](https://time.molten.sh/docs/react/api/components.md#actions), for controls of your own.
`useCalendarSelector` and the other [hooks](https://time.molten.sh/docs/react/api/components.md#hooks) read the state.
- **Views.** A [custom view](https://time.molten.sh/docs/react/views/custom-views.md) is a strategy, which picks the dates and
the events, and a `Renderer`, which is your component.
This calendar uses plain elements and class names from the app's own CSS:
```tsx title="meeting-calendar.tsx"
// The strategy picks the dates and the meetings. The Renderer is your markup.
const weekView = defineCalendarView({
name: "week",
strategy: {
getRange: (anchor) => plainDateInterval(anchor, anchor.add({ days: 7 })),
navigate: (anchor, delta) => anchor.add({ weeks: delta }),
getTitle: (range, { locale }) => range.start.toLocaleString(locale, { dateStyle: "medium" }),
project: ({ snapshot, instantRange }: CalendarViewProjectionInput) =>
snapshot.queryTimed(instantRange),
},
Renderer: ({ projection, environment }) => (
{projection.map(({ event }) => (