@wtfalch/calendar 0.1.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 (42) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +15 -0
  3. package/dist/calendar/calendar-client.d.ts +7 -0
  4. package/dist/calendar/calendar-client.js +242 -0
  5. package/dist/calendar/calendar.css +953 -0
  6. package/dist/calendar/client.d.ts +87 -0
  7. package/dist/calendar/client.js +233 -0
  8. package/dist/calendar/errors.d.ts +28 -0
  9. package/dist/calendar/errors.js +61 -0
  10. package/dist/calendar/fake/index.d.ts +36 -0
  11. package/dist/calendar/fake/index.js +79 -0
  12. package/dist/calendar/fake/sample.d.ts +66 -0
  13. package/dist/calendar/fake/sample.js +116 -0
  14. package/dist/calendar/fake/store.d.ts +79 -0
  15. package/dist/calendar/fake/store.js +906 -0
  16. package/dist/calendar/index.d.ts +12 -0
  17. package/dist/calendar/index.js +11 -0
  18. package/dist/calendar/push.d.ts +38 -0
  19. package/dist/calendar/push.js +129 -0
  20. package/dist/calendar/react/AvailabilityRibbon.d.ts +40 -0
  21. package/dist/calendar/react/AvailabilityRibbon.js +108 -0
  22. package/dist/calendar/react/Calendar.d.ts +28 -0
  23. package/dist/calendar/react/Calendar.js +431 -0
  24. package/dist/calendar/react/EventDetail.d.ts +22 -0
  25. package/dist/calendar/react/EventDetail.js +91 -0
  26. package/dist/calendar/react/EventEditor.d.ts +52 -0
  27. package/dist/calendar/react/EventEditor.js +188 -0
  28. package/dist/calendar/react/ShareDialog.d.ts +25 -0
  29. package/dist/calendar/react/ShareDialog.js +125 -0
  30. package/dist/calendar/react/Toolbar.d.ts +29 -0
  31. package/dist/calendar/react/Toolbar.js +58 -0
  32. package/dist/calendar/react/index.d.ts +9 -0
  33. package/dist/calendar/react/index.js +8 -0
  34. package/dist/calendar/react/participants.d.ts +34 -0
  35. package/dist/calendar/react/participants.js +40 -0
  36. package/dist/calendar/types.d.ts +384 -0
  37. package/dist/calendar/types.js +40 -0
  38. package/dist/calendar/uri.d.ts +13 -0
  39. package/dist/calendar/uri.js +22 -0
  40. package/dist/calendar/wire.d.ts +177 -0
  41. package/dist/calendar/wire.js +349 -0
  42. package/package.json +82 -0
