@moltenship/calendar 1.0.0-rc.2 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/README.md +27 -6
  2. package/dist/index.d.mts +3 -3
  3. package/dist/index.mjs +2 -2
  4. package/docs/accessibility.md +305 -0
  5. package/docs/agents/changes.md +449 -0
  6. package/docs/agents/coding-agents.md +116 -0
  7. package/docs/agents/connect.md +444 -0
  8. package/docs/agents/deleting.md +296 -0
  9. package/docs/agents/reference.md +511 -0
  10. package/docs/agents/server.md +317 -0
  11. package/docs/agents/webmcp.md +153 -0
  12. package/docs/agents.md +355 -0
  13. package/docs/annotations.md +198 -0
  14. package/docs/api/changes.md +264 -0
  15. package/docs/api/components.md +245 -0
  16. package/docs/api/dnd-kit.md +265 -0
  17. package/docs/api/events.md +153 -0
  18. package/docs/api/primitives.md +218 -0
  19. package/docs/api/store.md +92 -0
  20. package/docs/api.md +57 -0
  21. package/docs/availability.md +576 -0
  22. package/docs/comparison.md +278 -0
  23. package/docs/concepts/anatomy.md +73 -0
  24. package/docs/concepts/events.md +163 -0
  25. package/docs/concepts/how-it-works.md +112 -0
  26. package/docs/concepts/state.md +244 -0
  27. package/docs/concepts/time.md +168 -0
  28. package/docs/customization.md +271 -0
  29. package/docs/frameworks.md +116 -0
  30. package/docs/guides/dnd-kit.md +333 -0
  31. package/docs/guides/google-calendar-sync.md +1246 -0
  32. package/docs/guides/google-calendar.md +367 -0
  33. package/docs/guides/motion.md +414 -0
  34. package/docs/guides/nextjs-app-router.md +630 -0
  35. package/docs/guides/nextjs.md +149 -0
  36. package/docs/guides/performance.md +103 -0
  37. package/docs/guides/tanstack-query.md +485 -0
  38. package/docs/ics/feed.md +484 -0
  39. package/docs/ics/import.md +183 -0
  40. package/docs/ics/reference.md +482 -0
  41. package/docs/ics.md +142 -0
  42. package/docs/index.md +149 -0
  43. package/docs/installation.md +209 -0
  44. package/docs/interactions.md +441 -0
  45. package/docs/llms.txt +99 -0
  46. package/docs/migrating-to-2.md +497 -0
  47. package/docs/quick-start.md +163 -0
  48. package/docs/recurrence/calendar.md +598 -0
  49. package/docs/recurrence/model.md +128 -0
  50. package/docs/recurrence/reference.md +547 -0
  51. package/docs/recurrence.md +122 -0
  52. package/docs/stylex.md +290 -0
  53. package/docs/temporal/daylight-saving-time.md +172 -0
  54. package/docs/temporal/month-grid.md +119 -0
  55. package/docs/temporal/reference.md +167 -0
  56. package/docs/temporal.md +105 -0
  57. package/docs/testing.md +600 -0
  58. package/docs/theme-builder.md +82 -0
  59. package/docs/theming.md +275 -0
  60. package/docs/undo-redo.md +347 -0
  61. package/docs/views/agenda.md +222 -0
  62. package/docs/views/custom-views.md +195 -0
  63. package/docs/views/month.md +110 -0
  64. package/docs/views/resource-columns.md +265 -0
  65. package/docs/views/resource-timeline.md +226 -0
  66. package/docs/views/scrolling.md +193 -0
  67. package/docs/views/week-and-day.md +258 -0
  68. package/docs/views/year.md +138 -0
  69. package/docs/views.md +69 -0
  70. package/package.json +42 -14
  71. package/skills/moltenship-time/SKILL.md +77 -0
  72. package/skills/moltenship-time/references/agent-ready.md +272 -0
  73. package/skills/moltenship-time/references/changes.md +188 -0
  74. package/skills/moltenship-time/references/compose.md +175 -0
  75. package/skills/moltenship-time/references/mistakes.md +100 -0
  76. package/skills/moltenship-time/references/solid.md +213 -0
  77. package/skills/moltenship-time/references/state.md +129 -0
  78. package/skills/moltenship-time/references/testing.md +176 -0
