@wtfalch/calendar 0.1.0 → 0.2.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.
@@ -0,0 +1,198 @@
1
+ /**
2
+ * The pure slot search behind `CalendarClient.findTime` (issue #13). No
3
+ * network and no server-shaped types here — just merging busy periods and
4
+ * walking the gaps between them, so the search itself is testable without a
5
+ * connection at all.
6
+ */
7
+ import { parseDurationMs } from "./wire.js";
8
+ /** 09:00-17:00. Every busy period already arrives in UTC (`wire.ts`'s
9
+ * `availabilityFromWire`), so this is the fallback for `workingHours:
10
+ * true` and for a principal a per-attendee map (wtfalch/calendar#31)
11
+ * never names -- the same uniform bound the package used for everyone
12
+ * before that option existed (issue #13's original Decision). */
13
+ const WORKING_HOURS_START_UTC = 9;
14
+ const WORKING_HOURS_END_UTC = 17;
15
+ const UTC = { timeZone: 'UTC' };
16
+ /** Every *known* principal's busy periods, merged into one sorted,
17
+ * overlap-free timeline. An unknown principal contributes nothing, on
18
+ * purpose: this package never treats "cannot be seen" as a constraint to
19
+ * book around (`AvailabilityResult`'s own doc comment). */
20
+ function mergedBusy(answers) {
21
+ const raw = [];
22
+ for (const answer of answers.values()) {
23
+ if (answer.kind !== 'known')
24
+ continue;
25
+ for (const period of answer.periods) {
26
+ raw.push({ start: new Date(period.start).getTime(), end: new Date(period.end).getTime() });
27
+ }
28
+ }
29
+ raw.sort((a, b) => a.start - b.start);
30
+ const merged = [];
31
+ for (const interval of raw) {
32
+ const last = merged[merged.length - 1];
33
+ if (last && interval.start <= last.end)
34
+ last.end = Math.max(last.end, interval.end);
35
+ else
36
+ merged.push({ ...interval });
37
+ }
38
+ return merged;
39
+ }
40
+ /**
41
+ * The UTC instant of `hour:00` on the civil date `(year, month, day)` as
42
+ * read in `timeZone` (wtfalch/calendar#31). Guess the instant as if
43
+ * `timeZone` were UTC, read what `timeZone` actually shows for that guess,
44
+ * and correct by the difference — one pass, no timezone database beyond
45
+ * what `Intl.DateTimeFormat` already carries. Exact only up to a DST
46
+ * transition landing on this exact hour, which is the same limitation
47
+ * every offset-corrected-guess conversion has without a full tz-rules
48
+ * engine; a wrong hour on the one or two days a year that happens is a far
49
+ * smaller failure than the fixed-UTC window this option replaces.
50
+ */
51
+ function zonedHourToUtcMs(year, month, day, hour, timeZone) {
52
+ const guessMs = Date.UTC(year, month - 1, day, hour, 0, 0);
53
+ const parts = new Intl.DateTimeFormat('en-US', {
54
+ timeZone,
55
+ hourCycle: 'h23',
56
+ year: 'numeric',
57
+ month: '2-digit',
58
+ day: '2-digit',
59
+ hour: '2-digit',
60
+ minute: '2-digit',
61
+ second: '2-digit',
62
+ }).formatToParts(new Date(guessMs));
63
+ const get = (type) => Number(parts.find((part) => part.type === type)?.value ?? 0);
64
+ const asIfUtc = Date.UTC(get('year'), get('month') - 1, get('day'), get('hour'), get('minute'));
65
+ return guessMs - (asIfUtc - guessMs);
66
+ }
67
+ /** One principal's own working-day windows, one per civil day of theirs
68
+ * that overlaps `[rangeStart, rangeEnd)` -- walked by *their* calendar
69
+ * dates in `hours.timeZone`, not UTC's, so a zone far from UTC still gets
70
+ * its own correctly-placed window rather than one sliced by a UTC
71
+ * midnight that means nothing to that principal (wtfalch/calendar#31). */
72
+ function dailyWindows(rangeStart, rangeEnd, hours) {
73
+ const startHour = hours.startHour ?? WORKING_HOURS_START_UTC;
74
+ const endHour = hours.endHour ?? WORKING_HOURS_END_UTC;
75
+ const windows = [];
76
+ const civil = new Intl.DateTimeFormat('en-US', {
77
+ timeZone: hours.timeZone,
78
+ year: 'numeric',
79
+ month: '2-digit',
80
+ day: '2-digit',
81
+ }).formatToParts(new Date(rangeStart));
82
+ const get = (type) => Number(civil.find((part) => part.type === type)?.value ?? 0);
83
+ // Anchored as a UTC-noon instant per civil day, purely to step the
84
+ // calendar forward one day at a time with `setUTCDate` -- never read as
85
+ // a real instant itself.
86
+ const day = new Date(Date.UTC(get('year'), get('month') - 1, get('day'), 12));
87
+ // A year of days is far more than any sane `findTime` range asks for;
88
+ // it only guards a caller-supplied range from looping forever.
89
+ for (let i = 0; i < 366; i++) {
90
+ const start = zonedHourToUtcMs(day.getUTCFullYear(), day.getUTCMonth() + 1, day.getUTCDate(), startHour, hours.timeZone);
91
+ const end = zonedHourToUtcMs(day.getUTCFullYear(), day.getUTCMonth() + 1, day.getUTCDate(), endHour, hours.timeZone);
92
+ if (start >= rangeEnd)
93
+ break;
94
+ if (start < end && end > rangeStart) {
95
+ windows.push({ start: Math.max(start, rangeStart), end: Math.min(end, rangeEnd) });
96
+ }
97
+ day.setUTCDate(day.getUTCDate() + 1);
98
+ }
99
+ return windows;
100
+ }
101
+ /** The time covered by both `a` and `b` -- both already sorted and
102
+ * disjoint, so one sweep suffices. Used to fold one more principal's own
103
+ * working-day windows into the running candidate set: a slot must fall
104
+ * inside *every* named principal's own working day, not just one shared
105
+ * window (wtfalch/calendar#31). */
106
+ function intersect(a, b) {
107
+ const out = [];
108
+ let i = 0;
109
+ let j = 0;
110
+ while (i < a.length && j < b.length) {
111
+ const ai = a[i];
112
+ const bj = b[j];
113
+ if (!ai || !bj)
114
+ break;
115
+ const start = Math.max(ai.start, bj.start);
116
+ const end = Math.min(ai.end, bj.end);
117
+ if (start < end)
118
+ out.push({ start, end });
119
+ if (ai.end < bj.end)
120
+ i += 1;
121
+ else
122
+ j += 1;
123
+ }
124
+ return out;
125
+ }
126
+ /**
127
+ * `range`, split into candidate windows. `workingHours`:
128
+ * - `false`/`undefined`: the whole range, unsplit.
129
+ * - `true`: one uniform 09:00-17:00 UTC window per UTC day (issue #13's
130
+ * original behaviour, kept for a caller with no per-principal data).
131
+ * - a per-principal map: the intersection of every named principal's own
132
+ * working day, each in their own zone and hours -- a principal in
133
+ * `principalIds` but absent from the map falls back to the uniform
134
+ * 09:00-17:00 UTC window, same as `true` (wtfalch/calendar#31).
135
+ */
136
+ function candidateWindows(range, workingHours, principalIds) {
137
+ const rangeStart = new Date(range.after).getTime();
138
+ const rangeEnd = new Date(range.before).getTime();
139
+ if (rangeStart >= rangeEnd)
140
+ return [];
141
+ if (workingHours === false)
142
+ return [{ start: rangeStart, end: rangeEnd }];
143
+ if (workingHours === true)
144
+ return dailyWindows(rangeStart, rangeEnd, UTC);
145
+ let windows = [{ start: rangeStart, end: rangeEnd }];
146
+ for (const principalId of principalIds) {
147
+ const hours = workingHours.get(principalId) ?? UTC;
148
+ windows = intersect(windows, dailyWindows(rangeStart, rangeEnd, hours));
149
+ if (windows.length === 0)
150
+ break;
151
+ }
152
+ return windows;
153
+ }
154
+ /** One free slot per gap that fits `durationMs` — the earliest-starting fit
155
+ * in that gap, not every possible start inside it. `findTime` names where
156
+ * to look first; a start-time granularity nobody asked for would be an
157
+ * option this ticket does not need (issue #13 Decision). */
158
+ function slotsIn(window, busy, durationMs) {
159
+ const slots = [];
160
+ let cursor = window.start;
161
+ for (const period of busy) {
162
+ if (period.end <= cursor)
163
+ continue;
164
+ if (period.start >= window.end)
165
+ break;
166
+ if (period.start - cursor >= durationMs) {
167
+ slots.push({
168
+ after: new Date(cursor).toISOString(),
169
+ before: new Date(cursor + durationMs).toISOString(),
170
+ });
171
+ }
172
+ cursor = Math.max(cursor, period.end);
173
+ }
174
+ if (window.end - cursor >= durationMs) {
175
+ slots.push({
176
+ after: new Date(cursor).toISOString(),
177
+ before: new Date(cursor + durationMs).toISOString(),
178
+ });
179
+ }
180
+ return slots;
181
+ }
182
+ /** Every slot at least `duration` long where every *known* principal in
183
+ * `answers` is free. An unparseable `duration` (`wire.ts`'s
184
+ * `parseDurationMs` returning `null`) answers no slots rather than
185
+ * throwing — the same "do not crash a whole read over one bad value"
186
+ * discipline `availabilityFromWire` already follows. `principalIds` is
187
+ * only consulted when `workingHours` is a per-principal map, to know which
188
+ * principals besides `answers`' own keys (an unknown principal still gets
189
+ * its own working day considered, even with no busy periods to merge in)
190
+ * need one (wtfalch/calendar#31). */
191
+ export function findFreeSlots(answers, range, duration, workingHours, principalIds = [...answers.keys()]) {
192
+ const durationMs = parseDurationMs(duration);
193
+ if (!durationMs)
194
+ return [];
195
+ const busy = mergedBusy(answers);
196
+ const windows = candidateWindows(range, workingHours, principalIds);
197
+ return windows.flatMap((window) => slotsIn(window, busy, durationMs));
198
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Export a `CalendarEvent` (or several) as an RFC 5545 `.ics` document
3
+ * (wtfalch/calendar#28). Read-only feeds and `.ics` import are the other
4
+ * half of this gap, tracked separately (agora#159,
5
+ * https://github.com/wtfalch/agora/issues/159) and deferred with a named
6
+ * home (`PRODUCT.md`); this file is export only.
7
+ *
8
+ * **Every date-time is written in UTC (`Z`-suffixed), naively.** `start` is
9
+ * a local date-time with no offset, and `timeZone` says which zone it is
10
+ * local to -- but this package already treats every `start` as if it were
11
+ * UTC for its own display arithmetic (`EventDetail.tsx`'s `formatWhen`,
12
+ * `Calendar.tsx`'s grid rendering both do `new Date(`${event.start}Z`)`).
13
+ * Doing anything more accurate here -- resolving a named zone's real UTC
14
+ * offset -- would make this file the one place in the package that treats
15
+ * `timeZone` differently from everywhere else, for an event whose zone is
16
+ * "UTC" or unset in every fixture and every sample this package ships.
17
+ * `RecurrenceRule.until` shares the same treatment, which is also what RFC
18
+ * 5545 §3.3.10 requires: `UNTIL` must carry the same value type (UTC or
19
+ * not) as `DTSTART`.
20
+ *
21
+ * **`rscale`/`skip` (RFC 8984 §3.3, non-Gregorian calendars) have no RFC
22
+ * 5545 `RRULE` equivalent** and are silently omitted -- there is no
23
+ * standard part to write them into. Every other `CalendarRecurrenceRule`
24
+ * part round-trips (wtfalch/calendar#27's own `byDay`/`byMonthDay`/`byMonth`/
25
+ * `bySetPosition`/`firstDayOfWeek`/... included).
26
+ *
27
+ * **`virtualLocations` and `alerts` are not carried into the export.**
28
+ * Neither RFC 5545 property (`VALARM` for alerts; nothing standard for a
29
+ * join link distinct from `LOCATION`) was part of this ticket's evidence
30
+ * (`EventDetail.tsx` has no export control at all, not "an export control
31
+ * that drops one field"), so adding them is left to a later ticket.
32
+ */
33
+ import type { CalendarEvent } from './types.ts';
34
+ export type IcsExportOptions = {
35
+ /** The `DTSTAMP` moment. Injectable so a caller (or a test) does not have
36
+ * to accept the real wall clock, mirroring `EventEditor`'s/`Calendar`'s
37
+ * own `now` prop. Defaults to `new Date()`. */
38
+ now?: Date;
39
+ };
40
+ /** One or more events as a single RFC 5545 `.ics` document (a `VCALENDAR`
41
+ * wrapping one `VEVENT` per event) -- CRLF line endings and folding
42
+ * included, so the string this returns is ready to write to a file or hand
43
+ * to a `Blob` exactly as is. */
44
+ export declare function eventsToIcs(events: readonly CalendarEvent[], options?: IcsExportOptions): string;
45
+ /** A single event's own `.ics` document -- `EventDetail`'s "Download .ics"
46
+ * control (wtfalch/calendar#28) is this, one event at a time. */
47
+ export declare function eventToIcs(event: CalendarEvent, options?: IcsExportOptions): string;
@@ -0,0 +1,247 @@
1
+ /**
2
+ * Export a `CalendarEvent` (or several) as an RFC 5545 `.ics` document
3
+ * (wtfalch/calendar#28). Read-only feeds and `.ics` import are the other
4
+ * half of this gap, tracked separately (agora#159,
5
+ * https://github.com/wtfalch/agora/issues/159) and deferred with a named
6
+ * home (`PRODUCT.md`); this file is export only.
7
+ *
8
+ * **Every date-time is written in UTC (`Z`-suffixed), naively.** `start` is
9
+ * a local date-time with no offset, and `timeZone` says which zone it is
10
+ * local to -- but this package already treats every `start` as if it were
11
+ * UTC for its own display arithmetic (`EventDetail.tsx`'s `formatWhen`,
12
+ * `Calendar.tsx`'s grid rendering both do `new Date(`${event.start}Z`)`).
13
+ * Doing anything more accurate here -- resolving a named zone's real UTC
14
+ * offset -- would make this file the one place in the package that treats
15
+ * `timeZone` differently from everywhere else, for an event whose zone is
16
+ * "UTC" or unset in every fixture and every sample this package ships.
17
+ * `RecurrenceRule.until` shares the same treatment, which is also what RFC
18
+ * 5545 §3.3.10 requires: `UNTIL` must carry the same value type (UTC or
19
+ * not) as `DTSTART`.
20
+ *
21
+ * **`rscale`/`skip` (RFC 8984 §3.3, non-Gregorian calendars) have no RFC
22
+ * 5545 `RRULE` equivalent** and are silently omitted -- there is no
23
+ * standard part to write them into. Every other `CalendarRecurrenceRule`
24
+ * part round-trips (wtfalch/calendar#27's own `byDay`/`byMonthDay`/`byMonth`/
25
+ * `bySetPosition`/`firstDayOfWeek`/... included).
26
+ *
27
+ * **`virtualLocations` and `alerts` are not carried into the export.**
28
+ * Neither RFC 5545 property (`VALARM` for alerts; nothing standard for a
29
+ * join link distinct from `LOCATION`) was part of this ticket's evidence
30
+ * (`EventDetail.tsx` has no export control at all, not "an export control
31
+ * that drops one field"), so adding them is left to a later ticket.
32
+ */
33
+ import { parseDurationMs } from "./wire.js";
34
+ const DAY_MS = 24 * 60 * 60 * 1000;
35
+ /** RFC 5545 §3.3.11 `TEXT` escaping. Order matters: the backslash escape
36
+ * must run first, or every other escape's own backslash gets escaped
37
+ * again. */
38
+ function escapeText(value) {
39
+ return value
40
+ .replace(/\\/g, '\\\\')
41
+ .replace(/;/g, '\\;')
42
+ .replace(/,/g, '\\,')
43
+ .replace(/\r\n|\r|\n/g, '\\n');
44
+ }
45
+ /** RFC 5545 §3.2's `param-value`: quoted when it carries a character the
46
+ * bare form cannot (`,`, `;`, `:`); a `"` is stripped rather than escaped,
47
+ * since a quoted param value has no escape for one (`QSAFE-CHAR` excludes
48
+ * `DQUOTE` outright). */
49
+ function paramValue(value) {
50
+ const cleaned = value.replace(/"/g, "'");
51
+ return /[,;:]/.test(cleaned) ? `"${cleaned}"` : cleaned;
52
+ }
53
+ /** RFC 5545 §3.1's line folding: no content line may exceed 75 octets: a
54
+ * longer one is split, each continuation introduced by CRLF and a single
55
+ * space (which itself counts as an octet on that continuation line, hence
56
+ * the narrower budget after the first chunk). Splits on octet boundaries,
57
+ * never mid-UTF-8-sequence -- backing off while the next byte is a
58
+ * continuation byte (`10xxxxxx`) -- so a title with an accented letter or
59
+ * an emoji folds without corrupting it. */
60
+ function foldLine(line) {
61
+ const bytes = new TextEncoder().encode(line);
62
+ if (bytes.length <= 75)
63
+ return line;
64
+ const decoder = new TextDecoder();
65
+ const chunks = [];
66
+ let start = 0;
67
+ let budget = 75;
68
+ while (start < bytes.length) {
69
+ let end = Math.min(start + budget, bytes.length);
70
+ while (end > start && ((bytes[end] ?? 0) & 0xc0) === 0x80)
71
+ end -= 1;
72
+ chunks.push(decoder.decode(bytes.slice(start, end)));
73
+ start = end;
74
+ budget = 74; // the continuation's own leading space is the 75th octet
75
+ }
76
+ return chunks.join('\r\n ');
77
+ }
78
+ /** `"2026-10-05T09:00:00"` -> `"20261005T090000Z"` (naive-UTC; see the file
79
+ * header). Slicing to 15 after stripping punctuation drops any fractional
80
+ * seconds this package never produces but should not choke on. */
81
+ function basicDateTime(local) {
82
+ return `${local.replace(/[-:]/g, '').slice(0, 15)}Z`;
83
+ }
84
+ /** `"2026-10-05T09:00:00"` -> `"20261005"`, for an all-day `DTSTART`/`DTEND`
85
+ * (`VALUE=DATE`, which carries no time or zone at all). */
86
+ function basicDate(local) {
87
+ return local.slice(0, 10).replace(/-/g, '');
88
+ }
89
+ function isoBasicUtc(date) {
90
+ return `${date.toISOString().replace(/[-:]/g, '').split('.')[0]}Z`;
91
+ }
92
+ /** The event's own end, in the same naive-UTC local shape `start` is in.
93
+ * `DTEND`/`VALUE=DATE`'s own end is exclusive (RFC 5545 §3.6.1), which an
94
+ * all-day event's whole-day duration already lands on: "2 days" starting
95
+ * the 5th ends, exclusive, the 7th -- the day after the last day. */
96
+ function computeEnd(event) {
97
+ const ms = parseDurationMs(event.duration) ?? (event.isAllDay ? DAY_MS : 0);
98
+ const end = new Date(new Date(`${event.start}Z`).getTime() + ms);
99
+ return end.toISOString().slice(0, 19);
100
+ }
101
+ const FREQ_ICS = {
102
+ daily: 'DAILY',
103
+ weekly: 'WEEKLY',
104
+ monthly: 'MONTHLY',
105
+ yearly: 'YEARLY',
106
+ };
107
+ const WEEKDAY_ICS = {
108
+ mo: 'MO',
109
+ tu: 'TU',
110
+ we: 'WE',
111
+ th: 'TH',
112
+ fr: 'FR',
113
+ sa: 'SA',
114
+ su: 'SU',
115
+ };
116
+ function ndayToIcs(day) {
117
+ return `${day.nthOfPeriod ?? ''}${WEEKDAY_ICS[day.day]}`;
118
+ }
119
+ /** RFC 5545 §3.3.10's `RRULE` value, parts in the order that section lists
120
+ * them. Every `CalendarRecurrenceRule` part but `rscale`/`skip` (the file
121
+ * header's own note) has a part here. */
122
+ function rruleValue(rule) {
123
+ const parts = [`FREQ=${FREQ_ICS[rule.frequency]}`];
124
+ if (rule.until !== undefined)
125
+ parts.push(`UNTIL=${basicDateTime(rule.until)}`);
126
+ if (rule.count !== undefined)
127
+ parts.push(`COUNT=${rule.count}`);
128
+ if (rule.interval !== undefined)
129
+ parts.push(`INTERVAL=${rule.interval}`);
130
+ if (rule.bySecond && rule.bySecond.length > 0)
131
+ parts.push(`BYSECOND=${rule.bySecond.join(',')}`);
132
+ if (rule.byMinute && rule.byMinute.length > 0)
133
+ parts.push(`BYMINUTE=${rule.byMinute.join(',')}`);
134
+ if (rule.byHour && rule.byHour.length > 0)
135
+ parts.push(`BYHOUR=${rule.byHour.join(',')}`);
136
+ if (rule.byDay && rule.byDay.length > 0) {
137
+ parts.push(`BYDAY=${rule.byDay.map(ndayToIcs).join(',')}`);
138
+ }
139
+ if (rule.byMonthDay && rule.byMonthDay.length > 0) {
140
+ parts.push(`BYMONTHDAY=${rule.byMonthDay.join(',')}`);
141
+ }
142
+ if (rule.byYearDay && rule.byYearDay.length > 0) {
143
+ parts.push(`BYYEARDAY=${rule.byYearDay.join(',')}`);
144
+ }
145
+ if (rule.byWeekNo && rule.byWeekNo.length > 0)
146
+ parts.push(`BYWEEKNO=${rule.byWeekNo.join(',')}`);
147
+ if (rule.byMonth && rule.byMonth.length > 0)
148
+ parts.push(`BYMONTH=${rule.byMonth.join(',')}`);
149
+ if (rule.bySetPosition && rule.bySetPosition.length > 0) {
150
+ parts.push(`BYSETPOS=${rule.bySetPosition.join(',')}`);
151
+ }
152
+ if (rule.firstDayOfWeek !== undefined)
153
+ parts.push(`WKST=${WEEKDAY_ICS[rule.firstDayOfWeek]}`);
154
+ return parts.join(';');
155
+ }
156
+ /** `calendarAddress` arrives off the wire (and out of `wire.ts`) already
157
+ * `mailto:`-prefixed (`react/participants.ts`'s own `addressOf` strips it
158
+ * for display) -- normalized rather than assumed, since a caller can build
159
+ * a `CalendarEventDraft` by hand with a bare address. Not imported from
160
+ * `react/participants.ts`: this file is the framework-free core, which
161
+ * never reaches into `./react` (mirrors `types.ts`'s own header comment on
162
+ * `wire.ts` staying behind the client). */
163
+ function normalizeMailto(address) {
164
+ return `mailto:${address.trim().replace(/^mailto:/i, '')}`;
165
+ }
166
+ const ROLE_ICS = {
167
+ owner: 'CHAIR',
168
+ chair: 'CHAIR',
169
+ attendee: 'REQ-PARTICIPANT',
170
+ optional: 'OPT-PARTICIPANT',
171
+ informational: 'NON-PARTICIPANT',
172
+ };
173
+ const PARTSTAT_ICS = {
174
+ 'needs-action': 'NEEDS-ACTION',
175
+ accepted: 'ACCEPTED',
176
+ declined: 'DECLINED',
177
+ tentative: 'TENTATIVE',
178
+ };
179
+ /** `ORGANIZER` (the participant carrying the `owner` role, if any) and one
180
+ * `ATTENDEE` per participant besides them -- RFC 5545 §3.2.3/§3.8.4.1/
181
+ * §3.8.4.3. An owner still appears as `ORGANIZER` only, never doubled as
182
+ * their own `ATTENDEE`. */
183
+ function participantLines(participants) {
184
+ const organizer = participants.find((person) => (person.roles ?? []).includes('owner'));
185
+ const lines = [];
186
+ if (organizer !== undefined) {
187
+ const cn = organizer.name !== undefined ? `;CN=${paramValue(organizer.name)}` : '';
188
+ lines.push(`ORGANIZER${cn}:${normalizeMailto(organizer.calendarAddress)}`);
189
+ }
190
+ for (const person of participants) {
191
+ if (person === organizer)
192
+ continue;
193
+ const role = (person.roles ?? []).find((r) => r !== 'owner') ?? 'attendee';
194
+ const cn = person.name !== undefined ? `;CN=${paramValue(person.name)}` : '';
195
+ const partstat = person.participationStatus !== undefined
196
+ ? `;PARTSTAT=${PARTSTAT_ICS[person.participationStatus]}`
197
+ : '';
198
+ lines.push(`ATTENDEE;ROLE=${ROLE_ICS[role]}${partstat}${cn}:${normalizeMailto(person.calendarAddress)}`);
199
+ }
200
+ return lines;
201
+ }
202
+ function veventLines(event, now) {
203
+ const lines = ['BEGIN:VEVENT', `UID:${event.uid}`, `DTSTAMP:${isoBasicUtc(now)}`];
204
+ const end = computeEnd(event);
205
+ if (event.isAllDay) {
206
+ lines.push(`DTSTART;VALUE=DATE:${basicDate(event.start)}`, `DTEND;VALUE=DATE:${basicDate(end)}`);
207
+ }
208
+ else {
209
+ lines.push(`DTSTART:${basicDateTime(event.start)}`, `DTEND:${basicDateTime(end)}`);
210
+ }
211
+ lines.push(`SUMMARY:${escapeText(event.title)}`);
212
+ if (event.description !== undefined)
213
+ lines.push(`DESCRIPTION:${escapeText(event.description)}`);
214
+ if (event.location !== undefined)
215
+ lines.push(`LOCATION:${escapeText(event.location)}`);
216
+ lines.push(`STATUS:${event.status.toUpperCase()}`, `SEQUENCE:${event.sequence}`);
217
+ // RFC 5545 §3.8.2.7: OPAQUE is the default, so only a 'free' event
218
+ // (wtfalch/calendar#29) needs the line.
219
+ if (event.freeBusyStatus === 'free')
220
+ lines.push('TRANSP:TRANSPARENT');
221
+ if (event.recurrenceRule !== undefined)
222
+ lines.push(`RRULE:${rruleValue(event.recurrenceRule)}`);
223
+ lines.push(...participantLines(event.participants ?? []));
224
+ lines.push('END:VEVENT');
225
+ return lines;
226
+ }
227
+ /** One or more events as a single RFC 5545 `.ics` document (a `VCALENDAR`
228
+ * wrapping one `VEVENT` per event) -- CRLF line endings and folding
229
+ * included, so the string this returns is ready to write to a file or hand
230
+ * to a `Blob` exactly as is. */
231
+ export function eventsToIcs(events, options = {}) {
232
+ const now = options.now ?? new Date();
233
+ const lines = [
234
+ 'BEGIN:VCALENDAR',
235
+ 'VERSION:2.0',
236
+ 'PRODID:-//wtfalch/calendar//EN',
237
+ 'CALSCALE:GREGORIAN',
238
+ ...events.flatMap((event) => veventLines(event, now)),
239
+ 'END:VCALENDAR',
240
+ ];
241
+ return `${lines.map(foldLine).join('\r\n')}\r\n`;
242
+ }
243
+ /** A single event's own `.ics` document -- `EventDetail`'s "Download .ics"
244
+ * control (wtfalch/calendar#28) is this, one event at a time. */
245
+ export function eventToIcs(event, options = {}) {
246
+ return eventsToIcs([event], options);
247
+ }
@@ -8,5 +8,7 @@
8
8
  * acceptance criteria). The JMAP wire stays behind the client.
9
9
  */
10
10
  export { createCalendarClient } from './calendar-client.ts';
11
+ export { eventToIcs, eventsToIcs } from './ics.ts';
12
+ export type { IcsExportOptions } from './ics.ts';
11
13
  export { CalendarError } from './types.ts';
12
- export type { AvailabilityInclusion, AvailabilityPeriod, Calendar, CalendarBusyStatus, CalendarChangedState, CalendarClient, CalendarClientOptions, CalendarEvent, CalendarEventDraft, CalendarEventStatus, CalendarParticipant, CalendarParticipantRole, CalendarParticipationStatus, CalendarRange, CalendarRecurrenceRule, CalendarRight, CalendarSubscription, Principal, SchedulingOptions, ShareGrant, } from './types.ts';
14
+ export type { AvailabilityInclusion, AvailabilityPeriod, AvailabilityResult, Calendar, CalendarAlert, CalendarAlertAction, CalendarAlertRelativeTo, CalendarBusyStatus, CalendarChangedState, CalendarClient, CalendarClientOptions, CalendarEvent, CalendarEventDraft, CalendarEventStatus, CalendarFreeBusyStatus, CalendarLink, CalendarNDay, CalendarParticipant, CalendarParticipantRole, CalendarParticipationStatus, CalendarRange, CalendarRecurrenceRule, CalendarRight, CalendarSubscription, CalendarVirtualLocation, CalendarWeekday, FindTimeResult, Principal, RecurrenceScope, RecurrenceScopeOptions, SchedulingOptions, SearchOptions, ShareGrant, WorkingHours, } from './types.ts';
@@ -8,4 +8,5 @@
8
8
  * acceptance criteria). The JMAP wire stays behind the client.
9
9
  */
10
10
  export { createCalendarClient } from "./calendar-client.js";
11
+ export { eventToIcs, eventsToIcs } from "./ics.js";
11
12
  export { CalendarError } from "./types.js";
@@ -35,7 +35,6 @@ import { EventDetail } from "./EventDetail.js";
35
35
  import { EventEditor } from "./EventEditor.js";
36
36
  import { ShareDialog } from "./ShareDialog.js";
37
37
  import { Toolbar } from "./Toolbar.js";
38
- import { sameAddress } from "./participants.js";
39
38
  const localizer = dayjsLocalizer(dayjs);
40
39
  /** The date in a month cell is `6`, not `06`. react-big-calendar's dayjs
41
40
  * localizer pads by default, and a zero-padded day reads as a code rather
@@ -254,14 +253,23 @@ function useMe(client) {
254
253
  * How the editor asks when a set of people are busy.
255
254
  *
256
255
  * One `resolvePrincipal` per address to turn it into the `principalId`
257
- * `getAvailability` takes, then one availability call each. An address that
258
- * resolves to nobody, or a call that fails, simply has no entry — which the
259
- * ribbon draws as unknown, because that is what it is.
256
+ * `getAvailability` takes — that part is unchanged, `Principal/query` has no
257
+ * batched form here — but then one `getAvailability` call for every resolved
258
+ * principal, not one per address: `getAvailability` now takes the whole set
259
+ * at once and answers a map, the same JMAP-level batching
260
+ * `Principal/getAvailability` always supported (issue #13 Decision; this
261
+ * hook is the "N round trips and the merge lives in the app" the ticket
262
+ * named). An address that resolves to nobody simply has no entry, which the
263
+ * ribbon draws as unknown.
260
264
  *
261
- * **An empty list is not "free".** It is the same answer the server gives for
262
- * never-shared and for shared-then-revoked, measured live and pinned in
263
- * `wire-live-transcript.test.ts`. The ribbon is the place that decides what to
264
- * draw; this function only reports what came back.
265
+ * **An empty answer is not "free".** It is the same answer the server gives
266
+ * for never-shared and for shared-then-revoked, measured live and pinned in
267
+ * `wire-live-transcript.test.ts` — `getAvailability`'s own `'unknown'` kind
268
+ * already folds that in. A failure of the one batched call now costs every
269
+ * address its entry rather than only the addresses that individually failed;
270
+ * that trade only ever turns a real busy reading into an honest "unknown"
271
+ * one, never the other way, so the ribbon's own catch-all (`useEffect` below,
272
+ * `AvailabilityRibbon`) still has the right thing to draw.
265
273
  */
266
274
  function useAvailabilityLookup(client) {
267
275
  return useCallback(async (addresses, day) => {
@@ -270,19 +278,26 @@ function useAvailabilityLookup(client) {
270
278
  const to = new Date(from);
271
279
  to.setDate(to.getDate() + 1);
272
280
  const range = { after: from.toISOString(), before: to.toISOString() };
273
- const answers = new Map();
281
+ const addressByPrincipalId = new Map();
274
282
  await Promise.all(addresses.map(async (address) => {
275
283
  try {
276
284
  const principal = await client.resolvePrincipal(address);
277
- if (!principal)
278
- return;
279
- answers.set(address, await client.getAvailability(principal.accountId, range));
285
+ if (principal)
286
+ addressByPrincipalId.set(principal.accountId, address);
280
287
  }
281
288
  catch {
282
- // No entry, so the band stays unknown. A failure to ask is one
289
+ // No entry, so the band stays unknown. A failed resolve is one
283
290
  // more way of not being able to see somebody.
284
291
  }
285
292
  }));
293
+ const answers = new Map();
294
+ if (addressByPrincipalId.size > 0) {
295
+ const results = await client.getAvailability([...addressByPrincipalId.keys()], range);
296
+ for (const [principalId, address] of addressByPrincipalId) {
297
+ const result = results.get(principalId);
298
+ answers.set(address, result?.kind === 'known' ? result.periods : undefined);
299
+ }
300
+ }
286
301
  return answers;
287
302
  }, [client]);
288
303
  }
@@ -396,24 +411,18 @@ export function Calendar({ client, location, onNavigate, account, onError, now,
396
411
  /**
397
412
  * Answer an invite.
398
413
  *
399
- * Always with `sendSchedulingMessages: true`, and not by the person's
400
- * choice: an RSVP nobody is told about is not an RSVP. That is the opposite
401
- * of the editor's Save, where telling people is the separate decision --
402
- * here the telling *is* the act.
403
- *
404
- * The patch addresses the viewer's own participant entry by its map key.
405
- * Those keys are assigned by `wire.ts` (`p0`, `p1`, ...) and are never part
406
- * of the contract, so the key is looked up by address rather than assumed.
414
+ * `client.respond`, not `updateEvent` -- the organiser's verb (#11). Always
415
+ * with `sendSchedulingMessages: true`, and not by the person's choice: an
416
+ * RSVP nobody is told about is not an RSVP. That is the opposite of the
417
+ * editor's Save, where telling people is the separate decision -- here the
418
+ * telling *is* the act.
407
419
  */
408
420
  const respond = useCallback(async (answer) => {
409
- if (selected === undefined || me === undefined)
421
+ if (selected === undefined)
410
422
  return;
411
- const participants = (selected.participants ?? []).map((person) => sameAddress(person.calendarAddress, me)
412
- ? { ...person, participationStatus: answer }
413
- : person);
414
- await client.updateEvent(selected.id, { participants }, { sendSchedulingMessages: true });
423
+ await client.respond(selected.id, answer, { sendSchedulingMessages: true });
415
424
  reload();
416
- }, [client, me, reload, selected]);
425
+ }, [client, reload, selected]);
417
426
  const empty = !loading && !error && gridEvents.length === 0;
418
427
  const detail = selected !== undefined ? (_jsx(EventDetail, { event: selected, me: me, onEdit: () => setEditing({ event: selected, start: undefined }), onRespond: respond, onClose: closeDetail })) : null;
419
428
  /** The phone day view's own picker: the week around `current.date`, tapping