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