@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.
@@ -9,6 +9,7 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
9
9
  */
10
10
  import { Button, Icon, Identity, Pill } from '@wtfalch/design';
11
11
  import { useState } from 'react';
12
+ import { eventToIcs } from "../ics.js";
12
13
  import { parseDurationMs } from "../wire.js";
13
14
  import { STATUS_TONE, STATUS_WORD, addressOf, sameAddress } from "./participants.js";
14
15
  /** The three answers a person can give, in the order a person weighs them.
@@ -35,6 +36,26 @@ function formatWhen(event) {
35
36
  return `${date}, ${time(start)}`;
36
37
  return `${date}, ${time(start)} to ${time(new Date(start.getTime() + ms))}`;
37
38
  }
39
+ /** A filesystem-safe `.ics` filename built from the title -- strips the
40
+ * characters no common filesystem accepts, and falls back to a generic
41
+ * name for a title that is empty or entirely such characters (wtfalch/calendar#28). */
42
+ function icsFilename(title) {
43
+ const cleaned = title.replace(/[\\/:*?"<>|]/g, '-').trim();
44
+ return `${cleaned === '' ? 'event' : cleaned}.ics`;
45
+ }
46
+ /** Hands the browser a `.ics` file the way a native "Save As" would: a blob
47
+ * URL, a link nobody sees, one click, then the URL is freed. There is no
48
+ * server round trip -- the export is built entirely from the event this
49
+ * pane already has (wtfalch/calendar#28). */
50
+ function downloadIcs(event) {
51
+ const blob = new Blob([eventToIcs(event)], { type: 'text/calendar;charset=utf-8' });
52
+ const url = URL.createObjectURL(blob);
53
+ const link = document.createElement('a');
54
+ link.href = url;
55
+ link.download = icsFilename(event.title);
56
+ link.click();
57
+ URL.revokeObjectURL(url);
58
+ }
38
59
  /**
39
60
  * What the pane says about repetition.
40
61
  *
@@ -84,7 +105,7 @@ export function EventDetail({ event, me, onEdit, onRespond, onClose }) {
84
105
  setAnswering(null);
85
106
  }
86
107
  };
87
- return (_jsxs("article", { className: "wtcal-detail", "aria-label": event.title, children: [_jsxs("header", { className: "wtcal-detail-head", children: [_jsx("h2", { className: "wtcal-detail-title", children: event.title }), _jsx(Button, { kind: "ghost", size: "sm", iconOnly: true, "aria-label": "Close event details", onPress: onClose, children: _jsx(Icon, { name: "close", size: "sm" }) })] }), _jsx("p", { className: "wtcal-detail-when", children: formatWhen(event) }), repeat !== null && _jsx("p", { className: "wtcal-detail-repeat", children: repeat }), invited && onRespond !== undefined && (_jsxs("section", { className: "wtcal-rsvp", "aria-label": "Your answer", children: [_jsx("h3", { className: "wtcal-detail-label", children: "Are you going?" }), _jsx("div", { className: "wtcal-rsvp-answers", children: ANSWERS.map((answer) => {
108
+ return (_jsxs("article", { className: "wtcal-detail", "aria-label": event.title, children: [_jsxs("header", { className: "wtcal-detail-head", children: [_jsx("h2", { className: "wtcal-detail-title", children: event.title }), _jsxs("div", { className: "wtcal-detail-head-actions", children: [_jsx(Button, { kind: "ghost", size: "sm", iconOnly: true, "aria-label": "Download as .ics", onPress: () => downloadIcs(event), children: _jsx(Icon, { name: "download", size: "sm" }) }), _jsx(Button, { kind: "ghost", size: "sm", iconOnly: true, "aria-label": "Close event details", onPress: onClose, children: _jsx(Icon, { name: "close", size: "sm" }) })] })] }), _jsx("p", { className: "wtcal-detail-when", children: formatWhen(event) }), repeat !== null && _jsx("p", { className: "wtcal-detail-repeat", children: repeat }), invited && onRespond !== undefined && (_jsxs("section", { className: "wtcal-rsvp", "aria-label": "Your answer", children: [_jsx("h3", { className: "wtcal-detail-label", children: "Are you going?" }), _jsx("div", { className: "wtcal-rsvp-answers", children: ANSWERS.map((answer) => {
88
109
  const chosen = mine?.participationStatus === answer.value;
89
110
  return (_jsx(Button, { kind: chosen ? 'primary' : 'default', "aria-pressed": chosen, busy: answering === answer.value, disabled: answering !== null, onPress: () => void respond(answer.value), children: answer.label }, answer.value));
90
111
  }) }), _jsx("p", { className: "wtcal-rsvp-note", children: "The organiser is told either way." }), failure !== null && (_jsx("p", { className: "wtcal-failure", role: "alert", children: failure }))] })), event.status === 'cancelled' && _jsx(Pill, { tone: "bad", children: "Cancelled" }), event.status === 'tentative' && _jsx(Pill, { tone: "warn", children: "Tentative" }), event.location !== undefined && (_jsxs("section", { className: "wtcal-detail-section", children: [_jsx("h3", { className: "wtcal-detail-label", children: "Where" }), _jsx("p", { className: "wtcal-detail-text", children: event.location })] })), event.description !== undefined && (_jsxs("section", { className: "wtcal-detail-section", children: [_jsx("h3", { className: "wtcal-detail-label", children: "Notes" }), _jsx("p", { className: "wtcal-detail-text", children: event.description })] })), participants.length > 0 && (_jsxs("section", { className: "wtcal-detail-section", children: [_jsxs("h3", { className: "wtcal-detail-label", children: [participants.length, " invited"] }), _jsx("ul", { className: "wtcal-detail-people", children: participants.map((participant) => (_jsx("li", { children: _jsx(Identity, { kind: "line", size: "sm", name: participant.name ?? null, address: addressOf(participant), aside: participant.participationStatus !== undefined && (_jsx(Pill, { quiet: true, tone: STATUS_TONE[participant.participationStatus], children: STATUS_WORD[participant.participationStatus] })) }) }, participant.calendarAddress))) })] })), _jsx("footer", { className: "wtcal-detail-actions", children: _jsx(Button, { kind: "primary", onPress: onEdit, children: "Edit event" }) })] }));
@@ -1,4 +1,4 @@
1
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
2
  /**
3
3
  * The event editor: create, edit and delete a person's own events, recurring
4
4
  * included (MSG-055, https://github.com/wtfalch/messaging/issues/158).
@@ -33,6 +33,33 @@ const FREQUENCIES = [
33
33
  { value: 'monthly', label: 'Every month' },
34
34
  { value: 'yearly', label: 'Every year' },
35
35
  ];
36
+ /** Singular/plural noun for the "every N ___" interval field (wtfalch/calendar#30). */
37
+ const INTERVAL_UNIT = {
38
+ daily: ['day', 'days'],
39
+ weekly: ['week', 'weeks'],
40
+ monthly: ['month', 'months'],
41
+ yearly: ['year', 'years'],
42
+ };
43
+ /** Two-letter RFC 5545 weekday codes, Monday first -- `CalendarRecurrenceRule.byDay`'s
44
+ * own `day` values (wtfalch/calendar#30). Only offered for a weekly rule: a
45
+ * bare weekday on a daily/monthly/yearly rule is a different, unrelated
46
+ * RFC 8984 shape this ticket's evidence never asked for. */
47
+ const WEEKDAYS = [
48
+ { value: 'mo', label: 'Mo' },
49
+ { value: 'tu', label: 'Tu' },
50
+ { value: 'we', label: 'We' },
51
+ { value: 'th', label: 'Th' },
52
+ { value: 'fr', label: 'Fr' },
53
+ { value: 'sa', label: 'Sa' },
54
+ { value: 'su', label: 'Su' },
55
+ ];
56
+ function recurrenceEndOf(rule) {
57
+ if (rule?.until !== undefined)
58
+ return 'on';
59
+ if (rule?.count !== undefined)
60
+ return 'after';
61
+ return 'never';
62
+ }
36
63
  const DURATIONS = [
37
64
  { value: 'PT15M', label: '15 minutes' },
38
65
  { value: 'PT30M', label: '30 minutes' },
@@ -77,6 +104,16 @@ export function EventEditor({ event, initialStart, now, calendarId, compact, onS
77
104
  const [location, setLocation] = useState(event?.location ?? '');
78
105
  const [description, setDescription] = useState(event?.description ?? '');
79
106
  const [frequency, setFrequency] = useState(event?.recurrenceRule?.frequency ?? '');
107
+ // Named `recurrenceInterval`, not `interval`: the setter would otherwise be
108
+ // `setInterval`, shadowing the timer function of the same name.
109
+ const [recurrenceInterval, setRecurrenceInterval] = useState(event?.recurrenceRule?.interval ?? 1);
110
+ const [byDay, setByDay] = useState((event?.recurrenceRule?.byDay ?? []).map((day) => day.day));
111
+ const [recurrenceEnd, setRecurrenceEnd] = useState(recurrenceEndOf(event?.recurrenceRule));
112
+ // `until` here is a plain `YYYY-MM-DD` for the date input, not the wire's
113
+ // own local date-time -- `draft`'s own memo appends the end-of-day time
114
+ // when it builds the rule.
115
+ const [until, setUntil] = useState(event?.recurrenceRule?.until?.slice(0, 10) ?? '');
116
+ const [count, setCount] = useState(event?.recurrenceRule?.count ?? 5);
80
117
  const [participants, setParticipants] = useState(event?.participants ?? []);
81
118
  const [invitee, setInvitee] = useState('');
82
119
  /** Off, always, whatever the event already has on it. Sending is a decision
@@ -99,11 +136,30 @@ export function EventEditor({ event, initialStart, now, calendarId, compact, onS
99
136
  duration,
100
137
  isAllDay,
101
138
  location: location.trim() === '' ? undefined : location.trim(),
102
- recurrenceRule: frequency === '' ? undefined : { frequency, interval: 1 },
139
+ recurrenceRule: frequency === ''
140
+ ? undefined
141
+ : {
142
+ frequency,
143
+ interval: recurrenceInterval,
144
+ // `byDay` only makes sense once a week's worth of days exist to
145
+ // choose from -- a stale weekday picked while the frequency was
146
+ // 'weekly' must not leak onto a monthly/yearly rule when the
147
+ // person switches it without clearing the picker.
148
+ ...(frequency === 'weekly' && byDay.length > 0
149
+ ? { byDay: byDay.map((day) => ({ day })) }
150
+ : {}),
151
+ // The date input gives a bare day; the wire's `until` is
152
+ // inclusive, so end-of-day is what actually keeps that day's
153
+ // own occurrence in the series.
154
+ ...(recurrenceEnd === 'on' && until !== '' ? { until: `${until}T23:59:59` } : {}),
155
+ ...(recurrenceEnd === 'after' ? { count } : {}),
156
+ },
103
157
  participants: participants.length === 0 ? undefined : participants,
104
158
  status: event?.status ?? 'confirmed',
105
159
  }), [
160
+ byDay,
106
161
  calendarId,
162
+ count,
107
163
  description,
108
164
  duration,
109
165
  event,
@@ -111,9 +167,15 @@ export function EventEditor({ event, initialStart, now, calendarId, compact, onS
111
167
  isAllDay,
112
168
  location,
113
169
  participants,
170
+ recurrenceEnd,
171
+ recurrenceInterval,
114
172
  start,
115
173
  title,
174
+ until,
116
175
  ]);
176
+ const toggleWeekday = useCallback((day, on) => {
177
+ setByDay((current) => (on ? [...current, day] : current.filter((d) => d !== day)));
178
+ }, []);
117
179
  /** Somebody typed an address and meant it. Duplicates are dropped rather
118
180
  * than refused: adding a person already on the list is not an error, it is
119
181
  * just nothing. */
@@ -176,7 +238,7 @@ export function EventEditor({ event, initialStart, now, calendarId, compact, onS
176
238
  // began 3px before it ended -- the circle sat on the last letter.
177
239
  // The prop is the system's own answer to that, and the only thing
178
240
  // it changes is the body's right padding.
179
- _jsx(Checkbox, { tile: true, label: "Email everyone", checked: notify, onChange: setNotify, disabled: busy })), _jsx("span", { className: "wtcal-editor-spacer" }), _jsx(Button, { kind: "ghost", onPress: onClose, disabled: busy, children: "Cancel" }), _jsx(Button, { kind: "primary", busy: busy, disabled: titleMissing, onPress: () => attempt('save'), children: creating ? 'Create event' : 'Save changes' })] }), children: _jsxs("div", { className: compact ? 'wtcal-editor is-compact' : 'wtcal-editor', children: [_jsx(Field, { label: "Title", required: true, children: (wiring) => (_jsx(Input, { ...wiring, block: true, size: "lg", value: title, placeholder: "What is this meeting?", onChange: (e) => setTitle(e.target.value) })) }), _jsxs("div", { className: "wtcal-editor-row", children: [_jsx(Field, { label: isAllDay ? 'Day' : 'Starts', children: (wiring) => (_jsx(Input, { ...wiring, block: true, type: isAllDay ? 'date' : 'datetime-local', value: isAllDay ? start.slice(0, 10) : start, onChange: (e) => setStart(isAllDay ? `${e.target.value}T00:00` : e.target.value) })) }), !isAllDay && (_jsx(Field, { label: "For", children: (wiring) => (_jsx(Select, { ...wiring, block: true, value: duration, onChange: (e) => setDuration(e.target.value), children: durationOptions(duration).map((option) => (_jsx("option", { value: option.value, children: option.label }, option.value))) })) }))] }), !isAllDay && (_jsx(AvailabilityRibbon, { participants: participants, start: new Date(start), durationMinutes: (parseDurationMs(duration) ?? 3_600_000) / 60_000, lookup: availability })), _jsx(Checkbox, { label: "All day", checked: isAllDay, onChange: setIsAllDay }), _jsx(Field, { label: "Repeats", children: (wiring) => (_jsx(Select, { ...wiring, block: true, value: frequency, onChange: (e) => setFrequency(e.target.value), children: FREQUENCIES.map((option) => (_jsx("option", { value: option.value, children: option.label }, option.value))) })) }), _jsx(Field, { label: "Who", hint: "An email address. They are added to the event, not mailed yet.", children: (wiring) => (_jsxs("div", { className: "wtcal-invitee-add", children: [_jsx(Input, { ...wiring, block: true, type: "email", value: invitee, placeholder: "someone@example.org", onChange: (e) => setInvitee(e.target.value),
241
+ _jsx(Checkbox, { tile: true, label: "Email everyone", checked: notify, onChange: setNotify, disabled: busy })), _jsx("span", { className: "wtcal-editor-spacer" }), _jsx(Button, { kind: "ghost", onPress: onClose, disabled: busy, children: "Cancel" }), _jsx(Button, { kind: "primary", busy: busy, disabled: titleMissing, onPress: () => attempt('save'), children: creating ? 'Create event' : 'Save changes' })] }), children: _jsxs("div", { className: compact ? 'wtcal-editor is-compact' : 'wtcal-editor', children: [_jsx(Field, { label: "Title", required: true, children: (wiring) => (_jsx(Input, { ...wiring, block: true, size: "lg", value: title, placeholder: "What is this meeting?", onChange: (e) => setTitle(e.target.value) })) }), _jsxs("div", { className: "wtcal-editor-row", children: [_jsx(Field, { label: isAllDay ? 'Day' : 'Starts', children: (wiring) => (_jsx(Input, { ...wiring, block: true, type: isAllDay ? 'date' : 'datetime-local', value: isAllDay ? start.slice(0, 10) : start, onChange: (e) => setStart(isAllDay ? `${e.target.value}T00:00` : e.target.value) })) }), !isAllDay && (_jsx(Field, { label: "For", children: (wiring) => (_jsx(Select, { ...wiring, block: true, value: duration, onChange: (e) => setDuration(e.target.value), children: durationOptions(duration).map((option) => (_jsx("option", { value: option.value, children: option.label }, option.value))) })) }))] }), !isAllDay && (_jsx(AvailabilityRibbon, { participants: participants, start: new Date(start), durationMinutes: (parseDurationMs(duration) ?? 3_600_000) / 60_000, lookup: availability })), _jsx(Checkbox, { label: "All day", checked: isAllDay, onChange: setIsAllDay }), _jsx(Field, { label: "Repeats", children: (wiring) => (_jsx(Select, { ...wiring, block: true, value: frequency, onChange: (e) => setFrequency(e.target.value), children: FREQUENCIES.map((option) => (_jsx("option", { value: option.value, children: option.label }, option.value))) })) }), frequency !== '' && (_jsxs(_Fragment, { children: [_jsxs("div", { className: "wtcal-editor-row", children: [_jsx(Field, { label: `Every (${INTERVAL_UNIT[frequency][recurrenceInterval === 1 ? 0 : 1]})`, children: (wiring) => (_jsx(Input, { ...wiring, block: true, type: "number", min: 1, value: recurrenceInterval, onChange: (e) => setRecurrenceInterval(Math.max(1, Number(e.target.value) || 1)) })) }), _jsx(Field, { label: "Ends", children: (wiring) => (_jsxs(Select, { ...wiring, block: true, value: recurrenceEnd, onChange: (e) => setRecurrenceEnd(e.target.value), children: [_jsx("option", { value: "never", children: "Never" }), _jsx("option", { value: "on", children: "On a date" }), _jsx("option", { value: "after", children: "After a number of times" })] })) })] }), frequency === 'weekly' && (_jsx(Field, { label: "On", hint: "Which day of the week.", children: () => (_jsx("div", { className: "wtcal-weekdays", children: WEEKDAYS.map((day) => (_jsx(Checkbox, { tile: true, label: day.label, checked: byDay.includes(day.value), onChange: (on) => toggleWeekday(day.value, on) }, day.value))) })) })), recurrenceEnd === 'on' && (_jsx(Field, { label: "End date", children: (wiring) => (_jsx(Input, { ...wiring, block: true, type: "date", value: until, onChange: (e) => setUntil(e.target.value) })) })), recurrenceEnd === 'after' && (_jsx(Field, { label: "Number of times", children: (wiring) => (_jsx(Input, { ...wiring, block: true, type: "number", min: 1, value: count, onChange: (e) => setCount(Math.max(1, Number(e.target.value) || 1)) })) }))] })), _jsx(Field, { label: "Who", hint: "An email address. They are added to the event, not mailed yet.", children: (wiring) => (_jsxs("div", { className: "wtcal-invitee-add", children: [_jsx(Input, { ...wiring, block: true, type: "email", value: invitee, placeholder: "someone@example.org", onChange: (e) => setInvitee(e.target.value),
180
242
  // Enter adds a person; without this it submits nothing and
181
243
  // the address the person typed disappears on Save.
182
244
  onKeyDown: (e) => {
@@ -124,24 +124,170 @@ export type CalendarParticipant = {
124
124
  roles?: readonly CalendarParticipantRole[];
125
125
  participationStatus?: CalendarParticipationStatus;
126
126
  };
127
+ /** RFC 5545's two-letter weekday abbreviation, as JSCalendar's `NDay.day`
128
+ * and `RecurrenceRule.firstDayOfWeek` name it (RFC 8984 §3.3). */
129
+ export type CalendarWeekday = 'mo' | 'tu' | 'we' | 'th' | 'fr' | 'sa' | 'su';
127
130
  /**
128
- * A recurrence rule, RFC 5545 §3.3.10 shaped.
131
+ * One weekday entry in a rule's `byDay`: RFC 8984 §3.3's `NDay`. A bare
132
+ * weekday (`{day: 'tu'}`) means every occurrence of that weekday in the
133
+ * period the rule's `frequency` sweeps; `nthOfPeriod` narrows it to one
134
+ * instance -- the 2nd Tuesday of the month is `{day: 'tu', nthOfPeriod: 2}`,
135
+ * the last Friday is `{day: 'fr', nthOfPeriod: -1}` (RFC 5545 §3.3.10's
136
+ * `BYDAY`, RFC 8984 §3.3).
137
+ */
138
+ export type CalendarNDay = {
139
+ day: CalendarWeekday;
140
+ nthOfPeriod?: number;
141
+ };
142
+ /**
143
+ * A recurrence rule, RFC 8984 §3.3 (`RecurrenceRule`) shaped -- every part
144
+ * that section defines, not only the bounds (`interval`/`count`/`until`).
145
+ * Dropping any of these on read, or on a 'this and following' split, quietly
146
+ * corrupts the rule for every JMAP client sharing the account
147
+ * (wtfalch/calendar#27): a `BYDAY`/`BYMONTHDAY`/`BYSETPOS`/`WKST`-carrying
148
+ * series that loses these the moment either half of a split is written back
149
+ * degrades to "every N days/weeks/months/years" with none of what actually
150
+ * picked its occurrences.
129
151
  *
130
152
  * `recurrenceRule` — confirmed live: the wire uses this singular field name
131
153
  * (one rule), not JSCalendar 2.0's plural `recurrenceRules` (MSG-053
132
154
  * acceptance criteria; plan §7; #137 amendment). The client never expands
133
155
  * this itself: expansion is entirely server-side (plan §7; #137
134
- * "Recurrence"), so this type exists only to display and edit the rule, not
135
- * to compute occurrences from it.
156
+ * "Recurrence"), so this type exists only to display, edit and round-trip
157
+ * the rule, not to compute occurrences from it.
136
158
  */
137
159
  export type CalendarRecurrenceRule = {
138
160
  frequency: 'daily' | 'weekly' | 'monthly' | 'yearly';
139
161
  interval?: number;
162
+ /** The calendar scale the rule's dates are computed in (RFC 8984 §3.3);
163
+ * every rule seen live has been `'gregorian'`, the default, but a value
164
+ * another client wrote must still round-trip rather than being dropped. */
165
+ rscale?: string;
166
+ /** How an invalid date produced by `byMonthDay`/`byMonth` (e.g. Feb 30) is
167
+ * handled: omit that occurrence, or roll it backward/forward to the
168
+ * nearest valid date (RFC 8984 §3.3). */
169
+ skip?: 'omit' | 'backward' | 'forward';
170
+ /** The weekday a week is considered to start on, for `weekly`'s own
171
+ * interval counting and for resolving `byWeekNo` (RFC 5545 §3.3.10's
172
+ * `WKST`, RFC 8984 §3.3). Defaults to `'mo'` when absent. */
173
+ firstDayOfWeek?: CalendarWeekday;
174
+ /** Which weekdays, optionally the Nth one of the period (RFC 5545's
175
+ * `BYDAY`). */
176
+ byDay?: readonly CalendarNDay[];
177
+ /** Which days of the month, 1-31 or negative counting from the end (RFC
178
+ * 5545's `BYMONTHDAY`). */
179
+ byMonthDay?: readonly number[];
180
+ /** Which months, as a string so a leap month can carry an `'L'` suffix
181
+ * (e.g. `'3L'`) for calendar scales that have one (RFC 5545's `BYMONTH`,
182
+ * RFC 8984 §3.3). */
183
+ byMonth?: readonly string[];
184
+ /** Which days of the year, 1-366 or negative counting from the end (RFC
185
+ * 5545's `BYYEARDAY`). */
186
+ byYearDay?: readonly number[];
187
+ /** Which weeks of the year (RFC 5545's `BYWEEKNO`; `yearly` only). */
188
+ byWeekNo?: readonly number[];
189
+ byHour?: readonly number[];
190
+ byMinute?: readonly number[];
191
+ bySecond?: readonly number[];
192
+ /** Which of the occurrences generated by the rest of the rule to keep --
193
+ * "the 2nd Tuesday and last Friday of every month with a meeting" is
194
+ * `byDay` naming both weekdays and `bySetPosition: [1, -1]` picking the
195
+ * first and last of each month's matches (RFC 5545's `BYSETPOS`, RFC 8984
196
+ * §3.3's `bySetPosition`). */
197
+ bySetPosition?: readonly number[];
140
198
  count?: number;
141
199
  until?: string;
142
200
  };
143
201
  /** RFC 5545 `STATUS`, as JSCalendar's `Event.status` names it. */
144
202
  export type CalendarEventStatus = 'confirmed' | 'cancelled' | 'tentative';
203
+ /**
204
+ * RFC 5545 §3.8.2.7 `TRANSP`, as JSCalendar's `Event.freeBusyStatus` names
205
+ * it (RFC 8984 §4.4.1): whether this event counts as busy time for its
206
+ * owner's free/busy search. `'busy'` is the default when absent -- an
207
+ * optional webinar or a tentative hold that should not produce a false
208
+ * conflict in `findTime()` is the one that sets `'free'`
209
+ * (wtfalch/calendar#29).
210
+ */
211
+ export type CalendarFreeBusyStatus = 'free' | 'busy';
212
+ /** JSCalendar `Alert.action` (RFC 8984 §5.7). Only `'display'` is built --
213
+ * the ticket that added `alerts` (issue #15) scopes email out -- but an
214
+ * `'email'` alert another client wrote is read and written back unchanged,
215
+ * live-confirmed against Stalwart v0.16.20, so the type names it. */
216
+ export type CalendarAlertAction = 'display' | 'email';
217
+ /** JSCalendar `OffsetTrigger.relativeTo` (RFC 8984 §5.6): whether `offset`
218
+ * counts from the event's start or its end. Optional because a live
219
+ * `CalendarEvent/get` never sent it back when the create never sent it
220
+ * either -- the server does not fill in its own default (T15). */
221
+ export type CalendarAlertRelativeTo = 'start' | 'end';
222
+ /**
223
+ * One alert on an event: a JSCalendar `Alert`. `offset` is a relative
224
+ * trigger, an ISO 8601 signed duration (e.g. `-PT15M` to fire 15 minutes
225
+ * before `relativeTo`); `when` is an absolute one, an ISO 8601 UTC
226
+ * date-time. At most one of the two is meaningful for a given alert. Both
227
+ * are live-confirmed against Stalwart v0.16.20 to round-trip through
228
+ * `CalendarEvent/set`/`get` with no shape change (T15).
229
+ *
230
+ * Neither is set when this package could not read the trigger, or when
231
+ * there was none to read -- live-confirmed possible: a trigger written
232
+ * with neither `offset` nor `when` is accepted on write, but the next `get`
233
+ * returns that alert with no `trigger` key at all (T15 amendment, a
234
+ * refuter finding). Writing such an alert back must not fabricate a
235
+ * trigger either -- `alertToWire` omits the key entirely, the same way the
236
+ * server does, rather than emit an empty or partial one.
237
+ */
238
+ export type CalendarAlert = {
239
+ /** The wire's own map key, present on an alert read off the server and
240
+ * reused on write-back. `CalendarEvent/set` replaces the *whole*
241
+ * `alerts` map on any write that touches it, so a client that renumbers
242
+ * keys on every save also renames them server-side -- out from under
243
+ * the dedicated `CalendarAlert` push channel
244
+ * (`CalendarChangedState.CalendarAlert`) and anything else that
245
+ * correlates by this id (T15 amendment). Absent for an alert the caller
246
+ * builds fresh; `alertsToWire` assigns one, the same way
247
+ * `participantsToWire` does for a participant. */
248
+ id?: string;
249
+ offset?: string;
250
+ when?: string;
251
+ relativeTo?: CalendarAlertRelativeTo;
252
+ action: CalendarAlertAction;
253
+ /** When the person last dismissed this alert -- an ISO 8601 UTC
254
+ * date-time the server stores and returns verbatim; this package never
255
+ * computes or clears it, only carries it forward. Because
256
+ * `CalendarEvent/set` replaces the whole `alerts` map, a mapper that
257
+ * silently drops this field on the way out wipes every alert's
258
+ * acknowledgement the moment anything touches `alerts` again -- live-
259
+ * confirmed (T15 amendment, a refuter finding). */
260
+ acknowledged?: string;
261
+ };
262
+ /**
263
+ * A join link into the call an event is, or hosts -- JSCalendar's
264
+ * `VirtualLocation` (RFC 8984 §4.2.6), the convention
265
+ * https://github.com/wtfalch/agora/issues/163 reserved. `uri` is the join
266
+ * link itself (a video-call URL, a SIP URI, a phone number as `tel:`); `name`
267
+ * is a label for it ("Join by video"). Separate from `CalendarEvent.location`
268
+ * on purpose: that field stays a plain string for the physical place, this
269
+ * one is the call (#16).
270
+ */
271
+ export type CalendarVirtualLocation = {
272
+ uri: string;
273
+ name?: string;
274
+ };
275
+ /**
276
+ * A link on an event: an agenda doc, a shared file, any URL the meeting
277
+ * should carry. This is JSCalendar's `Link` (RFC 8984 §1.4.11), the value
278
+ * type of `Event.links` (§4.2.5) (wtfalch/calendar#32). `href` is the link
279
+ * itself. `rel: 'enclosure'` marks it as an attachment rather than a
280
+ * related page. `contentType`/`size` describe the linked file when known.
281
+ * Uploading the file is the caller's job; this package only carries the
282
+ * reference.
283
+ */
284
+ export type CalendarLink = {
285
+ href: string;
286
+ title?: string;
287
+ contentType?: string;
288
+ size?: number;
289
+ rel?: string;
290
+ };
145
291
  /**
146
292
  * One event, or one occurrence of a recurring event.
147
293
  *
@@ -172,18 +318,49 @@ export type CalendarEvent = {
172
318
  /** An ISO 8601 duration, e.g. `PT1H`. */
173
319
  duration: string;
174
320
  isAllDay: boolean;
321
+ /** The physical place, a plain string. A join link into a call is a
322
+ * separate property, `virtualLocations` (#16). */
175
323
  location?: string;
324
+ /**
325
+ * Join links into a call the event is or hosts (#16, `CalendarVirtualLocation`'s
326
+ * own doc comment). Live-confirmed against Stalwart v0.16.20: the server
327
+ * round-trips this like any other property, but only when `get`'s
328
+ * `properties` names it explicitly -- omitted from an explicit list (as
329
+ * `EVENT_GET_PROPERTIES` was before this ticket), it silently drops out of
330
+ * the response even though the value is still stored, the same trap
331
+ * `wire.ts`'s header comment already logs for `recurrenceId`/`baseEventId`.
332
+ * A raw `CalendarEvent/set update` that never mentions this property, from
333
+ * this client or any other, leaves it untouched on the server.
334
+ */
335
+ virtualLocations?: readonly CalendarVirtualLocation[];
336
+ /** Links and attachments on the event (wtfalch/calendar#32,
337
+ * `CalendarLink`). Absent rather than empty when it has none. */
338
+ links?: readonly CalendarLink[];
176
339
  recurrenceRule?: CalendarRecurrenceRule;
177
340
  participants?: readonly CalendarParticipant[];
341
+ /** Reminders on this event -- a JSCalendar `alerts` map, flattened to a
342
+ * list the way `participants` already is (`wire.ts`'s `alertsToWire`
343
+ * assigns the wire's arbitrary map keys, mirroring `participantsToWire`).
344
+ * Absent rather than empty when the event has none (T15). */
345
+ alerts?: readonly CalendarAlert[];
178
346
  status: CalendarEventStatus;
347
+ /** Absent reads as `'busy'`, RFC 8984 §4.4.1's own default -- so an event
348
+ * from before this field existed, or from any other client that never
349
+ * set it, keeps counting as busy exactly as it always has
350
+ * (wtfalch/calendar#29). */
351
+ freeBusyStatus?: CalendarFreeBusyStatus;
179
352
  /** RFC 5545 `SEQUENCE`, bumped on every organizer edit an attendee's
180
353
  * client should treat as superseding its own copy. */
181
354
  sequence: number;
182
355
  /** Set only on an expanded occurrence (see above); absent on a master
183
356
  * event or a non-recurring one. */
184
357
  recurrenceId?: string;
185
- /** The master event this occurrence was expanded from, set only on an
186
- * expanded occurrence.
358
+ /** The top-level event this id traces back to: the master, on an
359
+ * expanded occurrence -- and, live-confirmed against Stalwart v0.16.20
360
+ * (wtfalch/calendar#14), a plain event's own `id` right back at itself,
361
+ * recurring or not. An earlier version of this comment claimed the field
362
+ * was absent on a master; the server sends it there too. `recurrenceId`,
363
+ * not this field, is what actually tells an occurrence from a master.
187
364
  *
188
365
  * Editing a series means addressing the master, and an occurrence's own
189
366
  * `id` is synthetic, so without this an editor can change one occurrence
@@ -209,6 +386,53 @@ export type AvailabilityPeriod = {
209
386
  end: string;
210
387
  busyStatus: CalendarBusyStatus;
211
388
  };
389
+ /**
390
+ * One principal's answer from `getAvailability`, distinguishing a real read
391
+ * from the one thing the wire cannot say by itself.
392
+ *
393
+ * `Principal/getAvailability` answers `{"list": []}` for three different
394
+ * truths — never shared, shared then revoked, and shared but genuinely free
395
+ * (`.plans/msg-055-slice-4-freebusy.md`, live-confirmed against Stalwart
396
+ * v0.16.20) — so an empty list is folded into `'unknown'` here rather than
397
+ * surfaced as `'known'` with zero periods. `'known'` means real periods came
398
+ * back; `'unknown'` is the only honest reading of everything else, including
399
+ * a request that failed outright for that one principal (issue #13).
400
+ */
401
+ export type AvailabilityResult = {
402
+ readonly kind: 'known';
403
+ readonly periods: readonly AvailabilityPeriod[];
404
+ } | {
405
+ readonly kind: 'unknown';
406
+ };
407
+ /**
408
+ * `findTime`'s answer: where every *known* principal is free, and who could
409
+ * not be read at all.
410
+ *
411
+ * `slots` never assumes an unknown principal is free — it is computed from
412
+ * `known` answers only — so `unknown` travels alongside it rather than being
413
+ * folded away. A caller that drops `unknown` on the floor is a caller that
414
+ * can book over somebody it never actually saw (issue #13; the same rule
415
+ * `AvailabilityResult`'s doc comment states for one principal).
416
+ */
417
+ export type FindTimeResult = {
418
+ readonly slots: readonly CalendarRange[];
419
+ readonly unknown: readonly string[];
420
+ };
421
+ /**
422
+ * One principal's own working day, for `findTime`'s per-attendee
423
+ * `options.workingHours` (wtfalch/calendar#31). `timeZone` is an IANA name
424
+ * ("America/New_York") -- this package still expands no rule and now
425
+ * converts no wall-clock time it was not explicitly given one for, but a
426
+ * caller that *does* know a participant's zone (from their own directory,
427
+ * a browser `Intl` read, wherever) can finally hand it in. `startHour`/
428
+ * `endHour` are local hours, `0`-`23`, defaulting to `9`/`17` -- the same
429
+ * bound `findTime` used uniformly before this option existed.
430
+ */
431
+ export type WorkingHours = {
432
+ timeZone: string;
433
+ startHour?: number;
434
+ endHour?: number;
435
+ };
212
436
  /** The per-type state strings a push event carries, mirroring
213
437
  * `@wtfalch/email/mailbox`'s `ChangedState` for the four calendar-shaped
214
438
  * `DataType`s Stalwart pushes over EventSource/WebSocket: `Calendar`,
@@ -236,6 +460,30 @@ export type CalendarSubscription = {
236
460
  export type SchedulingOptions = {
237
461
  sendSchedulingMessages?: boolean;
238
462
  };
463
+ /**
464
+ * Which occurrences of a recurring event `updateEvent`/`deleteEvent` reach --
465
+ * the question every calendar UI asks the moment somebody edits a repeating
466
+ * event (wtfalch/calendar#14). `'occurrence'` and `'series'` were already
467
+ * reachable before this option existed: a synthetic occurrence id already
468
+ * wrote a single occurrence, a master's own id already wrote the whole
469
+ * series. `'following'` is the one JMAP has no verb for at all -- see
470
+ * `calendar-client.ts`'s `splitFollowing` for how it is built out of a rule
471
+ * truncation and a new event, both live-confirmed against Stalwart v0.16.20.
472
+ */
473
+ export type RecurrenceScope = 'occurrence' | 'following' | 'series';
474
+ /**
475
+ * `updateEvent`/`deleteEvent`'s own scope option, separate from
476
+ * `SchedulingOptions` because `createEvent` takes the latter but has no
477
+ * occurrence to scope a write to.
478
+ */
479
+ export type RecurrenceScopeOptions = {
480
+ /** Omitted, a write lands on whatever `id` was given, exactly as it did
481
+ * before this option existed -- a synthetic occurrence id already wrote
482
+ * an occurrence-scoped change, a master id already wrote the whole
483
+ * series, so the default keeps every existing caller's behaviour
484
+ * unchanged (wtfalch/calendar#14). */
485
+ scope?: RecurrenceScope;
486
+ };
239
487
  /** Who the person holding a connection is, for telling their own participant
240
488
  * row from everyone else's. `calendarAddress` is bare here — no `mailto:`
241
489
  * scheme — because that is how the session document writes it. */
@@ -255,6 +503,22 @@ export type CalendarRange = {
255
503
  after: string;
256
504
  before: string;
257
505
  };
506
+ /**
507
+ * What `searchEvents` takes beyond the query string.
508
+ *
509
+ * `range` is optional here, unlike every other listing method's -- the whole
510
+ * point of the ticket (wtfalch/calendar#17,
511
+ * https://github.com/wtfalch/calendar/issues/17) is answering a search
512
+ * across a person's calendars with no range named, the gap Agora's combined
513
+ * Mail/Chat/Calendar search hit (agora#216,
514
+ * https://github.com/wtfalch/agora/issues/216): `listEvents(range)` forced
515
+ * the caller to guess a range and filter client-side, silently missing a
516
+ * match outside whatever range happened to be loaded.
517
+ */
518
+ export type SearchOptions = {
519
+ range?: CalendarRange;
520
+ limit?: number;
521
+ };
258
522
  /**
259
523
  * A connection to one JMAP calendars account.
260
524
  *
@@ -283,10 +547,67 @@ export interface CalendarClient {
283
547
  listCalendars(): Promise<readonly Calendar[]>;
284
548
  /** Every occurrence in `range`, recurring events expanded server-side. */
285
549
  listEvents(range: CalendarRange): Promise<readonly CalendarEvent[]>;
550
+ /**
551
+ * One query across every calendar this account holds, for Agora's combined
552
+ * Mail/Chat/Calendar search (wtfalch/calendar#17; agora#216). Matches on
553
+ * the wire's own `text` filter, which a live Stalwart v0.16.20 searches
554
+ * across both `title` and `description` in one pass, case-insensitively --
555
+ * a single filter, not two ORed together (live-confirmed 2026-09-21, see
556
+ * `calendar-client.ts`'s `searchEvents`).
557
+ *
558
+ * `options.range` given: sent as `expandRecurrences: true` with
559
+ * `filter.after`/`filter.before`, exactly like `listEvents`, so a matching
560
+ * recurring event comes back as its dated occurrences. `options.range`
561
+ * omitted: the server refuses to expand recurrences with no bounds at all
562
+ * (`invalidArguments`, live-confirmed), so a matching recurring event comes
563
+ * back as its single master id instead -- the same fallback
564
+ * `CalendarEvent/query` itself uses for any other unexpanded query.
565
+ */
566
+ searchEvents(query: string, options?: SearchOptions): Promise<readonly CalendarEvent[]>;
286
567
  getEvent(id: string): Promise<CalendarEvent>;
287
568
  createEvent(calendarId: string, event: CalendarEventDraft, options?: SchedulingOptions): Promise<CalendarEvent>;
288
- updateEvent(id: string, patch: Partial<CalendarEventDraft>, options?: SchedulingOptions): Promise<CalendarEvent>;
289
- deleteEvent(id: string, options?: SchedulingOptions): Promise<void>;
569
+ /**
570
+ * `options.scope` picks which occurrences of a recurring event this
571
+ * reaches -- see `RecurrenceScope`. `'following'` returns the new series'
572
+ * own event, the one that now carries the change from `id`'s occurrence
573
+ * onward, since the id the caller passed in stops being useful the moment
574
+ * its series ends there.
575
+ *
576
+ * **An expanded occurrence's id is positional, not stable.** It names a
577
+ * slot in the last listing's own order, not a fixed identity for that
578
+ * date -- live-confirmed against Stalwart v0.16.20 (wtfalch/calendar#14):
579
+ * a write here that adds or removes an occurrence (an 'occurrence'-scope
580
+ * edit or delete, a 'following' split) renumbers every later occurrence's
581
+ * own id on the next expansion. An id held across two writes can silently
582
+ * name a different occurrence on the second one. Re-list (`listEvents`)
583
+ * before reusing an id this method, or `deleteEvent`, has just touched.
584
+ */
585
+ updateEvent(id: string, patch: Partial<CalendarEventDraft>, options?: SchedulingOptions & RecurrenceScopeOptions): Promise<CalendarEvent>;
586
+ /** `options.scope` picks which occurrences of a recurring event this
587
+ * reaches -- see `RecurrenceScope`. `'following'` deletes nothing on its
588
+ * own id; it only truncates the series before it (`RecurrenceScope`'s own
589
+ * doc comment).
590
+ *
591
+ * Shares `updateEvent`'s own warning: an expanded occurrence's id is
592
+ * positional, not stable, so a write here can renumber every later
593
+ * occurrence's own id -- re-list before reusing one. */
594
+ deleteEvent(id: string, options?: SchedulingOptions & RecurrenceScopeOptions): Promise<void>;
595
+ /**
596
+ * Reply to an invite: accept, decline or answer tentatively.
597
+ *
598
+ * An iTIP REPLY against the caller's own copy of the event -- never
599
+ * `updateEvent`, the organiser's verb (#11: "`updateEvent` patches the
600
+ * event -- which is the organiser's verb, not a guest's"). It patches only
601
+ * the caller's own participant entry, found by address rather than by a
602
+ * wire map key the caller was never given, and it bumps nothing: a real
603
+ * Stalwart v0.16.20 reply left `sequence` unchanged on the replier's own
604
+ * copy while the organiser's copy of `participationStatus` updated on its
605
+ * own, with no separate write on the organiser's side (T11 live capture,
606
+ * `wire-live-transcript.test.ts`).
607
+ */
608
+ respond(eventId: string, status: CalendarParticipationStatus, options?: SchedulingOptions & {
609
+ comment?: string;
610
+ }): Promise<void>;
290
611
  /** Add or replace one grant in a calendar's `shareWith` ACL. A person
291
612
  * shares their own calendar directly; this never touches authz (plan
292
613
  * §5). */
@@ -306,10 +627,39 @@ export interface CalendarClient {
306
627
  * empty rights object for the grantee, not remove them; this instead
307
628
  * deletes the `shareWith` key outright (MSG-055 slice 3 plan). */
308
629
  unshareCalendar(calendarId: string, accountId: string): Promise<void>;
309
- /** A person's busy periods over `range`, gated by the ACL share alone —
310
- * see `AvailabilityPeriod`'s doc comment for the empty-result rule
311
- * (plan §5; #137 "Free/busy"). */
312
- getAvailability(principalId: string, range: CalendarRange): Promise<readonly AvailabilityPeriod[]>;
630
+ /**
631
+ * Every named principal's busy periods over `range`, one JMAP request no
632
+ * matter how many principals — `Principal/getAvailability` batches like
633
+ * any other JMAP method call (RFC 8620 §3.3), measured live for issue #13.
634
+ * See `AvailabilityResult`'s doc comment for what a missing share reads as.
635
+ *
636
+ * Used to take one `principalId` and return its periods directly; every
637
+ * caller needed the same "an empty answer is not free" reading in the end,
638
+ * so the many-principal shape replaced it rather than sitting beside it —
639
+ * `AvailabilityRibbon`'s own lookup now asks for every participant at once
640
+ * (issue #13 Decision).
641
+ */
642
+ getAvailability(principalIds: readonly string[], range: CalendarRange): Promise<ReadonlyMap<string, AvailabilityResult>>;
643
+ /**
644
+ * Slots at least `duration` long where every principal `getAvailability`
645
+ * could read is free — never one it could not see, which is what
646
+ * `FindTimeResult.unknown` is for.
647
+ *
648
+ * `options.workingHours` clips candidate slots to a working day:
649
+ * `true` clips uniformly to 09:00-17:00 UTC on each day of `range`, the
650
+ * one timezone every busy period already arrives in (issue #13's original
651
+ * Decision, kept for a caller with no per-principal data). A map keyed by
652
+ * principal id instead clips *that* principal to *their own* zone and
653
+ * hours (wtfalch/calendar#31) — a slot must fall inside every named
654
+ * principal's own working day, not just one shared window, which is what
655
+ * stops a multi-timezone team from being proposed a meeting at 2am local
656
+ * for half the invitees. A principal in `principalIds` but absent from the
657
+ * map falls back to the uniform 09:00-17:00 UTC window, the same as
658
+ * `true`.
659
+ */
660
+ findTime(principalIds: readonly string[], range: CalendarRange, duration: string, options?: {
661
+ workingHours?: boolean | ReadonlyMap<string, WorkingHours>;
662
+ }): Promise<FindTimeResult>;
313
663
  /** Watch for changes on the account. The connection reconnects on its own
314
664
  * with a backoff; only `close()` needs calling when done, mirroring
315
665
  * `@wtfalch/email/mailbox/push.ts`'s `push()`. */