@@ -0,0 +1,484 @@
1
+ # Show an ICS feed
2
+
3
+ Parse a Google, Outlook or iCloud feed on the server and show its events in the calendar.
4
+
5
+ Source: https://time.molten.sh/docs/react/ics/feed
6
+
7
+ > Live example: see it at https://time.molten.sh/docs/react/ics/feed
8
+
9
+ These events come from an ICS feed, the iCalendar text that Google Calendar, Outlook and iCloud
10
+ publish. The feed was written for this week, parsed in your browser with `@moltenship/ics`, and
11
+ shown in your time zone. Each title says where its time came from: a New York time zone, an Outlook
12
+ zone name, UTC, a date, or a floating time with no zone at all. Open the source to compare.
13
+
14
+ This guide does the same in a Next.js app: the server fetches and parses the feed, and the browser
15
+ shows it. The [Next.js guide](../guides/nextjs.md) covers the rules for server rendering that apply
16
+ here too.
17
+
18
+ ## Install
19
+
20
+ The parser is a separate package. It reads iCalendar text into Temporal values and doesn't depend
21
+ on the calendar, so it works on its own too.
22
+
23
+ **pnpm**
24
+
25
+ ```bash
26
+ pnpm add @moltenship/ics
27
+ ```
28
+
29
+ **npm**
30
+
31
+ ```bash
32
+ npm install @moltenship/ics
33
+ ```
34
+
35
+ **yarn**
36
+
37
+ ```bash
38
+ yarn add @moltenship/ics
39
+ ```
40
+
41
+ **bun**
42
+
43
+ ```bash
44
+ bun add @moltenship/ics
45
+ ```
46
+
47
+ It needs `Temporal`, as the calendar does: Node.js 26 has it, and the browser may need the
48
+ [polyfill](../installation.md#temporal).
49
+
50
+ ## Fetch and parse on the server
51
+
52
+ A Server Component fetches the feed, parses it with `parseIcs`, and maps the events to plain JSON
53
+ for the client:
54
+
55
+ ```tsx title="page.tsx"
56
+ // app/team/page.tsx (a Server Component)
57
+ import { parseIcs } from "@moltenship/ics";
58
+ import { cacheLife } from "next/cache";
59
+ import { connection } from "next/server";
60
+ import { Suspense } from "react";
61
+
62
+ import { FeedCalendar } from "./feed-calendar";
63
+ import { toFeedEvents, type FeedEventJson } from "./feed-events";
64
+
65
+ const feedUrl = "https://calendar.example.com/team/basic.ics";
66
+
67
+ async function getFeedEvents(timeZone: string): Promise<readonly FeedEventJson[]> {
68
+ "use cache";
69
+ cacheLife("hours"); // fetch the feed again at most once an hour
70
+
71
+ const response = await fetch(feedUrl);
72
+ if (!response.ok) throw new Error(`The feed answered ${response.status}`);
73
+
74
+ const { calendars, issues } = parseIcs(await response.text());
75
+ for (const issue of issues) {
76
+ console.warn(`${feedUrl}, line ${issue.line ?? "?"}: ${issue.message}`);
77
+ }
78
+ return calendars.flatMap((calendar) => toFeedEvents(calendar, timeZone));
79
+ }
80
+
81
+ export default function TeamPage() {
82
+ return (
83
+ <Suspense fallback={<p>Loading the team calendar…</p>}>
84
+ <TeamFeed />
85
+ </Suspense>
86
+ );
87
+ }
88
+
89
+ async function TeamFeed() {
90
+ await connection(); // render on each request, for a fresh `now`
91
+
92
+ // The viewer's time zone, for example from their profile or a cookie.
93
+ const timeZone = "Europe/Berlin";
94
+ const events = await getFeedEvents(timeZone);
95
+
96
+ return (
97
+ <FeedCalendar events={events} now={Temporal.Now.instant().toString()} timeZone={timeZone} />
98
+ );
99
+ }
100
+ ```
101
+
102
+ - **Caching.** Feeds change slowly, and providers limit how often you fetch them. `"use cache"`
103
+ with `cacheLife("hours")` keeps the result for an hour. The time zone is an argument, so each
104
+ time zone gets its own entry. Without
105
+ [Cache Components](https://nextjs.org/docs/app/getting-started/caching), pass
106
+ `{ next: { revalidate: 3600 } }` to `fetch` instead.
107
+ - **Issues.** `parseIcs` doesn't throw on bad data. It keeps what it can and lists each problem in
108
+ `issues`, with its line. The page logs them; see [Issues](#issues) for more.
109
+ - **The current time.** `connection()` renders the calendar on each request, so `now` is today
110
+ rather than the day you built the app. That makes it request-time data, so it sits in a
111
+ `<Suspense>` boundary: the rest of the page still prerenders, and the build doesn't stop on it.
112
+
113
+ Temporal values can't cross from a Server Component to a Client Component, so `toFeedEvents` returns
114
+ ISO 8601 strings. The client turns them back into Temporal values:
115
+
116
+ ```tsx title="feed-calendar.tsx"
117
+ // app/team/feed-calendar.tsx
118
+ "use client";
119
+
120
+ import { createCalendar, defineEventAdapter } from "@moltenship/calendar";
121
+ import { useMemo } from "react";
122
+
123
+ import { CalendarToolbar } from "@/components/calendar/calendar-toolbar";
124
+ import type { CalendarEventColor } from "@/components/calendar/event-colors";
125
+ import { createWeekView } from "@/components/calendar/time-grid-view/time-grid-view";
126
+
127
+ import type { FeedEventJson } from "./feed-events";
128
+
129
+ export type FeedEvent = {
130
+ readonly id: string;
131
+ readonly title: string;
132
+ readonly color: CalendarEventColor;
133
+ } & (
134
+ | { readonly kind: "timed"; readonly start: Temporal.Instant; readonly end: Temporal.Instant }
135
+ | {
136
+ readonly kind: "all-day";
137
+ readonly start: Temporal.PlainDate;
138
+ readonly end: Temporal.PlainDate;
139
+ }
140
+ );
141
+
142
+ /** Turns the strings from the server back into Temporal values. */
143
+ export function fromFeedJson({ kind, start, end, ...event }: FeedEventJson): FeedEvent {
144
+ return kind === "timed"
145
+ ? { ...event, kind, start: Temporal.Instant.from(start), end: Temporal.Instant.from(end) }
146
+ : { ...event, kind, start: Temporal.PlainDate.from(start), end: Temporal.PlainDate.from(end) };
147
+ }
148
+
149
+ const Calendar = createCalendar<FeedEvent>()({
150
+ eventAdapter: defineEventAdapter<FeedEvent>()({
151
+ getId: (event) => event.id,
152
+ getTitle: (event) => event.title,
153
+ // A FeedEvent is already an interval: its kind, start and end.
154
+ getInterval: (event) => event,
155
+ getResourceIds: () => [],
156
+ }),
157
+ views: [createWeekView<FeedEvent>({ getEventColor: (event) => event.color })],
158
+ });
159
+
160
+ const weekRules = { firstDay: 1, minimalDays: 4, weekend: [6, 7] } as const;
161
+
162
+ interface FeedCalendarProps {
163
+ readonly events: readonly FeedEventJson[];
164
+ readonly now: string;
165
+ readonly timeZone: string;
166
+ }
167
+
168
+ export function FeedCalendar({ events, now, timeZone }: FeedCalendarProps) {
169
+ const feedEvents = useMemo(() => events.map(fromFeedJson), [events]);
170
+ const nowInstant = Temporal.Instant.from(now);
171
+
172
+ return (
173
+ <Calendar.Root
174
+ events={feedEvents}
175
+ now={nowInstant}
176
+ defaultAnchorDate={nowInstant.toZonedDateTimeISO(timeZone).toPlainDate()}
177
+ defaultTimeZone={timeZone}
178
+ locale="en-US"
179
+ weekRules={weekRules}
180
+ >
181
+ <Calendar.Frame className="flex h-[640px] flex-col rounded-xl border">
182
+ <CalendarToolbar calendar={Calendar} />
183
+ <Calendar.Viewport className="min-h-0 flex-1">
184
+ <Calendar.ActiveView />
185
+ </Calendar.Viewport>
186
+ </Calendar.Frame>
187
+ </Calendar.Root>
188
+ );
189
+ }
190
+ ```
191
+
192
+ ## Map ICS events to calendar events
193
+
194
+ ICS writes times in five ways, and the parser keeps them apart as `start.kind`. `toFeedEvent` turns
195
+ each into an event the calendar can show:
196
+
197
+ ```ts title="feed-events.ts"
198
+ // app/team/feed-events.ts
199
+ import { getEventEnd, type IcsCalendar, type IcsDateValue, type IcsEvent } from "@moltenship/ics";
200
+
201
+ import type { CalendarEventColor } from "@/components/calendar/event-colors";
202
+
203
+ /** A feed event as plain JSON, ready to pass from a Server Component to a Client Component. */
204
+ export interface FeedEventJson {
205
+ readonly id: string;
206
+ readonly title: string;
207
+ readonly color: CalendarEventColor;
208
+ readonly kind: "timed" | "all-day";
209
+ /** An instant, such as "2026-10-12T07:00:00Z", or a date for an all-day event. */
210
+ readonly start: string;
211
+ readonly end: string;
212
+ }
213
+
214
+ // The calendar needs an end after the start; ICS allows events that take no time.
215
+ const minimumLength = { minutes: 30 };
216
+
217
+ /** The zone for floating and unresolved times: the feed's X-WR-TIMEZONE, else the viewer's. */
218
+ export function feedTimeZone(calendar: IcsCalendar, viewerTimeZone: string): string {
219
+ return calendar.timeZone ?? viewerTimeZone;
220
+ }
221
+
222
+ function toInstant(value: IcsDateValue, timeZone: string): Temporal.Instant {
223
+ switch (value.kind) {
224
+ case "utc":
225
+ return value.instant;
226
+ case "zoned":
227
+ return value.zoned.toInstant();
228
+ case "date":
229
+ return value.date.toZonedDateTime(timeZone).toInstant();
230
+ case "floating":
231
+ case "unresolved":
232
+ return value.wallTime.toZonedDateTime(timeZone).toInstant();
233
+ }
234
+ }
235
+
236
+ /** One event for the calendar, or `undefined` for a cancelled one. */
237
+ export function toFeedEvent(event: IcsEvent, timeZone: string): FeedEventJson | undefined {
238
+ if (event.status === "CANCELLED") return undefined;
239
+
240
+ const end = getEventEnd(event); // DTEND, else DTSTART + DURATION, in the start's kind
241
+ let times: Pick<FeedEventJson, "kind" | "start" | "end">;
242
+ if (event.start.kind === "date") {
243
+ const start = event.start.date;
244
+ const endDate = end.kind === "date" ? end.date : start;
245
+ const isAfter = Temporal.PlainDate.compare(endDate, start) > 0;
246
+ times = {
247
+ kind: "all-day",
248
+ start: start.toString(),
249
+ end: (isAfter ? endDate : start.add({ days: 1 })).toString(),
250
+ };
251
+ } else {
252
+ const start = toInstant(event.start, timeZone);
253
+ // A DTEND in UTC or a time zone keeps its instant, even after a floating start.
254
+ const absoluteEnd = event.end?.kind === "utc" || event.end?.kind === "zoned";
255
+ const endInstant = toInstant(absoluteEnd ? event.end! : end, timeZone);
256
+ const isAfter = Temporal.Instant.compare(endInstant, start) > 0;
257
+ times = {
258
+ kind: "timed",
259
+ start: start.toString(),
260
+ end: (isAfter ? endInstant : start.add(minimumLength)).toString(),
261
+ };
262
+ }
263
+
264
+ return {
265
+ // An override (RECURRENCE-ID) shares its series' UID, so its start keeps the ID unique.
266
+ id: event.recurrenceId === undefined ? event.uid : `${event.uid}/${times.start}`,
267
+ title: event.summary ?? "Busy",
268
+ // Free time (TRANSP:TRANSPARENT) and tentative events are gray, the rest blue.
269
+ color: event.transparency === "TRANSPARENT" || event.status === "TENTATIVE" ? "gray" : "blue",
270
+ ...times,
271
+ };
272
+ }
273
+
274
+ /** Every event of a parsed calendar, ready for the client. */
275
+ export function toFeedEvents(
276
+ calendar: IcsCalendar,
277
+ viewerTimeZone: string,
278
+ ): readonly FeedEventJson[] {
279
+ const timeZone = feedTimeZone(calendar, viewerTimeZone);
280
+ return calendar.events.flatMap((event) => toFeedEvent(event, timeZone) ?? []);
281
+ }
282
+ ```
283
+
284
+ | `kind` | Written as | Shown as |
285
+ | ------------ | ------------------------------ | ----------------------------------------------------- |
286
+ | `utc` | `DTSTART:20261012T090000Z` | A timed event at that instant |
287
+ | `zoned` | `DTSTART;TZID=Europe/Berlin:…` | A timed event at `zoned.toInstant()` |
288
+ | `date` | `DTSTART;VALUE=DATE:20261012` | An all-day event |
289
+ | `floating` | `DTSTART:20261012T090000` | A timed event at that wall time, in a zone you choose |
290
+ | `unresolved` | `DTSTART;TZID=Our Office:…` | The same as floating |
291
+
292
+ - **Floating times** have a clock time and no zone. A feed's `X-WR-TIMEZONE`, which Google adds,
293
+ says which zone the publisher meant, and the parser gives it to you as `calendar.timeZone`.
294
+ `feedTimeZone` uses it, and the viewer's time zone when the feed has none. The preview's feed has
295
+ none, so its focus time shows at the same clock time wherever you are.
296
+ - **The end.** `getEventEnd` returns DTEND, else DTSTART plus DURATION, else the RFC's default: the
297
+ next day for a date, the start itself for a time. It's always the same kind as the start.
298
+ - **No length.** ICS lets an event end when it starts, but a calendar event's end must come after
299
+ its start, so those events show as half an hour long, or one day for a date.
300
+ - **Cancelled events.** Feeds keep a cancelled event, with `STATUS:CANCELLED`, so that subscribers
301
+ can remove it. `toFeedEvent` skips it.
302
+ - **Colors.** Events marked free (`TRANSP:TRANSPARENT`) or tentative are gray, the rest blue. Change
303
+ the rule to suit your app, or color each feed differently.
304
+
305
+ ## Recurring events
306
+
307
+ `@moltenship/ics` reads recurrence but doesn't expand it. A series is one event with its rule in
308
+ `recurrenceRule`, the occurrences it removes in `exceptionDates`, and extra ones in
309
+ `recurrenceDates`. A change to one occurrence is a separate event with the series' UID and a
310
+ `recurrenceId` that names the occurrence it replaces. So the mapping above shows:
311
+
312
+ - **A recurring event once,** at its DTSTART, which is the first occurrence.
313
+ - **A changed occurrence as its own event,** at its new time.
314
+
315
+ [`@moltenship/calendar-recurrence`](../recurrence/reference.md) expands them. `recurringEventsFromIcs`
316
+ groups a calendar's events into series masters, overrides and one-off events, and an expander turns
317
+ them into the occurrences for the dates on screen. Those dates are known in the browser, so the
318
+ server sends the feed's text, a string, instead of mapped events. In the page above, have the
319
+ cached function return `await response.text()`, and pass it as `text`:
320
+
321
+ ```tsx title="recurring-feed-calendar.tsx"
322
+ // app/team/recurring-feed-calendar.tsx
323
+ "use client";
324
+
325
+ import { createCalendar, weekRange, type PlainDateInterval } from "@moltenship/calendar";
326
+ import {
327
+ createCanonicalRecurrenceAdapter,
328
+ createOccurrenceAdapter,
329
+ createOccurrenceExpander,
330
+ recurringEventsFromIcs,
331
+ type RecurrenceOccurrence,
332
+ type RecurringCalendarEvent,
333
+ } from "@moltenship/calendar-recurrence";
334
+ import { parseIcs, type IcsEvent } from "@moltenship/ics";
335
+ import { useMemo, useState } from "react";
336
+
337
+ import { CalendarToolbar } from "@/components/calendar/calendar-toolbar";
338
+ import { createWeekView } from "@/components/calendar/time-grid-view/time-grid-view";
339
+
340
+ type FeedEvent = RecurringCalendarEvent<IcsEvent>;
341
+ type FeedOccurrence = RecurrenceOccurrence<FeedEvent, string>;
342
+
343
+ const adapters = createCanonicalRecurrenceAdapter<IcsEvent>();
344
+
345
+ const Calendar = createCalendar<FeedOccurrence>()({
346
+ eventAdapter: createOccurrenceAdapter(adapters.event),
347
+ views: [createWeekView<FeedOccurrence>()],
348
+ });
349
+
350
+ /** The feed's VEVENTs as series masters, overrides and one-off events. */
351
+ export function readRecurringFeed(text: string): readonly FeedEvent[] {
352
+ const { calendars } = parseIcs(text);
353
+ return calendars.flatMap((calendar) => {
354
+ // UTC times on all-day and floating series, such as an UNTIL, read in the feed's zone.
355
+ const { events, issues } = recurringEventsFromIcs(calendar.events, {
356
+ timeZone: calendar.timeZone,
357
+ });
358
+ for (const issue of issues) console.warn(`${issue.event.uid}: ${issue.message}`);
359
+ return events;
360
+ });
361
+ }
362
+
363
+ const weekRules = { firstDay: 1, minimalDays: 4, weekend: [6, 7] } as const;
364
+
365
+ interface RecurringFeedCalendarProps {
366
+ /** The feed's ICS text, which the server fetched. */
367
+ readonly text: string;
368
+ readonly now: string;
369
+ readonly timeZone: string;
370
+ }
371
+
372
+ export function RecurringFeedCalendar({ text, now, timeZone }: RecurringFeedCalendarProps) {
373
+ const nowInstant = Temporal.Instant.from(now);
374
+ const today = nowInstant.toZonedDateTimeISO(timeZone).toPlainDate();
375
+ const events = useMemo(() => readRecurringFeed(text), [text]);
376
+ const [expander] = useState(() => createOccurrenceExpander(adapters));
377
+ const [range, setRange] = useState<PlainDateInterval>(() =>
378
+ weekRange(today, { weekStartsOn: weekRules.firstDay }),
379
+ );
380
+ const { occurrences } = useMemo(
381
+ () => expander.expand(events, { range, timeZone }),
382
+ [expander, events, range, timeZone],
383
+ );
384
+
385
+ return (
386
+ <Calendar.Root
387
+ events={occurrences}
388
+ onVisibleRangeChange={({ loadRange }) => setRange(loadRange)}
389
+ now={nowInstant}
390
+ defaultAnchorDate={today}
391
+ defaultTimeZone={timeZone}
392
+ locale="en-US"
393
+ weekRules={weekRules}
394
+ >
395
+ <Calendar.Frame className="flex h-[640px] flex-col rounded-xl border">
396
+ <CalendarToolbar calendar={Calendar} />
397
+ <Calendar.Viewport className="min-h-0 flex-1">
398
+ <Calendar.ActiveView />
399
+ </Calendar.Viewport>
400
+ </Calendar.Frame>
401
+ </Calendar.Root>
402
+ );
403
+ }
404
+ ```
405
+
406
+ - **IDs.** Masters and one-off events keep their UID. An override gets the ID of the occurrence it
407
+ replaces, such as `standup@example.com::2026-10-20T07:00:00Z`, so it never collides with its
408
+ series.
409
+ - **Time zones.** A zoned series repeats on its zone's wall clock, so a 09:00 meeting stays at 09:00
410
+ across daylight saving time. Floating and all-day series stay floating and all-day, and the
411
+ calendar shows them that way. Pass the feed's `X-WR-TIMEZONE` as `timeZone`, so UTC dates on them,
412
+ such as an UNTIL, keep the feed's dates. Feeds without one, such as Exchange's, write the UNTIL of
413
+ an all-day series at the owner's midnight in UTC; without `timeZone`, the bridge reads such dates
414
+ in the zone most of the feed's TZIDs name, so the last day isn't lost. Pass `timeZone: "UTC"` to
415
+ read them in UTC, as the bridge did before.
416
+ - **Daylight saving time.** A DTSTART in the hour a zone skips moves forward by the gap. A series
417
+ keeps the length written up to DTEND: a weekly Sydney 02:30–03:30 meeting from the night clocks
418
+ go forward shows 03:30–04:30 that night, and 02:30–03:30 on later weeks.
419
+ - **Outlook's all-day events.** Older Outlook and Exchange exports write an all-day event from
420
+ midnight to midnight in a zone, with `X-MICROSOFT-CDO-ALLDAYEVENT:TRUE`. The bridge reads it as
421
+ all-day on the dates written, and its series' midnight dates as dates.
422
+ - **This and future.** Apple writes a change to an occurrence and every later one as an override
423
+ with `RANGE=THISANDFUTURE`. The bridge splits the series there, as Google Calendar does: the new
424
+ part starts at the override, with its title, and the rest of the rule moved the same way. Its
425
+ occurrences take the new part's IDs.
426
+ - **Cancelled events.** A cancelled override, with `STATUS:CANCELLED`, hides its occurrence. A
427
+ cancelled master is left out with its overrides.
428
+ - **Issues.** `recurringEventsFromIcs` reports what it changed or left out, such as an RDATE with a
429
+ date where the series has times, or a `RANGE=THISANDFUTURE` change the rule can't follow, which
430
+ then replaces one occurrence. The expander reports its own issues, such as a rule it can't
431
+ expand.
432
+
433
+ To expand on the server instead, call the expander there for a range you choose, and map each
434
+ occurrence's `interval` to JSON as `toFeedEvent` maps an event's times. The calendar then shows only
435
+ that range. [Show and edit recurring events](../recurrence/calendar.md) covers expansion in
436
+ more detail.
437
+
438
+ ## Time zones
439
+
440
+ A TZID is a name the file chooses, and the parser maps it to a time zone Temporal knows: an IANA
441
+ name such as `America/New_York`, a Windows or Outlook name such as `W. Europe Standard Time`, the
442
+ file's own VTIMEZONE, and a few more. A TZID that matches none of them isn't guessed. The time
443
+ stays `unresolved`, with its wall time and TZID, and `issues` gets an `unknown-time-zone` warning.
444
+ The mapping above then reads it in the zone you chose, like a floating time.
445
+
446
+ If you know what a feed's own names mean, say so with `resolveTimeZone`. The parser asks it first;
447
+ `undefined` falls through to the built-in rules:
448
+
449
+ ```ts
450
+ const { calendars, issues } = parseIcs(text, {
451
+ resolveTimeZone: (tzid) => (tzid === "Our Office" ? "Europe/Lisbon" : undefined),
452
+ });
453
+ ```
454
+
455
+ The [API reference](./reference.md) lists every rule, in order.
456
+
457
+ ## Issues
458
+
459
+ Each issue has a `severity`, a `code`, a `message` and, when it comes from one, a `line`. An error
460
+ drops what it concerns, such as an event without DTSTART. A warning keeps a best-effort value.
461
+
462
+ Feeds you subscribe to break the rules more often than you'd think, so keep showing what parsed.
463
+ Log the issues, as the page does, and if people should know, pass a count of the errors to the
464
+ client and show it beside the calendar, such as "2 events couldn't be read".
465
+
466
+ Files that people upload are different: tell them what's wrong instead. `strict: true` throws an
467
+ `IcsParseError` with the errors in `issues`:
468
+
469
+ ```ts
470
+ import { IcsParseError, parseIcs } from "@moltenship/ics";
471
+
472
+ function readUpload(text: string) {
473
+ try {
474
+ return { calendars: parseIcs(text, { strict: true }).calendars };
475
+ } catch (error) {
476
+ if (!(error instanceof IcsParseError)) throw error;
477
+ return { errors: error.issues.map((issue) => `Line ${issue.line ?? "?"}: ${issue.message}`) };
478
+ }
479
+ }
480
+ ```
481
+
482
+ A parser from `createIcsParser` is also a [Standard Schema](https://standardschema.dev), so a form
483
+ or router library that takes one can validate the upload. The [API reference](./reference.md) covers
484
+ both.
@@ -0,0 +1,183 @@
1
+ # Read an .ics file
2
+
3
+ Parse an iCalendar file a person picks or uploads, report its problems with their lines, and turn its dates into instants.
4
+
5
+ Source: https://time.molten.sh/docs/react/ics/import
6
+
7
+ A person exports a calendar from Google Calendar or Outlook and gives your app the `.ics` file.
8
+ This page reads it in the browser, tells the person what the file got wrong, and checks an upload
9
+ on a server. Nothing here needs the calendar or a UI framework.
10
+
11
+ ## Read the file
12
+
13
+ `readIcsFile` takes the `File` from an `<input type="file">` or a drop, and the viewer's time
14
+ zone. It returns the events with their times as instants, and a line for each problem:
15
+
16
+ ```ts title="read-ics-file.ts"
17
+ import { getEventEnd, parseIcs, type IcsDateValue, type IcsIssue } from "@moltenship/ics";
18
+
19
+ export interface ImportedEvent {
20
+ readonly id: string;
21
+ readonly title: string;
22
+ readonly allDay: boolean;
23
+ readonly start: Temporal.Instant;
24
+ readonly end: Temporal.Instant;
25
+ }
26
+
27
+ export interface ImportResult {
28
+ readonly events: readonly ImportedEvent[];
29
+ /** What to tell the person about the file, one line per problem. */
30
+ readonly problems: readonly string[];
31
+ }
32
+
33
+ export async function readIcsFile(file: File, viewerTimeZone: string): Promise<ImportResult> {
34
+ // `File.text()` decodes the bytes as UTF-8, the encoding iCalendar files use.
35
+ const { calendars, issues } = parseIcs(await file.text());
36
+
37
+ const events = calendars.flatMap((calendar) => {
38
+ // Times without a zone are read in the file's X-WR-TIMEZONE, else in the viewer's zone.
39
+ const timeZone = calendar.timeZone ?? viewerTimeZone;
40
+ return calendar.events.map((event) => ({
41
+ id: event.uid,
42
+ title: event.summary ?? "Untitled",
43
+ allDay: event.start.kind === "date",
44
+ start: toInstant(event.start, timeZone),
45
+ end: toInstant(getEventEnd(event), timeZone),
46
+ }));
47
+ });
48
+
49
+ return { events, problems: issues.filter(isError).map(describe) };
50
+ }
51
+ ```
52
+
53
+ `parseIcs` takes a string, not bytes. `File.text()` decodes the file as UTF-8, which is the
54
+ encoding RFC 5545 names as the default. Read a `Response` with `response.text()`, and other bytes
55
+ with `new TextDecoder().decode(bytes)`.
56
+
57
+ A file can hold more than one VCALENDAR, so the function reads every calendar in `calendars`.
58
+
59
+ ## Turn dates into instants
60
+
61
+ An ICS start is one of five shapes, and `kind` says which. Two of them are instants already. The
62
+ other three need a time zone, which you choose:
63
+
64
+ ```ts title="read-ics-file.ts"
65
+ function toInstant(value: IcsDateValue, timeZone: string): Temporal.Instant {
66
+ switch (value.kind) {
67
+ case "utc":
68
+ return value.instant;
69
+ case "zoned":
70
+ return value.zoned.toInstant();
71
+ case "date":
72
+ // An all-day event starts when its date starts in the chosen zone.
73
+ return value.date.toZonedDateTime(timeZone).toInstant();
74
+ case "floating":
75
+ case "unresolved":
76
+ return value.wallTime.toZonedDateTime(timeZone).toInstant();
77
+ }
78
+ }
79
+ ```
80
+
81
+ | `kind` | The file wrote | How the function reads it |
82
+ | ------------ | ------------------------------------- | -------------------------------------------- |
83
+ | `utc` | A time in UTC, ending in `Z` | The instant itself |
84
+ | `zoned` | A time with a `TZID` the parser knows | The instant in that zone |
85
+ | `date` | A date, for an all-day event | The start of that date in the zone you chose |
86
+ | `floating` | A time with no zone | That wall time in the zone you chose |
87
+ | `unresolved` | A time with a `TZID` nobody knows | That wall time in the zone you chose |
88
+
89
+ The parser never falls back to the host's time zone, so the choice is in your code. This function
90
+ uses the calendar's `X-WR-TIMEZONE`, which Google Calendar writes, and the viewer's zone when the
91
+ file has none. [Time zones](./reference.md#time-zones) lists how a `TZID` is resolved,
92
+ Outlook's Windows names included.
93
+
94
+ `getEventEnd` returns the end in the start's kind: the file's `DTEND`, or the start plus
95
+ `DURATION`. An event with neither ends the next day when it's all-day, and when it starts when it's
96
+ timed, so give such an event a length of your own before you show it.
97
+
98
+ An all-day event keeps its date in `event.start.date`. Keep that `Temporal.PlainDate` instead of
99
+ an instant if your app shows all-day events on a date, as the calendar does.
100
+
101
+ ## Tell the person what went wrong
102
+
103
+ The parser is lenient. It keeps every event it can read and lists what it couldn't in `issues`. An
104
+ issue with the severity `"error"` dropped a value or a whole component, and one with `"warning"`
105
+ kept a value read leniently. Each has the line it came from, when it came from one:
106
+
107
+ ```ts title="read-ics-file.ts"
108
+ function isError(issue: IcsIssue): boolean {
109
+ return issue.severity === "error";
110
+ }
111
+
112
+ function describe(issue: IcsIssue): string {
113
+ return issue.line === undefined ? issue.message : `Line ${issue.line}: ${issue.message}`;
114
+ }
115
+ ```
116
+
117
+ For a file whose second event has no `DTSTART`, `problems` holds one line, and `events` holds the
118
+ other events:
119
+
120
+ ```text
121
+ Line 9: VEVENT has no DTSTART; skipped
122
+ ```
123
+
124
+ [Issues and strict mode](./reference.md#issues-and-strict-mode) lists every code.
125
+
126
+ ## Refuse a file with errors
127
+
128
+ To import all of a file or none of it, parse with `strict: true`. The parser then throws an
129
+ `IcsParseError` when the text has an error. Its `message` is the first error's, with a count of the
130
+ others, and its `issues` lists them all. Warnings never throw:
131
+
132
+ ```ts title="read-strictly.ts"
133
+ import { IcsParseError } from "@moltenship/ics";
134
+
135
+ /** The file's calendars, or the reason the file is refused. */
136
+ export function readStrictly(text: string) {
137
+ try {
138
+ return { ok: true as const, calendars: parseIcs(text, { strict: true }).calendars };
139
+ } catch (error) {
140
+ if (!(error instanceof IcsParseError)) throw error;
141
+ return { ok: false as const, reason: error.message, issues: error.issues };
142
+ }
143
+ }
144
+ ```
145
+
146
+ Text without a VCALENDAR is an error too, so this also refuses a file that isn't a calendar.
147
+
148
+ ## Check an upload on a server
149
+
150
+ A parser is a [Standard Schema](https://standardschema.dev): its `validate` fails with the errors,
151
+ or succeeds with the parse result. A value that isn't a string fails as well, so a form without a
152
+ file gets the same answer as a bad file. This handler runs wherever `Request` and `Response` do:
153
+
154
+ ```ts title="route.ts"
155
+ import { createIcsParser } from "@moltenship/ics";
156
+
157
+ const parser = createIcsParser();
158
+
159
+ /** A route handler for a form with an `<input type="file" name="calendar">`. */
160
+ export async function POST(request: Request): Promise<Response> {
161
+ const file = (await request.formData()).get("calendar");
162
+ const body = file instanceof File ? await file.text() : undefined;
163
+
164
+ // A parser is a Standard Schema: it fails with the errors, or succeeds with the result.
165
+ const result = await parser["~standard"].validate(body);
166
+ if (result.issues) {
167
+ return Response.json({ errors: result.issues.map((issue) => issue.message) }, { status: 400 });
168
+ }
169
+
170
+ const events = result.value.calendars.flatMap((calendar) => calendar.events);
171
+ return Response.json({ imported: events.length });
172
+ }
173
+ ```
174
+
175
+ Anything that takes a Standard Schema takes the parser the same way, such as a form library or a
176
+ router's body validation.
177
+
178
+ ## Recurring events
179
+
180
+ A recurring event arrives as one event with a `recurrenceRule`, and each changed occurrence as
181
+ another event with the same `uid` and a `recurrenceId`. So `uid` alone doesn't identify an event
182
+ in a file with series. [`@moltenship/calendar-recurrence`](../recurrence.md) groups such events
183
+ into series with `recurringEventsFromIcs` and lists their occurrences for a range of dates.