@moltenship/calendar 1.0.0-rc.2 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +27 -6
- package/dist/index.d.mts +3 -3
- package/dist/index.mjs +2 -2
- package/docs/accessibility.md +305 -0
- package/docs/agents/changes.md +449 -0
- package/docs/agents/coding-agents.md +116 -0
- package/docs/agents/connect.md +444 -0
- package/docs/agents/deleting.md +296 -0
- package/docs/agents/reference.md +511 -0
- package/docs/agents/server.md +317 -0
- package/docs/agents/webmcp.md +153 -0
- package/docs/agents.md +355 -0
- package/docs/annotations.md +198 -0
- package/docs/api/changes.md +264 -0
- package/docs/api/components.md +245 -0
- package/docs/api/dnd-kit.md +265 -0
- package/docs/api/events.md +153 -0
- package/docs/api/primitives.md +218 -0
- package/docs/api/store.md +92 -0
- package/docs/api.md +57 -0
- package/docs/availability.md +576 -0
- package/docs/comparison.md +278 -0
- package/docs/concepts/anatomy.md +73 -0
- package/docs/concepts/events.md +163 -0
- package/docs/concepts/how-it-works.md +112 -0
- package/docs/concepts/state.md +244 -0
- package/docs/concepts/time.md +168 -0
- package/docs/customization.md +271 -0
- package/docs/frameworks.md +116 -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/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/tanstack-query.md +485 -0
- package/docs/ics/feed.md +484 -0
- package/docs/ics/import.md +183 -0
- package/docs/ics/reference.md +482 -0
- package/docs/ics.md +142 -0
- package/docs/index.md +149 -0
- package/docs/installation.md +209 -0
- package/docs/interactions.md +441 -0
- package/docs/llms.txt +99 -0
- package/docs/migrating-to-2.md +497 -0
- package/docs/quick-start.md +163 -0
- package/docs/recurrence/calendar.md +598 -0
- package/docs/recurrence/model.md +128 -0
- package/docs/recurrence/reference.md +547 -0
- package/docs/recurrence.md +122 -0
- package/docs/stylex.md +290 -0
- package/docs/temporal/daylight-saving-time.md +172 -0
- package/docs/temporal/month-grid.md +119 -0
- package/docs/temporal/reference.md +167 -0
- package/docs/temporal.md +105 -0
- package/docs/testing.md +600 -0
- package/docs/theme-builder.md +82 -0
- package/docs/theming.md +275 -0
- package/docs/undo-redo.md +347 -0
- package/docs/views/agenda.md +222 -0
- package/docs/views/custom-views.md +195 -0
- package/docs/views/month.md +110 -0
- package/docs/views/resource-columns.md +265 -0
- package/docs/views/resource-timeline.md +226 -0
- package/docs/views/scrolling.md +193 -0
- package/docs/views/week-and-day.md +258 -0
- package/docs/views/year.md +138 -0
- package/docs/views.md +69 -0
- package/package.json +42 -14
- package/skills/moltenship-time/SKILL.md +77 -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 +175 -0
- package/skills/moltenship-time/references/mistakes.md +100 -0
- package/skills/moltenship-time/references/solid.md +213 -0
- package/skills/moltenship-time/references/state.md +129 -0
- package/skills/moltenship-time/references/testing.md +176 -0
|
@@ -0,0 +1,630 @@
|
|
|
1
|
+
# Next.js App Router example
|
|
2
|
+
|
|
3
|
+
A calendar whose view and date live in the URL, loaded by a Server Component and saved through Server Actions.
|
|
4
|
+
|
|
5
|
+
Source: https://time.molten.sh/docs/react/guides/nextjs-app-router
|
|
6
|
+
|
|
7
|
+
[Next.js and server rendering](./nextjs.md) covers the basics: Client Components, strings
|
|
8
|
+
instead of Temporal values, and `now` and the time zone from the server. This page walks through a
|
|
9
|
+
complete App Router route built on them. [Open the example](https://time.molten.sh/examples/nextjs), then read its source
|
|
10
|
+
here. To load events in the browser from an API instead, see
|
|
11
|
+
[Load events with TanStack Query](./tanstack-query.md).
|
|
12
|
+
|
|
13
|
+
- **The URL holds the view and the date**, as in `/examples/nextjs?view=week&date=2026-10-12`.
|
|
14
|
+
Previous, next, Today and the view switcher change it, and Back and Forward work.
|
|
15
|
+
- **A Server Component fetches the meetings** for the range the URL shows.
|
|
16
|
+
- **Server Actions save** created, moved and resized meetings. The calendar proposes each change, the
|
|
17
|
+
server decides, and the page renders again with the result.
|
|
18
|
+
- **The time zone comes from a cookie**, and the first render's clock from the server.
|
|
19
|
+
|
|
20
|
+
The route has eight files:
|
|
21
|
+
|
|
22
|
+
| File | Kind | What it does |
|
|
23
|
+
| ------------------- | ---------------- | --------------------------------------------------------- |
|
|
24
|
+
| `layout.tsx` | Server Component | The heading and the frame, which stay put as pages change |
|
|
25
|
+
| `page.tsx` | Server Component | Reads the URL and the cookies, and fetches the meetings |
|
|
26
|
+
| `loading.tsx` | Server Component | The first load's skeleton |
|
|
27
|
+
| `location.ts` | Shared | The URL's view and date, and the dates they show |
|
|
28
|
+
| `meetings.ts` | Server only | An in-memory store that stands in for your database |
|
|
29
|
+
| `actions.ts` | Server Actions | Save meetings and the time zone |
|
|
30
|
+
| `calendar.ts` | Client | The calendar, its views and its policies |
|
|
31
|
+
| `team-calendar.tsx` | Client Component | The calendar's state, wired to the URL and the actions |
|
|
32
|
+
|
|
33
|
+
## The URL
|
|
34
|
+
|
|
35
|
+
The view and the date are search params. A missing or broken view falls back to the week, and a
|
|
36
|
+
missing or broken date to today, so every link opens something:
|
|
37
|
+
|
|
38
|
+
```ts title="location.ts"
|
|
39
|
+
export const meetingViews = ["week", "day", "month"] as const;
|
|
40
|
+
export type MeetingView = (typeof meetingViews)[number];
|
|
41
|
+
|
|
42
|
+
/** Where the calendar is, as the URL says: `?view=week&date=2026-10-12`. */
|
|
43
|
+
export interface CalendarLocation {
|
|
44
|
+
readonly date: string;
|
|
45
|
+
readonly view: MeetingView;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
type SearchParams = Readonly<Record<string, string | string[] | undefined>>;
|
|
49
|
+
|
|
50
|
+
/** Reads the view and date from the URL. Missing or broken ones fall back to this week. */
|
|
51
|
+
export function parseLocation(params: SearchParams, today: Temporal.PlainDate): CalendarLocation {
|
|
52
|
+
const view = meetingViews.find((name) => name === params.view) ?? "week";
|
|
53
|
+
return { date: (parseDate(params.date) ?? today).toString(), view };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function parseDate(value: string | string[] | undefined): Temporal.PlainDate | undefined {
|
|
57
|
+
if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return undefined;
|
|
58
|
+
try {
|
|
59
|
+
return Temporal.PlainDate.from(value, { overflow: "reject" });
|
|
60
|
+
} catch {
|
|
61
|
+
return undefined;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function locationSearch({ date, view }: CalendarLocation): string {
|
|
66
|
+
return new URLSearchParams({ view, date }).toString();
|
|
67
|
+
}
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
## The page
|
|
71
|
+
|
|
72
|
+
The page is a Server Component. It reads the URL, the visitor and the clock, and fetches the
|
|
73
|
+
meetings for the range the calendar will show:
|
|
74
|
+
|
|
75
|
+
```tsx title="page.tsx"
|
|
76
|
+
import { TeamCalendar } from "./team-calendar";
|
|
77
|
+
import { parseLocation, visibleRange } from "./location";
|
|
78
|
+
import { findMeetings, getVisitor } from "./meetings";
|
|
79
|
+
|
|
80
|
+
interface MeetingsPageProps {
|
|
81
|
+
readonly searchParams: Promise<Record<string, string | string[] | undefined>>;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export default async function MeetingsPage({ searchParams }: MeetingsPageProps) {
|
|
85
|
+
const visitor = await getVisitor();
|
|
86
|
+
// Until the browser has said which zone it's in, render in UTC.
|
|
87
|
+
const timeZone = visitor.timeZone ?? "UTC";
|
|
88
|
+
// Read the clock once, and hand the instant to the browser, so both render the same today.
|
|
89
|
+
const now = Temporal.Now.instant();
|
|
90
|
+
const location = parseLocation(
|
|
91
|
+
await searchParams,
|
|
92
|
+
now.toZonedDateTimeISO(timeZone).toPlainDate(),
|
|
93
|
+
);
|
|
94
|
+
const meetings = await findMeetings(visitor, visibleRange(location, timeZone));
|
|
95
|
+
|
|
96
|
+
return (
|
|
97
|
+
<TeamCalendar
|
|
98
|
+
location={location}
|
|
99
|
+
meetings={meetings}
|
|
100
|
+
now={now.toString()}
|
|
101
|
+
timeZone={timeZone}
|
|
102
|
+
timeZoneFromCookie={visitor.timeZone !== undefined}
|
|
103
|
+
/>
|
|
104
|
+
);
|
|
105
|
+
}
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
- **It renders on every request.** Reading `searchParams` and cookies makes the page dynamic.
|
|
109
|
+
- **`now` is read once**, here, and passed down as a string, so the server and the browser render
|
|
110
|
+
the same today. Once the page has hydrated, the calendar follows the browser's clock instead, so
|
|
111
|
+
the now line keeps moving between server renders.
|
|
112
|
+
- **Meetings arrive as strings.** `meetings.ts` sends them as `MeetingJson`, with ISO 8601 times:
|
|
113
|
+
|
|
114
|
+
```ts title="meetings.ts"
|
|
115
|
+
/** A meeting as the server sends it: Client Components get strings, not Temporal values. */
|
|
116
|
+
export interface MeetingJson {
|
|
117
|
+
readonly color: CalendarEventColor;
|
|
118
|
+
readonly end: string;
|
|
119
|
+
readonly id: string;
|
|
120
|
+
readonly start: string;
|
|
121
|
+
readonly title: string;
|
|
122
|
+
}
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
The server works out the dates with the functions the views use, so it fetches exactly what they
|
|
126
|
+
show. The example's tests check that the two agree for every view:
|
|
127
|
+
|
|
128
|
+
```ts title="location.ts"
|
|
129
|
+
export const locale = "en-US";
|
|
130
|
+
export const weekRules = { firstDay: 1, minimalDays: 4, weekend: [6, 7] } as const;
|
|
131
|
+
|
|
132
|
+
/** The dates a location shows, by the same rules as its view. */
|
|
133
|
+
export function visibleDates({ date, view }: CalendarLocation): PlainDateInterval {
|
|
134
|
+
const anchor = Temporal.PlainDate.from(date);
|
|
135
|
+
switch (view) {
|
|
136
|
+
case "day":
|
|
137
|
+
return timeGridRange(anchor, { count: 1, kind: "days" }, weekRules);
|
|
138
|
+
case "week":
|
|
139
|
+
return timeGridRange(anchor, { kind: "week" }, weekRules);
|
|
140
|
+
case "month":
|
|
141
|
+
return getMonthRange(anchor, environment("UTC"));
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** The instants between those dates' starts of day in `timeZone`: the events to fetch. */
|
|
146
|
+
export function visibleRange(location: CalendarLocation, timeZone: string): InstantInterval {
|
|
147
|
+
return resolveViewInstantRange(visibleDates(location), timeZone);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export function environment(timeZone: string): CalendarEnvironmentBase {
|
|
151
|
+
return { direction: "ltr", disambiguation: "compatible", locale, timeZone, weekRules };
|
|
152
|
+
}
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
`visibleRange` turns the dates into instants in the visitor's time zone, as `Root` does for
|
|
156
|
+
`onVisibleRangeChange`. A week in Tokyo starts nine hours before a week in UTC.
|
|
157
|
+
|
|
158
|
+
## The calendar
|
|
159
|
+
|
|
160
|
+
The calendar is defined in a client module. Meetings have a time, so a policy refuses drops on the
|
|
161
|
+
all-day row before they reach the server:
|
|
162
|
+
|
|
163
|
+
```ts title="calendar.ts"
|
|
164
|
+
import {
|
|
165
|
+
createCalendar,
|
|
166
|
+
defineEventAdapter,
|
|
167
|
+
minimumDurationPolicy,
|
|
168
|
+
snapPolicy,
|
|
169
|
+
type CalendarEventChange,
|
|
170
|
+
type CalendarPolicy,
|
|
171
|
+
} from "@moltenship/calendar";
|
|
172
|
+
|
|
173
|
+
import type { CalendarEventColor } from "@/components/calendar/event-colors";
|
|
174
|
+
import { createMonthView } from "@/components/calendar/month-view/month-view";
|
|
175
|
+
import { createDayView, createWeekView } from "@/components/calendar/time-grid-view/time-grid-view";
|
|
176
|
+
|
|
177
|
+
export interface Meeting {
|
|
178
|
+
readonly color: CalendarEventColor;
|
|
179
|
+
readonly end: Temporal.Instant;
|
|
180
|
+
readonly id: string;
|
|
181
|
+
/** Created in this tab and not saved yet, so it has no ID from the server. */
|
|
182
|
+
readonly pending?: true;
|
|
183
|
+
readonly start: Temporal.Instant;
|
|
184
|
+
readonly title: string;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
export type MeetingChange = CalendarEventChange<Meeting, string, never>;
|
|
188
|
+
|
|
189
|
+
const getEventColor = (meeting: Meeting) => meeting.color;
|
|
190
|
+
|
|
191
|
+
export const Calendar = createCalendar<Meeting>()({
|
|
192
|
+
eventAdapter: defineEventAdapter<Meeting>()({
|
|
193
|
+
getId: (meeting) => meeting.id,
|
|
194
|
+
getInterval: ({ end, start }) => ({ end, kind: "timed", start }),
|
|
195
|
+
getResourceIds: () => [],
|
|
196
|
+
getTitle: (meeting) => meeting.title,
|
|
197
|
+
// The server knows a new meeting by the ID it gives it, so it can't move until then.
|
|
198
|
+
isReadOnly: (meeting) => meeting.pending === true,
|
|
199
|
+
}),
|
|
200
|
+
views: [
|
|
201
|
+
createWeekView<Meeting>({ dayView: "day", getEventColor }),
|
|
202
|
+
createDayView<Meeting>({ getEventColor }),
|
|
203
|
+
createMonthView<Meeting>({ getEventColor }),
|
|
204
|
+
],
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
// Meetings always have a time, so drops on the all-day row stop here, before the server.
|
|
208
|
+
const timedOnly: CalendarPolicy<Meeting, string, never> = ({ proposed }) =>
|
|
209
|
+
proposed === null || proposed.kind === "timed"
|
|
210
|
+
? { type: "accept" }
|
|
211
|
+
: { reason: "meetings-need-a-time", type: "reject" };
|
|
212
|
+
|
|
213
|
+
export const policies = [
|
|
214
|
+
timedOnly,
|
|
215
|
+
snapPolicy<Meeting, string, never>({ minutes: 15 }),
|
|
216
|
+
minimumDurationPolicy<Meeting, string, never>({ minutes: 15 }),
|
|
217
|
+
];
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
The Client Component wires it to the URL, the Server Actions and the time zone cookie:
|
|
221
|
+
|
|
222
|
+
```tsx title="team-calendar.tsx"
|
|
223
|
+
const viewOptions = [
|
|
224
|
+
{ label: "Week", value: "week" },
|
|
225
|
+
{ label: "Day", value: "day" },
|
|
226
|
+
{ label: "Month", value: "month" },
|
|
227
|
+
] as const;
|
|
228
|
+
|
|
229
|
+
export interface TeamCalendarProps {
|
|
230
|
+
readonly location: CalendarLocation;
|
|
231
|
+
readonly meetings: readonly MeetingJson[];
|
|
232
|
+
/** When the server rendered the page, so both sides agree on today. */
|
|
233
|
+
readonly now: string;
|
|
234
|
+
readonly timeZone: string;
|
|
235
|
+
/** `false` on a first visit, when the time zone is a guess. */
|
|
236
|
+
readonly timeZoneFromCookie: boolean;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
const subscribeToNothing = () => () => undefined;
|
|
240
|
+
|
|
241
|
+
/** `false` while the page hydrates, `true` from then on. */
|
|
242
|
+
function useHydrated() {
|
|
243
|
+
return useSyncExternalStore(
|
|
244
|
+
subscribeToNothing,
|
|
245
|
+
() => true,
|
|
246
|
+
() => false,
|
|
247
|
+
);
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
export function TeamCalendar(props: TeamCalendarProps) {
|
|
251
|
+
const { loading, location, navigate } = useCalendarLocation(props.location);
|
|
252
|
+
const { meetings, message, save } = useMeetings(props.meetings);
|
|
253
|
+
const [timeZone, setTimeZone] = useTimeZone(props.timeZone, props.timeZoneFromCookie);
|
|
254
|
+
// The server's clock while hydrating, so both sides render the same today. The browser's clock
|
|
255
|
+
// after that, so the now line keeps moving between server renders.
|
|
256
|
+
const serverNow = useHydrated() ? {} : { now: Temporal.Instant.from(props.now) };
|
|
257
|
+
|
|
258
|
+
return (
|
|
259
|
+
<Calendar.Root
|
|
260
|
+
{...serverNow}
|
|
261
|
+
anchorDate={Temporal.PlainDate.from(location.date)}
|
|
262
|
+
events={meetings}
|
|
263
|
+
locale={locale}
|
|
264
|
+
onAnchorDateChange={(date) => navigate({ date: date.toString() })}
|
|
265
|
+
onEventChange={save}
|
|
266
|
+
onViewChange={(view) => navigate({ view })}
|
|
267
|
+
policies={policies}
|
|
268
|
+
timeZone={timeZone}
|
|
269
|
+
view={location.view}
|
|
270
|
+
weekRules={weekRules}
|
|
271
|
+
>
|
|
272
|
+
<Calendar.Frame className="flex h-full flex-col">
|
|
273
|
+
<CalendarToolbar calendar={Calendar} className="border-b">
|
|
274
|
+
<ViewSwitcher
|
|
275
|
+
onValueChange={(view) => navigate({ view })}
|
|
276
|
+
options={viewOptions}
|
|
277
|
+
value={location.view}
|
|
278
|
+
/>
|
|
279
|
+
</CalendarToolbar>
|
|
280
|
+
{/* Stays on screen while the next range loads; only this bar says so. */}
|
|
281
|
+
<div
|
|
282
|
+
aria-hidden="true"
|
|
283
|
+
className={`h-0.5 shrink-0 bg-brand transition-opacity ${loading ? "opacity-100 motion-safe:animate-pulse" : "opacity-0"}`}
|
|
284
|
+
/>
|
|
285
|
+
<Calendar.Viewport aria-busy={loading} className="min-h-0 flex-1">
|
|
286
|
+
<Calendar.ActiveView />
|
|
287
|
+
</Calendar.Viewport>
|
|
288
|
+
<footer className="flex min-h-12 shrink-0 flex-wrap items-center gap-x-4 gap-y-2 border-t px-4 py-2 text-sm">
|
|
289
|
+
<TimeZonePicker onChange={setTimeZone} value={timeZone} />
|
|
290
|
+
<p className="text-fd-muted-foreground" role="status">
|
|
291
|
+
{message}
|
|
292
|
+
</p>
|
|
293
|
+
</footer>
|
|
294
|
+
<Calendar.Announcer messages={calendarAnnouncements} />
|
|
295
|
+
</Calendar.Frame>
|
|
296
|
+
</Calendar.Root>
|
|
297
|
+
);
|
|
298
|
+
}
|
|
299
|
+
```
|
|
300
|
+
|
|
301
|
+
`view` and `anchorDate` are controlled, so the URL decides what the calendar shows. `timeZone` is
|
|
302
|
+
controlled too, and comes from the cookie. `useHydrated` is `false` only while the page hydrates, so
|
|
303
|
+
`now` is the server's for that first render and the calendar's own clock after it.
|
|
304
|
+
|
|
305
|
+
## Navigation
|
|
306
|
+
|
|
307
|
+
When someone moves to another week or view, the calendar calls `onAnchorDateChange` or
|
|
308
|
+
`onViewChange`. The component pushes a new URL instead of keeping the change in state:
|
|
309
|
+
|
|
310
|
+
```tsx title="team-calendar.tsx"
|
|
311
|
+
/** The view and date from the URL. Changing them pushes a new URL; the calendar moves at once. */
|
|
312
|
+
function useCalendarLocation(location: CalendarLocation) {
|
|
313
|
+
const router = useRouter();
|
|
314
|
+
const pathname = usePathname();
|
|
315
|
+
const [loading, startNavigation] = useTransition();
|
|
316
|
+
// Shown until the new page has rendered on the server, so the grid moves on the click.
|
|
317
|
+
const [shown, show] = useOptimistic(location);
|
|
318
|
+
const queued = useRef<CalendarLocation | null>(null);
|
|
319
|
+
|
|
320
|
+
function navigate(change: Partial<CalendarLocation>) {
|
|
321
|
+
const first = queued.current === null;
|
|
322
|
+
queued.current = { ...(queued.current ?? shown), ...change };
|
|
323
|
+
if (!first) return;
|
|
324
|
+
// Opening a day from the month view changes the date and the view in one click. Wait for
|
|
325
|
+
// both, so they land in one URL and one history entry.
|
|
326
|
+
queueMicrotask(() => {
|
|
327
|
+
const next = queued.current ?? shown;
|
|
328
|
+
queued.current = null;
|
|
329
|
+
if (next.date === shown.date && next.view === shown.view) return;
|
|
330
|
+
startNavigation(() => {
|
|
331
|
+
show(next);
|
|
332
|
+
router.push(`${pathname}?${locationSearch(next)}`, { scroll: false });
|
|
333
|
+
});
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
return { loading, location: shown, navigate };
|
|
338
|
+
}
|
|
339
|
+
```
|
|
340
|
+
|
|
341
|
+
- **The grid moves on the click.** `router.push` runs inside a transition, and `useOptimistic` shows
|
|
342
|
+
the new view and date at once. Their meetings arrive with the server's render. Until then the grid
|
|
343
|
+
shows the meetings it already has that fall in the new range: all of them when zooming from a
|
|
344
|
+
month into a week, none when stepping to the next week.
|
|
345
|
+
- **The page says it's loading.** The transition's `loading` flag sets `aria-busy` on the viewport
|
|
346
|
+
and shows a thin bar under the toolbar. The grid itself never blanks.
|
|
347
|
+
- **One click, one URL.** Opening a day from the month view changes the view and the date. The
|
|
348
|
+
changes queue for one microtask, so they land in a single URL and a single history entry.
|
|
349
|
+
- **Back and Forward** restore that URL's render from the Next.js router's cache, or fetch it again
|
|
350
|
+
when it isn't cached, as after a save or a zone change. The controlled props follow.
|
|
351
|
+
|
|
352
|
+
The calendar stays mounted through all of this. Next.js keeps the page on screen while it fetches
|
|
353
|
+
the next render, and the props change in place, so the scroll position and the focus survive.
|
|
354
|
+
`loading.tsx` only shows when the route first loads, before there's a page to keep:
|
|
355
|
+
|
|
356
|
+
```tsx title="loading.tsx"
|
|
357
|
+
// The first visit's fallback. Later navigations keep the calendar on screen instead.
|
|
358
|
+
export default function Loading() {
|
|
359
|
+
return (
|
|
360
|
+
<div className="flex h-full flex-col" role="status">
|
|
361
|
+
<span className="sr-only">Loading calendar</span>
|
|
362
|
+
<div className="flex h-14 shrink-0 items-center gap-3 border-b px-4">
|
|
363
|
+
<span className="h-8 w-20 rounded-full bg-fd-muted" />
|
|
364
|
+
<span className="h-5 w-40 rounded-md bg-fd-muted" />
|
|
365
|
+
</div>
|
|
366
|
+
<div className="flex-1 bg-[linear-gradient(to_bottom,var(--color-fd-border)_1px,transparent_1px)] bg-size-[100%_3rem]" />
|
|
367
|
+
</div>
|
|
368
|
+
);
|
|
369
|
+
}
|
|
370
|
+
```
|
|
371
|
+
|
|
372
|
+
## Saving
|
|
373
|
+
|
|
374
|
+
The calendar proposes; the app commits. Every move, resize and create runs through the calendar's
|
|
375
|
+
policies first, then reaches `onEventChange`, which calls a Server Action:
|
|
376
|
+
|
|
377
|
+
```ts title="actions.ts"
|
|
378
|
+
export type SaveResult =
|
|
379
|
+
| { readonly ok: true }
|
|
380
|
+
| { readonly ok: false; readonly reason: "invalid" | "in-the-past" | "not-found" | "full" };
|
|
381
|
+
|
|
382
|
+
interface Times {
|
|
383
|
+
readonly end: string;
|
|
384
|
+
readonly start: string;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
// Server Actions are public endpoints: check every argument, whatever the calendar sent.
|
|
388
|
+
function parseTimes(input: unknown) {
|
|
389
|
+
const { end, start } = (input ?? {}) as Partial<Record<keyof Times, unknown>>;
|
|
390
|
+
if (typeof start !== "string" || typeof end !== "string") return undefined;
|
|
391
|
+
try {
|
|
392
|
+
const times = { end: Temporal.Instant.from(end), start: Temporal.Instant.from(start) };
|
|
393
|
+
const minutes = times.start.until(times.end).total("minutes");
|
|
394
|
+
return minutes >= 15 && minutes <= 24 * 60 ? times : undefined;
|
|
395
|
+
} catch {
|
|
396
|
+
return undefined;
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/** The rule this server adds on top of the calendar's policies. */
|
|
401
|
+
function startsInThePast(times: { readonly start: Temporal.Instant }) {
|
|
402
|
+
return Temporal.Instant.compare(times.start, Temporal.Now.instant()) < 0;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
export async function createMeeting(input: Times): Promise<SaveResult> {
|
|
406
|
+
const times = parseTimes(input);
|
|
407
|
+
if (times === undefined) return { ok: false, reason: "invalid" };
|
|
408
|
+
if (startsInThePast(times)) return { ok: false, reason: "in-the-past" };
|
|
409
|
+
|
|
410
|
+
const session = await startSession(await getVisitor());
|
|
411
|
+
if (insertMeeting(session, times) === undefined) return { ok: false, reason: "full" };
|
|
412
|
+
// Re-render the page in this response, so the new meeting arrives with its ID.
|
|
413
|
+
refresh();
|
|
414
|
+
return { ok: true };
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/** Moves and both resizes send the meeting's new start and end. */
|
|
418
|
+
export async function moveMeeting(input: Times & { readonly id: string }): Promise<SaveResult> {
|
|
419
|
+
const times = parseTimes(input);
|
|
420
|
+
const id: unknown = input?.id;
|
|
421
|
+
if (times === undefined || typeof id !== "string") return { ok: false, reason: "invalid" };
|
|
422
|
+
if (startsInThePast(times)) return { ok: false, reason: "in-the-past" };
|
|
423
|
+
|
|
424
|
+
const session = await startSession(await getVisitor());
|
|
425
|
+
if (!updateMeeting(session, id, times)) return { ok: false, reason: "not-found" };
|
|
426
|
+
refresh();
|
|
427
|
+
return { ok: true };
|
|
428
|
+
}
|
|
429
|
+
```
|
|
430
|
+
|
|
431
|
+
- **Check every argument.** A Server Action is a public endpoint, and anyone can call it with
|
|
432
|
+
anything. The calendar's snap and minimum duration don't protect the server.
|
|
433
|
+
- **The server has the last word.** This one refuses meetings that start in the past, a rule the
|
|
434
|
+
calendar doesn't know.
|
|
435
|
+
- **`refresh()` re-renders the page** in the same response as the action's result, so the saved
|
|
436
|
+
meeting arrives without another request. If your reads are cached with `"use cache"`, call
|
|
437
|
+
`updateTag` instead.
|
|
438
|
+
- **Saves run one at a time.** Next.js sends a page's Server Actions in order, so two quick moves of
|
|
439
|
+
one meeting are saved in the order they were made.
|
|
440
|
+
|
|
441
|
+
On the client, `save` turns the action's result into the promise the calendar waits for:
|
|
442
|
+
|
|
443
|
+
```tsx title="team-calendar.tsx"
|
|
444
|
+
function fromJson(meeting: MeetingJson): Meeting {
|
|
445
|
+
return {
|
|
446
|
+
...meeting,
|
|
447
|
+
end: Temporal.Instant.from(meeting.end),
|
|
448
|
+
start: Temporal.Instant.from(meeting.start),
|
|
449
|
+
};
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
function addMeeting(meetings: readonly Meeting[], meeting: Meeting): readonly Meeting[] {
|
|
453
|
+
return [...meetings, meeting];
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
function send(change: MeetingChange): Promise<SaveResult> {
|
|
457
|
+
if (change.proposed?.kind !== "timed") return Promise.resolve({ ok: false, reason: "invalid" });
|
|
458
|
+
const times = { end: change.proposed.end.toString(), start: change.proposed.start.toString() };
|
|
459
|
+
return change.cause === "create"
|
|
460
|
+
? createMeeting(times)
|
|
461
|
+
: moveMeeting({ ...times, id: change.eventId });
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
const refusals: Record<Exclude<SaveResult, { ok: true }>["reason"], string> = {
|
|
465
|
+
full: "Not saved: this example keeps 200 meetings at most.",
|
|
466
|
+
"in-the-past": "Not saved: the server refuses meetings that start in the past.",
|
|
467
|
+
invalid: "Not saved: the server couldn't read the change.",
|
|
468
|
+
"not-found": "Not saved: the meeting is gone. Reload the page.",
|
|
469
|
+
};
|
|
470
|
+
|
|
471
|
+
/** The server's meetings, plus new ones still saving. */
|
|
472
|
+
function useMeetings(json: readonly MeetingJson[]) {
|
|
473
|
+
const saved = useMemo(() => json.map(fromJson), [json]);
|
|
474
|
+
// The calendar shows a moved or resized meeting in its new place while it saves. A new one has
|
|
475
|
+
// no ID until the server gives it one, so it's shown here until the page re-renders with it.
|
|
476
|
+
const [meetings, addPending] = useOptimistic(saved, addMeeting);
|
|
477
|
+
const [message, setMessage] = useState("");
|
|
478
|
+
|
|
479
|
+
// The calendar keeps a change pending until this promise settles, and undoes it on a rejection.
|
|
480
|
+
function save(change: MeetingChange): Promise<void> {
|
|
481
|
+
const { promise, reject, resolve } = Promise.withResolvers<void>();
|
|
482
|
+
// Cleared first, so the same refusal twice is announced twice.
|
|
483
|
+
setMessage("");
|
|
484
|
+
startTransition(async () => {
|
|
485
|
+
if (change.cause === "create" && change.proposed.kind === "timed") {
|
|
486
|
+
const { end, start } = change.proposed;
|
|
487
|
+
addPending({
|
|
488
|
+
color: "blue",
|
|
489
|
+
end,
|
|
490
|
+
id: change.id,
|
|
491
|
+
pending: true,
|
|
492
|
+
start,
|
|
493
|
+
title: "New meeting",
|
|
494
|
+
});
|
|
495
|
+
}
|
|
496
|
+
const result = await send(change).catch(() => null);
|
|
497
|
+
if (result?.ok === true) {
|
|
498
|
+
resolve();
|
|
499
|
+
} else {
|
|
500
|
+
setMessage(
|
|
501
|
+
result === null ? "Not saved: the server didn't answer." : refusals[result.reason],
|
|
502
|
+
);
|
|
503
|
+
reject(new Error(result?.reason ?? "network"));
|
|
504
|
+
}
|
|
505
|
+
});
|
|
506
|
+
return promise;
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
return { meetings, message, save };
|
|
510
|
+
}
|
|
511
|
+
```
|
|
512
|
+
|
|
513
|
+
- **Moves and resizes** stay where they were dropped while the promise is pending. The calendar
|
|
514
|
+
shows them as saving, then keeps them in place until the page's next render has the saved times.
|
|
515
|
+
- **A refusal** rejects the promise, and the calendar moves the meeting back. The reason shows under
|
|
516
|
+
the calendar.
|
|
517
|
+
- **New meetings** have no ID until the server gives them one, so the calendar can't show them as
|
|
518
|
+
pending. `useOptimistic` adds them to the meetings on screen until the page renders again with the
|
|
519
|
+
saved one. They're marked `pending`, and the adapter's `isReadOnly` keeps them still until then.
|
|
520
|
+
|
|
521
|
+
## The time zone
|
|
522
|
+
|
|
523
|
+
The page renders in the zone from the `time-zone` cookie. On a first visit there's no cookie, so the
|
|
524
|
+
server renders in UTC, and the browser sends its own zone once it has hydrated:
|
|
525
|
+
|
|
526
|
+
```tsx title="team-calendar.tsx"
|
|
527
|
+
const timeZones = [
|
|
528
|
+
"America/Los_Angeles",
|
|
529
|
+
"America/New_York",
|
|
530
|
+
"Europe/London",
|
|
531
|
+
"Europe/Berlin",
|
|
532
|
+
"Asia/Kolkata",
|
|
533
|
+
"Asia/Tokyo",
|
|
534
|
+
"Australia/Sydney",
|
|
535
|
+
"UTC",
|
|
536
|
+
];
|
|
537
|
+
|
|
538
|
+
/** The cookie's time zone. A first visit has none: store the browser's, and render in it. */
|
|
539
|
+
function useTimeZone(timeZone: string, fromCookie: boolean) {
|
|
540
|
+
const [shown, show] = useOptimistic(timeZone);
|
|
541
|
+
|
|
542
|
+
// The calendar switches at once, and the page renders again in the new zone when the cookie is
|
|
543
|
+
// set. If saving fails, it goes back to the zone the server rendered in.
|
|
544
|
+
const change = useCallback(
|
|
545
|
+
(next: string) => {
|
|
546
|
+
startTransition(async () => {
|
|
547
|
+
show(next);
|
|
548
|
+
await saveTimeZone(next).catch(() => undefined);
|
|
549
|
+
});
|
|
550
|
+
},
|
|
551
|
+
[show],
|
|
552
|
+
);
|
|
553
|
+
|
|
554
|
+
useEffect(() => {
|
|
555
|
+
if (!fromCookie) change(Temporal.Now.timeZoneId());
|
|
556
|
+
}, [change, fromCookie]);
|
|
557
|
+
|
|
558
|
+
return [shown, change] as const;
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
function TimeZonePicker({
|
|
562
|
+
onChange,
|
|
563
|
+
value,
|
|
564
|
+
}: {
|
|
565
|
+
readonly onChange: (timeZone: string) => void;
|
|
566
|
+
readonly value: string;
|
|
567
|
+
}) {
|
|
568
|
+
const options = (timeZones.includes(value) ? timeZones : [value, ...timeZones]).map((zone) => ({
|
|
569
|
+
label: zone.replaceAll("_", " "),
|
|
570
|
+
value: zone,
|
|
571
|
+
}));
|
|
572
|
+
return (
|
|
573
|
+
<Select items={options} onValueChange={(zone) => zone !== null && onChange(zone)} value={value}>
|
|
574
|
+
<SelectTrigger aria-label="Time zone" className="w-48 rounded-full" size="sm">
|
|
575
|
+
<SelectValue />
|
|
576
|
+
</SelectTrigger>
|
|
577
|
+
<SelectContent alignItemWithTrigger={false}>
|
|
578
|
+
<SelectGroup>
|
|
579
|
+
{options.map((option) => (
|
|
580
|
+
<SelectItem key={option.value} value={option.value}>
|
|
581
|
+
{option.label}
|
|
582
|
+
</SelectItem>
|
|
583
|
+
))}
|
|
584
|
+
</SelectGroup>
|
|
585
|
+
</SelectContent>
|
|
586
|
+
</Select>
|
|
587
|
+
);
|
|
588
|
+
}
|
|
589
|
+
```
|
|
590
|
+
|
|
591
|
+
`useOptimistic` switches the calendar to the new zone at once. Setting a cookie in a Server Action
|
|
592
|
+
re-renders the page in the same response, so the meetings for the new zone's range arrive with the
|
|
593
|
+
action's result. Every later request renders in the right zone from the start, and hydration
|
|
594
|
+
matches. The picker under the calendar calls the same action.
|
|
595
|
+
|
|
596
|
+
Switching zones keeps each meeting at its instant, so a 09:30 standup in Tokyo shows in the small
|
|
597
|
+
hours in Berlin. A first visit has no zone to keep, so its sample meetings simply follow the browser's.
|
|
598
|
+
|
|
599
|
+
```ts title="actions.ts"
|
|
600
|
+
export async function saveTimeZone(input: string): Promise<void> {
|
|
601
|
+
const timeZone = timeZoneOf(input);
|
|
602
|
+
if (timeZone === undefined) return;
|
|
603
|
+
const visitor = await getVisitor();
|
|
604
|
+
// Switching zones keeps the meetings at the instants the visitor saw, so they move on the clock.
|
|
605
|
+
// A first visit has no zone to keep, and its sample meetings simply follow the new one.
|
|
606
|
+
if (visitor.timeZone !== undefined && visitor.timeZone !== timeZone) await startSession(visitor);
|
|
607
|
+
// Setting a cookie re-renders the page in this response, in the new zone.
|
|
608
|
+
await setTimeZoneCookie(timeZone);
|
|
609
|
+
}
|
|
610
|
+
```
|
|
611
|
+
|
|
612
|
+
## Temporal in the browser
|
|
613
|
+
|
|
614
|
+
The server runs on Node.js 26, which has `Temporal`. The calendar also renders while the page
|
|
615
|
+
hydrates, so `Temporal` has to exist in the browser before then. `team-calendar.tsx` imports
|
|
616
|
+
`temporal-polyfill/global` before anything else. The polyfill installs itself only in browsers
|
|
617
|
+
without `Temporal`, but as a static import every browser downloads it. The dynamic import that
|
|
618
|
+
[Installation](../installation.md#temporal) shows saves that, but only suits a calendar that renders
|
|
619
|
+
after hydration.
|
|
620
|
+
|
|
621
|
+
## Make it yours
|
|
622
|
+
|
|
623
|
+
- **Replace `meetings.ts`** with your database. Its functions take the visitor and a range, as
|
|
624
|
+
queries would.
|
|
625
|
+
- **Use your auth** in place of the session cookie, and check in every action that the visitor owns
|
|
626
|
+
the meeting they're changing.
|
|
627
|
+
- **Refuse stale writes.** Give meetings a revision, send it with each change, and refuse a change
|
|
628
|
+
made to an older one. The adapter's `getRevision` tells the calendar about them.
|
|
629
|
+
[Sync with Google Calendar](./google-calendar-sync.md) does the same with etags.
|
|
630
|
+
- **Cache the reads** with `"use cache"` and `cacheTag`, and call `updateTag` from the actions.
|