@@ -0,0 +1,12 @@
1
+ /**
2
+ * `@wtfalch/calendar/calendar` — a JMAP calendar client core.
3
+ *
4
+ * Session negotiation and the SSE push loop are copied from
5
+ * `@wtfalch/email/mailbox`'s `client.ts`/`push.ts`, swapping the capability
6
+ * constant to `urn:ietf:params:jmap:calendars` — not imported, so this
7
+ * package carries no runtime dependency on `@wtfalch/email` (plan §7; MSG-053
8
+ * acceptance criteria). The JMAP wire stays behind the client.
9
+ */
10
+ export { createCalendarClient } from './calendar-client.ts';
11
+ 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';
@@ -0,0 +1,11 @@
1
+ /**
2
+ * `@wtfalch/calendar/calendar` — a JMAP calendar client core.
3
+ *
4
+ * Session negotiation and the SSE push loop are copied from
5
+ * `@wtfalch/email/mailbox`'s `client.ts`/`push.ts`, swapping the capability
6
+ * constant to `urn:ietf:params:jmap:calendars` — not imported, so this
7
+ * package carries no runtime dependency on `@wtfalch/email` (plan §7; MSG-053
8
+ * acceptance criteria). The JMAP wire stays behind the client.
9
+ */
10
+ export { createCalendarClient } from "./calendar-client.js";
11
+ export { CalendarError } from "./types.js";
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Push, as server-sent events. Copied from `@wtfalch/email/mailbox/push.ts`
3
+ * (plan §7; MSG-053 acceptance criteria), unchanged but for the types it
4
+ * carries (`CalendarChangedState`/`CalendarSubscription` in place of
5
+ * `ChangedState`/`PushHandle`) and asking `CalendarConnection` for a fresh
6
+ * `Authorization` header on every (re)connect, matching this package's
7
+ * "the token is never cached" rule (`client.ts`).
8
+ *
9
+ * RFC 8620 §7.3 puts the event source behind the same authentication as the
10
+ * API, and the browser `EventSource` cannot send an `Authorization` header --
11
+ * it has no way to set headers at all. So the stream is read with `fetch`,
12
+ * which takes the same header every other request carries, and the handful
13
+ * of lines of SSE framing are parsed here. This works unchanged in a browser
14
+ * and in Node.
15
+ */
16
+ import type { CalendarConnection } from './client.ts';
17
+ import type { CalendarChangedState, CalendarSubscription } from './types.ts';
18
+ export type PushOptions = {
19
+ /** Which types to be told about. `*` is everything. */
20
+ types?: readonly string[] | '*';
21
+ /** Seconds between the server's keep-alive pings. */
22
+ ping?: number;
23
+ /** Called when the connection drops and again when it comes back, so a UI
24
+ * can say it is stale. */
25
+ onConnectionChange?: (connected: boolean) => void;
26
+ /** Called for an error that did not stop the retry loop. */
27
+ onError?: (error: unknown) => void;
28
+ };
29
+ /**
30
+ * Watch for changes on the account.
31
+ *
32
+ * `handler` is called with the changed state strings for this account; a
33
+ * value that differs from the one a previous read returned means that type
34
+ * has changed and its list should be refetched. The stream reconnects on its
35
+ * own with a backoff, so the handle only has to be closed when the caller is
36
+ * finished with it.
37
+ */
38
+ export declare function push(connection: CalendarConnection, handler: (changed: CalendarChangedState) => void, options?: PushOptions): CalendarSubscription;
@@ -0,0 +1,129 @@
1
+ /**
2
+ * Push, as server-sent events. Copied from `@wtfalch/email/mailbox/push.ts`
3
+ * (plan §7; MSG-053 acceptance criteria), unchanged but for the types it
4
+ * carries (`CalendarChangedState`/`CalendarSubscription` in place of
5
+ * `ChangedState`/`PushHandle`) and asking `CalendarConnection` for a fresh
6
+ * `Authorization` header on every (re)connect, matching this package's
7
+ * "the token is never cached" rule (`client.ts`).
8
+ *
9
+ * RFC 8620 §7.3 puts the event source behind the same authentication as the
10
+ * API, and the browser `EventSource` cannot send an `Authorization` header --
11
+ * it has no way to set headers at all. So the stream is read with `fetch`,
12
+ * which takes the same header every other request carries, and the handful
13
+ * of lines of SSE framing are parsed here. This works unchanged in a browser
14
+ * and in Node.
15
+ */
16
+ const FRAME_SEPARATOR = /\r?\n\r?\n/;
17
+ const RETRY_START_MS = 1_000;
18
+ const RETRY_CAP_MS = 30_000;
19
+ /** Parse one SSE frame's field lines into an event. */
20
+ function parseFrame(frame) {
21
+ let event = 'message';
22
+ let id = null;
23
+ const data = [];
24
+ // A stream may use CR, LF or CRLF line endings, so splitting on '\n' alone
25
+ // leaves a trailing '\r' on every field value and `event` stops matching.
26
+ for (const line of frame.split(/\r\n|\r|\n/)) {
27
+ if (line === '' || line.startsWith(':'))
28
+ continue;
29
+ const colon = line.indexOf(':');
30
+ const field = colon === -1 ? line : line.slice(0, colon);
31
+ // "If the line starts with a colon the field value is the rest of the
32
+ // line after the colon, with one leading space removed."
33
+ let value = colon === -1 ? '' : line.slice(colon + 1);
34
+ if (value.startsWith(' '))
35
+ value = value.slice(1);
36
+ if (field === 'event')
37
+ event = value;
38
+ else if (field === 'data')
39
+ data.push(value);
40
+ else if (field === 'id')
41
+ id = value;
42
+ }
43
+ return { event, data: data.join('\n'), id };
44
+ }
45
+ /**
46
+ * Watch for changes on the account.
47
+ *
48
+ * `handler` is called with the changed state strings for this account; a
49
+ * value that differs from the one a previous read returned means that type
50
+ * has changed and its list should be refetched. The stream reconnects on its
51
+ * own with a backoff, so the handle only has to be closed when the caller is
52
+ * finished with it.
53
+ */
54
+ export function push(connection, handler, options = {}) {
55
+ const controller = new AbortController();
56
+ const types = options.types === undefined || options.types === '*' ? '*' : options.types.join(',');
57
+ const ping = options.ping ?? 30;
58
+ let stopped = false;
59
+ let lastEventId = null;
60
+ const loop = async () => {
61
+ let delay = RETRY_START_MS;
62
+ while (!stopped) {
63
+ try {
64
+ const accountId = await connection.accountId();
65
+ const url = await connection.eventSourceUrl({ types, ping });
66
+ const headers = {
67
+ Authorization: await connection.authorization(),
68
+ Accept: 'text/event-stream',
69
+ };
70
+ if (lastEventId !== null)
71
+ headers['Last-Event-ID'] = lastEventId;
72
+ const response = await fetch(url, { headers, signal: controller.signal });
73
+ if (!response.ok || !response.body) {
74
+ throw new Error(`the event source answered ${response.status}`);
75
+ }
76
+ options.onConnectionChange?.(true);
77
+ delay = RETRY_START_MS;
78
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
79
+ let buffer = '';
80
+ while (!stopped) {
81
+ const { done, value } = await reader.read();
82
+ if (done)
83
+ break;
84
+ buffer += value;
85
+ // Frames are separated by a blank line; \r\n is as legal as \n.
86
+ let boundary = FRAME_SEPARATOR.exec(buffer);
87
+ while (boundary !== null) {
88
+ const frame = buffer.slice(0, boundary.index);
89
+ buffer = buffer.slice(boundary.index + boundary[0].length);
90
+ const parsed = parseFrame(frame);
91
+ if (parsed.id !== null)
92
+ lastEventId = parsed.id;
93
+ if (parsed.event === 'state' && parsed.data !== '') {
94
+ try {
95
+ const change = JSON.parse(parsed.data);
96
+ const mine = change.changed?.[accountId];
97
+ if (mine)
98
+ handler(mine);
99
+ }
100
+ catch (error) {
101
+ // One malformed frame is not a reason to drop the stream.
102
+ options.onError?.(error);
103
+ }
104
+ }
105
+ boundary = FRAME_SEPARATOR.exec(buffer);
106
+ }
107
+ }
108
+ await reader.cancel().catch(() => { });
109
+ }
110
+ catch (error) {
111
+ if (stopped || controller.signal.aborted)
112
+ return;
113
+ options.onError?.(error);
114
+ }
115
+ if (stopped)
116
+ return;
117
+ options.onConnectionChange?.(false);
118
+ await new Promise((resolve) => setTimeout(resolve, delay));
119
+ delay = Math.min(delay * 2, RETRY_CAP_MS);
120
+ }
121
+ };
122
+ void loop();
123
+ return {
124
+ close: () => {
125
+ stopped = true;
126
+ controller.abort();
127
+ },
128
+ };
129
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * The availability ribbon: each participant's day, drawn beneath the time row.
3
+ *
4
+ * The signature interaction of this component, and the reason the editor is
5
+ * the product rather than the grid. Picking a slot and checking a slot are one
6
+ * act: the event's own block is a cursor lying across every ribbon at once, so
7
+ * the cost of a time is read in a glance rather than in a scheduling tab
8
+ * nobody opens.
9
+ *
10
+ * **Three readings, and the third is not optional.** Solid is busy, open is
11
+ * free, hatched is unknown — and hatched carries the word, because a band that
12
+ * only *looks* different is a band somebody will read as free.
13
+ *
14
+ * The third reading exists because the server cannot tell us apart what we
15
+ * would need it to. `Principal/getAvailability` answers `{"list": []}` to all
16
+ * three of: never shared with you, shared then revoked, and shared but
17
+ * genuinely free. The JMAP session does not rescue it either — a colleague who
18
+ * shared at the "busy times" level never appears in the session's accounts
19
+ * map, so the session would report "not shared" for exactly the person who
20
+ * did. Both measured against Stalwart v0.16.20 and pinned in
21
+ * `wire-live-transcript.test.ts`.
22
+ *
23
+ * So an empty answer is drawn as unknown, never as free. A hatched ribbon
24
+ * never blocks the choice and never counts as a conflict; it only says the
25
+ * person cannot be seen.
26
+ */
27
+ import type { AvailabilityPeriod, CalendarParticipant } from '../types.ts';
28
+ export type AvailabilityLookup = (addresses: readonly string[], day: Date) => Promise<ReadonlyMap<string, readonly AvailabilityPeriod[] | undefined>>;
29
+ export type AvailabilityRibbonProps = {
30
+ participants: readonly CalendarParticipant[];
31
+ /** The event's own slot, drawn as the cursor across every ribbon. */
32
+ start: Date;
33
+ durationMinutes: number;
34
+ /** Absent when the surrounding app gave no way to ask. The ribbon then does
35
+ * not render at all, rather than drawing every band as unknown — a screen
36
+ * full of hatching says something about the colleagues, and this would be
37
+ * saying it about ourselves. */
38
+ lookup?: AvailabilityLookup;
39
+ };
40
+ export declare function AvailabilityRibbon({ participants, start, durationMinutes, lookup, }: AvailabilityRibbonProps): import("react").JSX.Element | null;
@@ -0,0 +1,108 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ /**
3
+ * The availability ribbon: each participant's day, drawn beneath the time row.
4
+ *
5
+ * The signature interaction of this component, and the reason the editor is
6
+ * the product rather than the grid. Picking a slot and checking a slot are one
7
+ * act: the event's own block is a cursor lying across every ribbon at once, so
8
+ * the cost of a time is read in a glance rather than in a scheduling tab
9
+ * nobody opens.
10
+ *
11
+ * **Three readings, and the third is not optional.** Solid is busy, open is
12
+ * free, hatched is unknown — and hatched carries the word, because a band that
13
+ * only *looks* different is a band somebody will read as free.
14
+ *
15
+ * The third reading exists because the server cannot tell us apart what we
16
+ * would need it to. `Principal/getAvailability` answers `{"list": []}` to all
17
+ * three of: never shared with you, shared then revoked, and shared but
18
+ * genuinely free. The JMAP session does not rescue it either — a colleague who
19
+ * shared at the "busy times" level never appears in the session's accounts
20
+ * map, so the session would report "not shared" for exactly the person who
21
+ * did. Both measured against Stalwart v0.16.20 and pinned in
22
+ * `wire-live-transcript.test.ts`.
23
+ *
24
+ * So an empty answer is drawn as unknown, never as free. A hatched ribbon
25
+ * never blocks the choice and never counts as a conflict; it only says the
26
+ * person cannot be seen.
27
+ */
28
+ import { useEffect, useMemo, useState } from 'react';
29
+ import { addressOf } from "./participants.js";
30
+ /** The window a ribbon covers: a working day, not twenty-four hours. A band
31
+ * that spends a third of its width on the small hours wastes the width that
32
+ * makes a busy block readable. */
33
+ const FIRST_HOUR = 7;
34
+ const LAST_HOUR = 21;
35
+ const SPAN_HOURS = LAST_HOUR - FIRST_HOUR;
36
+ /** Where an instant falls across the band, 0 to 1, clamped to its ends. */
37
+ function fractionOf(when, day) {
38
+ const dayStart = new Date(day);
39
+ dayStart.setHours(FIRST_HOUR, 0, 0, 0);
40
+ const hours = (when.getTime() - dayStart.getTime()) / 3_600_000;
41
+ return Math.min(1, Math.max(0, hours / SPAN_HOURS));
42
+ }
43
+ /** One busy period as a percentage box, or nothing when it misses the window
44
+ * entirely — a meeting at 04:00 is real but not on this band. */
45
+ function boxFor(period, day) {
46
+ const from = fractionOf(new Date(period.start), day);
47
+ const to = fractionOf(new Date(period.end), day);
48
+ if (to <= from)
49
+ return null;
50
+ return { left: from * 100, width: (to - from) * 100 };
51
+ }
52
+ export function AvailabilityRibbon({ participants, start, durationMinutes, lookup, }) {
53
+ const [known, setKnown] = useState(null);
54
+ /** The effect must key off values, not the arrays and dates rebuilt on
55
+ * every keystroke -- depending on those re-ran the fetch, which set state,
56
+ * which re-rendered, which re-ran the fetch. The first build did exactly
57
+ * that and hung four existing tests. */
58
+ const addressKey = participants.map(addressOf).join(',');
59
+ const addresses = useMemo(() => (addressKey === '' ? [] : addressKey.split(',')), [addressKey]);
60
+ const dayStamp = useMemo(() => {
61
+ const day = new Date(start);
62
+ day.setHours(0, 0, 0, 0);
63
+ return day.getTime();
64
+ }, [start]);
65
+ useEffect(() => {
66
+ if (!lookup || addresses.length === 0) {
67
+ setKnown(null);
68
+ return;
69
+ }
70
+ let live = true;
71
+ // A failure is not an error to show here: it is one more way of not being
72
+ // able to see somebody, which the band already has a reading for.
73
+ lookup(addresses, new Date(dayStamp)).then((answer) => {
74
+ if (live)
75
+ setKnown(answer);
76
+ }, () => {
77
+ if (live)
78
+ setKnown(new Map());
79
+ });
80
+ return () => {
81
+ live = false;
82
+ };
83
+ }, [addresses, dayStamp, lookup]);
84
+ if (!lookup || participants.length === 0)
85
+ return null;
86
+ const cursorLeft = fractionOf(start, start) * 100;
87
+ const cursorEnd = new Date(start.getTime() + durationMinutes * 60_000);
88
+ const cursorWidth = Math.max(1, fractionOf(cursorEnd, start) * 100 - cursorLeft);
89
+ return (_jsxs("section", { className: "wtcal-ribbons", "aria-label": "When these people are busy", children: [_jsx("div", { className: "wtcal-ribbon-hours", "aria-hidden": "true", children: [9, 12, 15, 18].map((hour) => (_jsx("span", { className: "wtcal-ribbon-hour", style: { left: `${((hour - FIRST_HOUR) / SPAN_HOURS) * 100}%` }, children: hour }, hour))) }), participants.map((person) => {
90
+ const address = addressOf(person);
91
+ const periods = known?.get(address);
92
+ // Undefined while the answer is still coming, and empty once it has
93
+ // arrived saying nothing. Both are drawn as unknown, because both are.
94
+ const unknown = periods === undefined || periods.length === 0;
95
+ return (_jsxs("div", { className: "wtcal-ribbon-row", children: [_jsx("span", { className: "wtcal-ribbon-who", title: address, children: person.name ?? address }), _jsxs("div", { className: unknown ? 'wtcal-ribbon is-unknown' : 'wtcal-ribbon', role: "img", "aria-label": unknown
96
+ ? `${person.name ?? address}: not shared, so their time cannot be seen`
97
+ : `${person.name ?? address}: ${periods.length} busy ${periods.length === 1 ? 'period' : 'periods'} this day`, children: [unknown ? (
98
+ // The word rides on the band. A hatch alone is a texture, and
99
+ // a texture is something a person decides for themselves --
100
+ // the texture says "different", the word says which way.
101
+ _jsx("span", { className: "wtcal-ribbon-word", children: "not shared" })) : (periods.map((period) => {
102
+ const box = boxFor(period, start);
103
+ if (!box)
104
+ return null;
105
+ return (_jsx("span", { className: "wtcal-ribbon-busy", style: { left: `${box.left}%`, width: `${box.width}%` } }, `${period.start}-${period.end}`));
106
+ })), _jsx("span", { className: "wtcal-ribbon-cursor", style: { left: `${cursorLeft}%`, width: `${cursorWidth}%` } })] })] }, address));
107
+ })] }));
108
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * `Calendar` — a month, week, day or agenda view on react-big-calendar,
3
+ * driven by `CalendarProps.location` and fetching through `CalendarProps.client`.
4
+ *
5
+ * MSG-055 (https://github.com/wtfalch/messaging/issues/158) turned MSG-053's
6
+ * shell into the first of the four first-ship features: a person's own events,
7
+ * created, edited and deleted here, recurring included. The direction this
8
+ * builds to is recorded in
9
+ * `.impeccable/surfaces/src-calendar-react-calendar-tsx.md`.
10
+ *
11
+ * **The grid is the map and the pane is the decision.** Selecting an event
12
+ * opens a pane beside the grid rather than a dialog over it, because deciding
13
+ * what to do about a meeting means looking at the week around it, and a dialog
14
+ * covers exactly that. Below the design system's `medium` breakpoint there is
15
+ * no week to look at, so the pane becomes a bottom sheet instead.
16
+ *
17
+ * The controlled/uncontrolled seam `Mail.tsx`
18
+ * (`packages/email/src/mailbox/react/Mail.tsx:69-106` on `email`'s
19
+ * `origin/main`) set for `location`/`onNavigate` is unchanged.
20
+ *
21
+ * No Agora code: only `react`, `react-big-calendar`, `dayjs` (its bundled
22
+ * localizer, already a dependency of `react-big-calendar` itself),
23
+ * `@wtfalch/design` for the component vocabulary — an optional peer, exactly
24
+ * as `@wtfalch/email`'s own `Mail` declares it — and this package's own
25
+ * `../types.ts`/`../wire.ts`.
26
+ */
27
+ import type { CalendarProps } from '../types.ts';
28
+ export declare function Calendar({ client, location, onNavigate, account, onError, now, className, }: CalendarProps): import("react").JSX.Element;