@moltenship/calendar 1.0.0-rc.2 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/README.md +27 -6
  2. package/dist/index.d.mts +3 -3
  3. package/dist/index.mjs +2 -2
  4. package/docs/accessibility.md +305 -0
  5. package/docs/agents/changes.md +449 -0
  6. package/docs/agents/coding-agents.md +116 -0
  7. package/docs/agents/connect.md +444 -0
  8. package/docs/agents/deleting.md +296 -0
  9. package/docs/agents/reference.md +511 -0
  10. package/docs/agents/server.md +317 -0
  11. package/docs/agents/webmcp.md +153 -0
  12. package/docs/agents.md +355 -0
  13. package/docs/annotations.md +198 -0
  14. package/docs/api/changes.md +264 -0
  15. package/docs/api/components.md +245 -0
  16. package/docs/api/dnd-kit.md +265 -0
  17. package/docs/api/events.md +153 -0
  18. package/docs/api/primitives.md +218 -0
  19. package/docs/api/store.md +92 -0
  20. package/docs/api.md +57 -0
  21. package/docs/availability.md +576 -0
  22. package/docs/comparison.md +278 -0
  23. package/docs/concepts/anatomy.md +73 -0
  24. package/docs/concepts/events.md +163 -0
  25. package/docs/concepts/how-it-works.md +112 -0
  26. package/docs/concepts/state.md +244 -0
  27. package/docs/concepts/time.md +168 -0
  28. package/docs/customization.md +271 -0
  29. package/docs/frameworks.md +116 -0
  30. package/docs/guides/dnd-kit.md +333 -0
  31. package/docs/guides/google-calendar-sync.md +1246 -0
  32. package/docs/guides/google-calendar.md +367 -0
  33. package/docs/guides/motion.md +414 -0
  34. package/docs/guides/nextjs-app-router.md +630 -0
  35. package/docs/guides/nextjs.md +149 -0
  36. package/docs/guides/performance.md +103 -0
  37. package/docs/guides/tanstack-query.md +485 -0
  38. package/docs/ics/feed.md +484 -0
  39. package/docs/ics/import.md +183 -0
  40. package/docs/ics/reference.md +482 -0
  41. package/docs/ics.md +142 -0
  42. package/docs/index.md +149 -0
  43. package/docs/installation.md +209 -0
  44. package/docs/interactions.md +441 -0
  45. package/docs/llms.txt +99 -0
  46. package/docs/migrating-to-2.md +497 -0
  47. package/docs/quick-start.md +163 -0
  48. package/docs/recurrence/calendar.md +598 -0
  49. package/docs/recurrence/model.md +128 -0
  50. package/docs/recurrence/reference.md +547 -0
  51. package/docs/recurrence.md +122 -0
  52. package/docs/stylex.md +290 -0
  53. package/docs/temporal/daylight-saving-time.md +172 -0
  54. package/docs/temporal/month-grid.md +119 -0
  55. package/docs/temporal/reference.md +167 -0
  56. package/docs/temporal.md +105 -0
  57. package/docs/testing.md +600 -0
  58. package/docs/theme-builder.md +82 -0
  59. package/docs/theming.md +275 -0
  60. package/docs/undo-redo.md +347 -0
  61. package/docs/views/agenda.md +222 -0
  62. package/docs/views/custom-views.md +195 -0
  63. package/docs/views/month.md +110 -0
  64. package/docs/views/resource-columns.md +265 -0
  65. package/docs/views/resource-timeline.md +226 -0
  66. package/docs/views/scrolling.md +193 -0
  67. package/docs/views/week-and-day.md +258 -0
  68. package/docs/views/year.md +138 -0
  69. package/docs/views.md +69 -0
  70. package/package.json +42 -14
  71. package/skills/moltenship-time/SKILL.md +77 -0
  72. package/skills/moltenship-time/references/agent-ready.md +272 -0
  73. package/skills/moltenship-time/references/changes.md +188 -0
  74. package/skills/moltenship-time/references/compose.md +175 -0
  75. package/skills/moltenship-time/references/mistakes.md +100 -0
  76. package/skills/moltenship-time/references/solid.md +213 -0
  77. package/skills/moltenship-time/references/state.md +129 -0
  78. package/skills/moltenship-time/references/testing.md +176 -0
@@ -0,0 +1,265 @@
1
+ # dnd-kit adapter
2
+
3
+ Drag your own dnd-kit items into the calendar, and calendar events out to your droppables, with @moltenship/calendar-dnd-kit.
4
+
5
+ Source: https://time.molten.sh/docs/react/api/dnd-kit
6
+
7
+ `@moltenship/calendar-dnd-kit` connects the calendar to [dnd-kit](https://dndkit.com), for apps
8
+ that already use it:
9
+
10
+ - **Drag your items in.** A task, or anything else you make draggable, becomes an event when it's
11
+ dropped on a time slot, a day, the all-day row or a resource.
12
+ - **Drag events out.** A calendar event dragged onto one of your droppables, such as an
13
+ "unscheduled" list or a bin, goes to it.
14
+
15
+ Drops go through the calendar like any drag: its hit-testing, snapping, policies, `onEventChange`
16
+ and `onEventChangeResult`. The calendar's own drags stay on its native pointer layer.
17
+ [Drag tasks in with dnd-kit](../guides/dnd-kit.md) builds a backlog beside a week, live.
18
+
19
+ It's a separate package. `@moltenship/calendar` doesn't re-export it, so a calendar without it
20
+ installs and bundles no dnd-kit. It works with dnd-kit's current packages, `@dnd-kit/react` and
21
+ `@dnd-kit/dom` 0.5, not the older `@dnd-kit/core`. Without dnd-kit, the same calls it makes are in
22
+ the pointer layer: see [drags from and to the rest of the page](./changes.md#drags-from-and-to-the-rest-of-the-page).
23
+
24
+ ## Install
25
+
26
+ **pnpm**
27
+
28
+ ```bash
29
+ pnpm add @moltenship/calendar-dnd-kit @dnd-kit/react @dnd-kit/dom
30
+ ```
31
+
32
+ **npm**
33
+
34
+ ```bash
35
+ npm install @moltenship/calendar-dnd-kit @dnd-kit/react @dnd-kit/dom
36
+ ```
37
+
38
+ **yarn**
39
+
40
+ ```bash
41
+ yarn add @moltenship/calendar-dnd-kit @dnd-kit/react @dnd-kit/dom
42
+ ```
43
+
44
+ **bun**
45
+
46
+ ```bash
47
+ bun add @moltenship/calendar-dnd-kit @dnd-kit/react @dnd-kit/dom
48
+ ```
49
+
50
+ dnd-kit 0.5 is still pre-1.0, and its minor versions change its API, so the adapter takes 0.5
51
+ only. It needs React 19, like the calendar.
52
+
53
+ ## Connect it
54
+
55
+ Render `<CalendarDndKit />` anywhere inside your `DragDropProvider`. It renders nothing, and
56
+ connects every calendar view on the page to that provider:
57
+
58
+ ```tsx
59
+ import { DragDropProvider } from "@dnd-kit/react";
60
+ import { CalendarDndKit } from "@moltenship/calendar-dnd-kit";
61
+
62
+ <DragDropProvider>
63
+ <CalendarDndKit />
64
+ <TaskList />
65
+ <Calendar.Root events={meetings} onEventChange={save} timeZone={timeZone}>
66
+ …
67
+ </Calendar.Root>
68
+ </DragDropProvider>;
69
+ ```
70
+
71
+ Each view becomes one droppable that takes only calendar items and calendar events. Its ID is
72
+ opaque, so tell it by `isCalendarTarget(droppable)`. It wins where the view is the topmost thing
73
+ under the pointer, over a droppable of yours around or under the calendar, and a droppable of
74
+ yours over the view, such as a floating bin, wins there. A read-only view's droppable is disabled.
75
+
76
+ `connectCalendarDragDrop(manager)` does the same for a `DragDropManager` of `@dnd-kit/dom` without
77
+ React, and returns a function that disconnects. Connecting a manager again, or rendering a second
78
+ `CalendarDndKit` in the same provider, shares the first connection.
79
+
80
+ ## Drag your items in
81
+
82
+ Spread `calendarDropData(source)` into a draggable's `data`, next to your own:
83
+
84
+ ```tsx
85
+ import { useDraggable } from "@dnd-kit/react";
86
+ import { calendarDropData } from "@moltenship/calendar-dnd-kit";
87
+
88
+ function TaskCard({ task }: { task: Task }) {
89
+ const { ref } = useDraggable({
90
+ id: task.id,
91
+ data: {
92
+ task,
93
+ ...calendarDropData({
94
+ event: meetingFromTask(task),
95
+ duration: { minutes: task.minutes },
96
+ title: task.title,
97
+ }),
98
+ },
99
+ });
100
+ return <li ref={ref}>{task.title}</li>;
101
+ }
102
+ ```
103
+
104
+ | Field | Meaning |
105
+ | ---------- | --------------------------------------------------------------------------------------------------------------------- |
106
+ | `event` | Your record the new event copies. Your `onEventChange` gets it as `change.event`, so it knows which task was dropped |
107
+ | `duration` | How long the event is when it's dropped on a time slot. An hour by default |
108
+ | `days` | How many days it covers when it's dropped on a day, such as a month cell or the all-day row. 1 by default |
109
+ | `eventId` | An event the calendar shows, to move instead of creating one: its start lands where it's dropped. Not a read-only one |
110
+ | `title` | What the calendar's announcements call it |
111
+
112
+ While the item is over a view, the view previews the slots it would take, from the slot under the
113
+ pointer, and marks them `data-invalid` or `data-warning` when your policies would reject or flag
114
+ them. Over a resource view it books the resource under the pointer. Dropped, it proposes a create
115
+ through the view, as dragging out a range does:
116
+
117
+ ```ts
118
+ function save(change: CalendarEventChange<Meeting, string, string>) {
119
+ if (change.cause === "create" && change.event !== null) {
120
+ // A task dropped on the calendar: its record, where it was dropped.
121
+ addMeeting({ ...change.event, id: newId(), ...placementFields(change.proposed) });
122
+ removeTask(change.event.taskId);
123
+ return;
124
+ }
125
+ // …moves, resizes, deletes and ranges dragged out in a view.
126
+ }
127
+ ```
128
+
129
+ Your own `onDragEnd` still hears the drop. `isCalendarTarget(operation.target)` says it landed on
130
+ a view, which handled it already.
131
+
132
+ ## Drag events out
133
+
134
+ A calendar event a view moves becomes a dnd-kit drag once the pointer leaves the view, of type
135
+ `calendarEventType`, until the move ends. Moves that stay in the view never reach dnd-kit. Your
136
+ droppables see it like any drag: list the type in `accept`, and `isDropTarget` lights up. Released
137
+ over one of them, the drag ends as a drop and the calendar proposes nothing. Any other end, a drop
138
+ back in the calendar or Escape, ends it as `canceled`.
139
+
140
+ ```tsx
141
+ import { useDragDropMonitor, useDroppable } from "@dnd-kit/react";
142
+ import { calendarEventOf, calendarEventType } from "@moltenship/calendar-dnd-kit";
143
+
144
+ function Unscheduled() {
145
+ const actions = Calendar.useCalendarActions();
146
+ const { isDropTarget, ref } = useDroppable({ id: "unscheduled", accept: calendarEventType });
147
+ useDragDropMonitor({
148
+ onDragEnd({ canceled, operation }) {
149
+ const dragged = calendarEventOf<Meeting, string, string>(operation.source);
150
+ if (canceled || dragged === null || operation.target?.id !== "unscheduled") return;
151
+ // Through the pipeline, so policies run and the event hides while it saves.
152
+ void actions.proposeEventChange(
153
+ { cause: "delete", eventId: dragged.eventId },
154
+ { input: "pointer" },
155
+ );
156
+ },
157
+ });
158
+ return (
159
+ <ul ref={ref} data-over={isDropTarget || undefined}>
160
+ …
161
+ </ul>
162
+ );
163
+ }
164
+ ```
165
+
166
+ `calendarEventOf(source)` gives `{ eventId, event, placement }`: the ID, your record and where it
167
+ was, or `null` for any other draggable. Off the view, a copy of the event follows the pointer, with
168
+ `data-outside`. Only moves drag out: resizes and creating a range stay in the view.
169
+
170
+ Once it has left the view, the drag is one of your provider's, so mind what else hears it:
171
+
172
+ - **Droppables without `accept`**, such as `useSortable` items, take calendar events too, and a
173
+ release over one proposes nothing in the calendar. Give your droppables an `accept` that leaves
174
+ calendar events out, or handles them.
175
+ - **Your `onDragStart` and `onDragEnd`** hear it. Leave alone what
176
+ `calendarEventOf(operation.source)` names when it isn't for you; a drag that came back and
177
+ dropped in the calendar ends `canceled`. A very short trip out can end before it starts, with a
178
+ `dragend` and no `dragstart`.
179
+ - **A `DragOverlay`** renders for it. Turn it off for calendar events, which the calendar draws:
180
+ `<DragOverlay disabled={(source) => calendarEventOf(source) !== null}>`.
181
+ - **The Feedback plugin**, one of dnd-kit's defaults, measures the drag's shape, which collision
182
+ detection needs. Without it, drags out reach no droppable. The adapter sets the stand-in's own
183
+ Feedback options and leaves yours alone. The Cursor plugin shows its grabbing cursor too.
184
+
185
+ ## How it behaves
186
+
187
+ - **Auto-scroll.** A view scrolls itself near its edges, once the pointer has been inside it clear
188
+ of them or has rested near one for a quarter of a second, so a drag that crosses an edge on its
189
+ way in doesn't scroll it, and one held there does. dnd-kit's `AutoScroller` is off while the
190
+ pointer is over a view that takes drops, and works as before elsewhere.
191
+ - **Cancel.** Escape, or a lost pointer, cancels: the preview goes and nothing is proposed.
192
+ - **Read-only.** A view of a `Root` without `onEventChange` previews nothing and takes no drop, and
193
+ starts no drags out.
194
+ - **Layers.** The topmost element under the pointer decides. A sheet, dialog or droppable of yours
195
+ over a view hides it, and one around or under the calendar doesn't.
196
+ - **Touch.** Your items use dnd-kit's sensors and their activation, and calendar events keep the
197
+ calendar's long-press. A gesture belongs to one of them: calendar events have no dnd-kit sensor,
198
+ and the calendar never sees a press that began outside it. Don't make dnd-kit draggables of your
199
+ own inside a view.
200
+ - **Keyboard.** dnd-kit's keyboard sensor drags your items in: Space picks one up, the arrow keys
201
+ move it, by 10 pixels or 50 with Shift, with the calendar previewing and announcing where it
202
+ would land, and Space, Enter or Tab drops it. Its steps are pixels, not slots, so it's slow
203
+ across a long way. Calendar events can't be dragged out by keyboard. Give both an explicit
204
+ action too, such as a button that schedules a task and one that unschedules an event.
205
+ - **Server rendering.** The package is a client module. It connects in an effect and reads no DOM
206
+ until then.
207
+ - **Announcements.** The calendar's `Announcer` speaks where an item would land and what came of
208
+ the drop, with its `title`, and proposes with `input: "keyboard"` when the keyboard sensor drove
209
+ it, `"pointer"` otherwise. dnd-kit's own announcements speak too, and their default text names
210
+ draggables and droppables by ID. Give its `Accessibility` plugin announcements that name your
211
+ items, and stay quiet where the calendar speaks: over a view, and for calendar events, which the
212
+ calendar announces until they reach one of your droppables. For example:
213
+
214
+ ```ts
215
+ import { Accessibility } from "@dnd-kit/dom";
216
+ import { calendarEventOf, isCalendarTarget } from "@moltenship/calendar-dnd-kit";
217
+
218
+ type Entity = { readonly data?: unknown; readonly id: string | number } | null;
219
+ type Announced = { readonly operation: { readonly source: Entity; readonly target: Entity } };
220
+
221
+ const taskOf = (source: Entity) => (source?.data as { task?: Task } | undefined)?.task;
222
+ const eventTitle = (source: Entity) => calendarEventOf<Meeting>(source)?.event.title;
223
+
224
+ const announcements = {
225
+ dragstart: ({ operation }: Announced) => {
226
+ const task = taskOf(operation.source);
227
+ return task && `Picked up ${task.title}.`;
228
+ },
229
+ dragover: ({ operation }: Announced) =>
230
+ operation.target === null || isCalendarTarget(operation.target)
231
+ ? undefined
232
+ : eventTitle(operation.source) && "Over the unscheduled tasks.",
233
+ dragend: ({ canceled, operation }: Announced & { readonly canceled: boolean }) => {
234
+ const task = taskOf(operation.source);
235
+ if (task) {
236
+ if (canceled) return `Cancelled. ${task.title} is still unscheduled.`;
237
+ return operation.target === null ? `${task.title} is still unscheduled.` : undefined;
238
+ }
239
+ const title = eventTitle(operation.source);
240
+ return title === undefined || canceled ? undefined : `${title} is unscheduled.`;
241
+ },
242
+ };
243
+
244
+ <DragDropProvider
245
+ plugins={(defaults) => [
246
+ ...defaults.filter((plugin) => plugin !== Accessibility),
247
+ Accessibility.configure({ announcements }),
248
+ ]}
249
+ >
250
+ …
251
+ </DragDropProvider>;
252
+ ```
253
+
254
+ ## API
255
+
256
+ | Export | What it is |
257
+ | ---------------------------------- | --------------------------------------------------------------------------------- |
258
+ | `CalendarDndKit` | A component that connects the views on the page to the `DragDropProvider` it's in |
259
+ | `connectCalendarDragDrop(manager)` | The same for a `DragDropManager`; returns a function that disconnects |
260
+ | `calendarDropData(source)` | `data` that makes a draggable an item the calendar takes |
261
+ | `calendarDropOf(source)` | The calendar drop a draggable carries, or `null` |
262
+ | `calendarEventType` | The `type` of a calendar event dragged out, for `accept` |
263
+ | `calendarEventOf(source)` | `{ eventId, event, placement }` of a calendar event dragged out, or `null` |
264
+ | `isCalendarTarget(target)` | Whether a droppable is a calendar view's |
265
+ | `CalendarEventDragData` | The type `calendarEventOf` returns |
@@ -0,0 +1,153 @@
1
+ # Events and snapshots
2
+
3
+ Adapters, event ranges, validation, snapshots, and queries.
4
+
5
+ Source: https://time.molten.sh/docs/react/api/events
6
+
7
+ Exported from `@moltenship/calendar` and from
8
+ `@moltenship/calendar-core`.
9
+
10
+ ## Adapter
11
+
12
+ ```ts
13
+ const eventAdapter = defineEventAdapter<TEvent>()({ getId, getTitle, getInterval, getResourceIds });
14
+ ```
15
+
16
+ `defineEventAdapter` returns your adapter unchanged. The two calls let TypeScript fix `TEvent` first
17
+ and then infer the ID types from `getId` and `getResourceIds`.
18
+
19
+ | Name | Type | Default | Description |
20
+ | ---------------- | ------------------------------------------ | ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
21
+ | `getId` | `(event) => string \| number` | | Required. A unique ID: a non-empty string or a finite number. |
22
+ | `getTitle` | `(event) => string` | | Required. The display title. |
23
+ | `getInterval` | `(event) => CalendarEventInterval` | | Required. When the event happens. See [ranges](#ranges). |
24
+ | `getResourceIds` | `(event) => readonly (string \| number)[]` | | Required. The resources the event belongs to. Return `[]` for none. |
25
+ | `getRevision` | `(event) => string \| number` | | Changes whenever the record changes. Lets Time reuse work for unchanged records after a refetch. |
26
+ | `isReadOnly` | `(event) => boolean` | `false` | Marks events users can't change. Exposed as `isReadOnly` on normalized events. |
27
+ | `isBusy` | `(event) => boolean` | `timed and floating events are busy; all-day events are free` | Whether the event makes its resources busy, as "show as busy" or "free" does. Exposed as `isBusy` on normalized events. See [busy or available](../availability.md#busy-or-available). |
28
+
29
+ `createCanonicalEventAdapter()` returns an adapter for records already in Time's `CalendarEvent`
30
+ shape (`id`, `title`, `kind`, `start`, `end`, optional `resourceIds`, and `data`).
31
+
32
+ ## Ranges
33
+
34
+ `getInterval` returns one of three shapes. In every one, `start` is included and `end` is excluded,
35
+ and `start` must come before `end`.
36
+
37
+ ```ts
38
+ type CalendarEventInterval =
39
+ | { kind: "timed"; start: Temporal.Instant; end: Temporal.Instant; sourceTimeZone?: string }
40
+ | { kind: "all-day"; start: Temporal.PlainDate; end: Temporal.PlainDate }
41
+ | { kind: "floating"; start: Temporal.PlainDateTime; end: Temporal.PlainDateTime };
42
+ ```
43
+
44
+ See [Time and time zones](../concepts/time.md) for when to use each.
45
+
46
+ ## Validation helpers
47
+
48
+ These check values before they reach the calendar. They return a result instead of throwing.
49
+
50
+ ```ts
51
+ import { isEventId, validateCalendarEvent } from "@moltenship/calendar";
52
+
53
+ isEventId("meeting-1"); // true
54
+
55
+ const result = validateCalendarEvent({
56
+ id: "meeting-1",
57
+ title: "Standup",
58
+ kind: "timed",
59
+ start: Temporal.Instant.from("2026-10-08T07:15:00Z"),
60
+ end: Temporal.Instant.from("2026-10-08T07:00:00Z"),
61
+ data: null,
62
+ });
63
+
64
+ result.valid; // false
65
+ result.valid || result.issues; // [{ code: "start-not-before-end", kind: "timed" }]
66
+ ```
67
+
68
+ | Function | Checks |
69
+ | ------------------------------------------------------ | ---------------------------------------------------------------------------------------- |
70
+ | `isEventId(value)`, `isResourceId(value)` | A non-empty string or a finite number |
71
+ | `validateCalendarEvent(event)` | A `CalendarEvent`: its ID, resource IDs, and range |
72
+ | `validateCalendarEventInterval(interval, comparators)` | A range, using the `{ instant, plainDate, plainDateTime }` comparison functions you pass |
73
+
74
+ ## Snapshots
75
+
76
+ A snapshot is a frozen, indexed copy of your events. `Root` builds one for you and exposes it as
77
+ `meta.eventSnapshot`. Outside React, build one yourself:
78
+
79
+ ```ts
80
+ import { createEventSnapshotCache } from "@moltenship/calendar";
81
+
82
+ const snapshots = createEventSnapshotCache(eventAdapter, { queryCacheSize: 128 });
83
+ const snapshot = snapshots.getSnapshot(events);
84
+
85
+ snapshots.getSnapshot(events) === snapshot; // true while `events` is the same array
86
+ ```
87
+
88
+ Keep one cache per adapter and reuse it. `getSnapshot` returns the same snapshot for the same array
89
+ and builds a new one, reusing what it can, for a new array. For a one-off snapshot, call
90
+ `createEventSnapshot(events, eventAdapter, options)`.
91
+
92
+ | Name | Type | Default | Description |
93
+ | -------------------- | ------------------------------ | ------------------- | ---------------------------------------------------- |
94
+ | `invalidEventPolicy` | `"report-and-skip" \| "throw"` | `"report-and-skip"` | What to do with invalid records. |
95
+ | `queryCacheSize` | `number` | `128` | How many distinct query results each snapshot keeps. |
96
+
97
+ ### Snapshot fields
98
+
99
+ | Field | Contents |
100
+ | --------------------------- | -------------------------------------------------------- |
101
+ | `events` | Valid events, normalized, in input order |
102
+ | `byId` | A read-only `Map` from ID to normalized event |
103
+ | `size` | Number of valid events |
104
+ | `issues` | Problems with skipped records (see below) |
105
+ | `version` | Goes up by one for each new snapshot from the same cache |
106
+ | `getQueryCacheStatistics()` | `capacity`, `size`, `hits`, `misses`, and `evictions` |
107
+
108
+ A normalized event has your record as `event`, plus `id`, `title`, `resourceIds`, `isReadOnly`,
109
+ `revision`, `inputIndex`, `isBusy` when the adapter has `isBusy`, and the range fields (`kind`, `start`,
110
+ `end`, and, on timed events, `sourceTimeZone` when the range has one). Inside a calendar, an event
111
+ with a change that is still saving also has `isPending: true` and shows its proposed range; see
112
+ [pending changes](../interactions.md#pending-changes).
113
+
114
+ ## Queries
115
+
116
+ ```ts
117
+ snapshot.queryTimed(instantInterval(start, end));
118
+ snapshot.queryAllDay(plainDateInterval(startDate, endDate));
119
+ snapshot.queryFloating(plainDateTimeInterval(startDateTime, endDateTime));
120
+
121
+ snapshot.queryTimed(range, { resourceIds: ["room-1"] });
122
+ snapshot.eventsForResource("room-1");
123
+ snapshot.get("meeting-1");
124
+ ```
125
+
126
+ - Each query returns the events of one kind that overlap the range. Ranges are end-exclusive on both
127
+ sides, so an event ending exactly at the range start isn't included.
128
+ - Build ranges with `instantInterval`, `plainDateInterval`, and `plainDateTimeInterval` from
129
+ the [Temporal helpers](../temporal/reference.md#ranges).
130
+ - `resourceIds` keeps events assigned to any of the listed resources. An empty list matches nothing.
131
+ - Results are frozen and in input order. Repeating a query returns the same array while it's in the
132
+ cache.
133
+
134
+ ## Invalid records
135
+
136
+ With the default policy, invalid records are left out of the snapshot and listed in
137
+ `snapshot.issues`. In a calendar they also appear as `invalid-event`
138
+ [diagnostics](./components.md#diagnostics). Each issue has the `event`, its `index` in your array, a `code`, and when known the `eventId`, the
139
+ adapter function that failed (`accessor`), the position of a bad resource ID (`resourceIndex`), and a
140
+ `message`.
141
+
142
+ | `code` | Cause |
143
+ | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
144
+ | `adapter-error` | An adapter function threw, `getTitle` returned something other than a string, `getResourceIds` something other than an array, or `isReadOnly` or `isBusy` something other than a boolean |
145
+ | `invalid-event-id` | `getId` returned an empty string, `NaN`, or another non-ID value |
146
+ | `duplicate-event-id` | Another record already has this ID |
147
+ | `invalid-resource-id` | `getResourceIds` returned an array with a non-ID value (its position is `resourceIndex`) |
148
+ | `invalid-revision` | `getRevision` returned something other than a string or a finite number |
149
+ | `invalid-event-interval` | The range has an unknown `kind`, the wrong Temporal type, a `sourceTimeZone` that isn't a string, or fields that throw when read |
150
+ | `start-not-before-end` | The range is empty or reversed |
151
+
152
+ With `invalidEventPolicy: "throw"`, building the snapshot throws an
153
+ `InvalidCalendarEventSnapshotError` with every issue on its `issues` property instead.
@@ -0,0 +1,218 @@
1
+ # Primitives
2
+
3
+ The framework-free layer under the React and Solid integrations, the calendar as a ui-sdk primitive, and the types of its agent actions.
4
+
5
+ Source: https://time.molten.sh/docs/react/api/primitives
6
+
7
+ `@moltenship/calendar-primitives` is the layer between the engine and a framework. It holds what
8
+ `Root` does, with no React or Solid in it: the state store, the runtime that turns events and state
9
+ into what a view draws, and the calendar as a [ui-sdk](https://ui-sdk.dev) primitive, which is what
10
+ an [agent](../agents.md) operates.
11
+
12
+ Apps don't need it: your framework's package exports the parts an app uses. Install it to write an
13
+ integration for another framework, or to name the agent types below.
14
+
15
+ ## Install
16
+
17
+ ```bash
18
+ pnpm add @moltenship/calendar-primitives @ui-sdk/core
19
+ ```
20
+
21
+ `@ui-sdk/core` is a peer dependency, from `0.1.0-beta.16` on within the 0.1 line. The package
22
+ imports no UI framework. It needs a runtime with `Temporal`, as the rest of the library does.
23
+
24
+ ## Where it sits
25
+
26
+ ```text
27
+ @moltenship/calendar-react @moltenship/calendar-solid thin: render parts, bind state
28
+ └──────────────┬──────────────┘
29
+ @moltenship/calendar-primitives runtime, store, primitive, agent actions
30
+ ┌──────────────┴──────────────┐
31
+ @moltenship/calendar-core @ui-sdk/core the engine · parts and the agent bridge
32
+ ```
33
+
34
+ The engine doesn't import ui-sdk, and ui-sdk's own date components aren't used. Dates, time zones,
35
+ recurrence, layouts, transactions and policies are the calendar's own.
36
+
37
+ ## What it exports
38
+
39
+ | Export | What it is |
40
+ | ----------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
41
+ | `createCalendarStore(options)` | The store of the six state values. The same one [your framework's package exports](./store.md) |
42
+ | `createCalendarRuntime(config)` | What `Root` runs: event snapshots, pending changes, the active view's projection, the visible range, diagnostics |
43
+ | `createCalendarPrimitive({ views })` | The calendar as a ui-sdk primitive: the six values as controlled keys, slots for the parts, and the agent actions |
44
+ | `calendarAgentActions` | The fifteen action names an agent can call |
45
+ | `calendarStateSlices` | The six state value names |
46
+ | `resolveViewOptions(view, overrides)` | A view's options: its `defaultOptions` with a root's `viewOptions` over them |
47
+ | `createDraftStore()`, `createKeyboardSessionStore()` | The stores behind gesture previews and keyboard grabs |
48
+ | `createAnnouncerChannel(getEnvironment, getResources)` | The channel a live region reads announcements from |
49
+ | `createClockTicker(clock, intervalMs)`, `systemClock`, `clockOf` | The clock a root samples for today and the current time |
50
+ | `eventLabel`, `agentEventLabel`, `visibleEventsOf` | How an agent's items are made: an event's label, the default label of a described event, the events in view |
51
+ | `describeAgentEvent`, `describeAgentPlacement`, `eventsInRange` | An event and a placement as an agent reads them, and the events `listEvents` returns for a range |
52
+ | `findEvent`, `readAgentInput` | An event by the ID an agent sent, and an action's one input object checked against its keys |
53
+ | `parseInstant`, `parsePlainDate`, `parsePlainDateTime`, `parseTimeZone` | How an agent's JSON values are read, with the errors the [reference](../agents/reference.md#errors) lists |
54
+
55
+ It also exports the equality helpers the integrations compare props with (`sameInstant`,
56
+ `samePlainDate`, `sameRange`, `sameWeekRules` and others), `createMemoCell` and `createStableCell`,
57
+ and the state types: `CalendarPublicState`, `CalendarActions`, `CalendarStore`,
58
+ `CalendarStateChangeDetail`, `CalendarChangeReason`, `CalendarChangeSource` and
59
+ `CalendarCommandOptions`.
60
+
61
+ ## The primitive
62
+
63
+ `createCalendarPrimitive` defines the calendar for ui-sdk, once per `createCalendar` call. An
64
+ integration renders it with its framework's ui-sdk package, `@ui-sdk/react` or `@ui-sdk/solid`.
65
+
66
+ Its slots are the calendar's structural parts:
67
+
68
+ | Slot | The part |
69
+ | ------------------ | -------------------------- |
70
+ | `root` | `Calendar.Frame` |
71
+ | `toolbar` | `Calendar.Toolbar` |
72
+ | `title` | `Calendar.Title` |
73
+ | `previous-trigger` | `Calendar.PreviousTrigger` |
74
+ | `next-trigger` | `Calendar.NextTrigger` |
75
+ | `today-trigger` | `Calendar.TodayTrigger` |
76
+ | `view-switcher` | `Calendar.ViewSwitcher` |
77
+ | `viewport` | `Calendar.Viewport` |
78
+
79
+ Events and cells aren't slots. A view renders them as ordinary elements with the
80
+ [data attributes](../interactions.md#in-your-own-views) the pointer layer reads, so a calendar with
81
+ a thousand events doesn't make a thousand ui-sdk parts.
82
+
83
+ The six state values are always controlled keys of the primitive. The integration merges what the
84
+ app controls with what the calendar store holds, and passes the result in. ui-sdk's own store is a
85
+ copy of that for the parts and for agents, never the owner of a value. That keeps what
86
+ [State](../concepts/state.md) promises: actions in one handler build on each other, and dates
87
+ compare by value.
88
+
89
+ ## Agent types
90
+
91
+ The primitive's `api` is what an agent calls. Its TypeScript types are exported for code that
92
+ wraps the bridge:
93
+
94
+ ```ts title="agent-actions.ts"
95
+ import {
96
+ calendarAgentActions,
97
+ type CalendarAgentApi,
98
+ type CalendarAgentChange,
99
+ type CalendarAgentEvent,
100
+ type CalendarAgentItem,
101
+ } from "@moltenship/calendar-primitives";
102
+
103
+ // The fifteen action names. A snapshot lists the ones a calendar takes, in alphabetical order.
104
+ export const actionNames: readonly (keyof CalendarAgentApi)[] = calendarAgentActions;
105
+
106
+ // One entry of a calendar's `items`: `{ value, label }`.
107
+ export type VisibleEvent = CalendarAgentItem;
108
+
109
+ // What `listEvents` returns for an event, and what an event action returns.
110
+ export type ListedEvent = CalendarAgentEvent;
111
+ export type ChangeResult = CalendarAgentChange;
112
+ ```
113
+
114
+ `CalendarAgentApi` has one method per action. Each takes nothing or one object, which is the one
115
+ argument of an agent's step:
116
+
117
+ | Method | Input | Returns |
118
+ | --------------------------------------------------------- | -------------------------------------------------------------------------------------- | ------------------------------- |
119
+ | `describeCalendar()` | none | `CalendarAgentDescription` |
120
+ | `listEvents(input?)` | `CalendarAgentRange`: `{ start?, end? }` | `readonly CalendarAgentEvent[]` |
121
+ | `getChange(input)` | `{ changeId }` | `CalendarAgentChange` |
122
+ | `navigateNext()`, `navigatePrevious()`, `navigateToday()` | none | nothing |
123
+ | `goToDate(input)` | `{ date }` | nothing |
124
+ | `setView(input)` | `{ view }` | nothing |
125
+ | `setTimeZone(input)` | `{ timeZone }` | nothing |
126
+ | `selectEvent(input)` | `{ eventId }`, or `{ eventId: null }` to clear | nothing |
127
+ | `createEvent(input)` | `CalendarAgentCreateInput`: `{ start, end, title?, resourceIds?, fields? }` | `CalendarAgentChange` |
128
+ | `updateEvent(input)` | `CalendarAgentUpdateInput`: `{ eventId, title?, start?, end?, resourceIds?, fields? }` | `CalendarAgentChange` |
129
+ | `moveEvent(input)` | `CalendarAgentMoveInput`: `{ eventId, start, end?, resourceIds? }` | `CalendarAgentChange` |
130
+ | `resizeEvent(input)` | `CalendarAgentResizeInput`: `{ eventId, start }` or `{ eventId, end }` | `CalendarAgentChange` |
131
+ | `deleteEvent(input)` | `CalendarAgentEventRef`: `{ eventId }` | `CalendarAgentChange` |
132
+
133
+ The five event methods are optional in the type, because a calendar has them only when it can
134
+ take them: `createEvent`, `updateEvent`, `moveEvent` and `resizeEvent` when its root has
135
+ `onEventChange`, and `deleteEvent` when the root also has `allowAgentDelete`. A read-only
136
+ calendar's snapshot doesn't list them.
137
+
138
+ Dates and times are ISO strings in both directions. `CalendarAgentChange` is
139
+ `{ changeId, cause, eventId, proposed, status, reason? }`, with `status` one of `"saved"`,
140
+ `"saving"`, `"validating"` and `"rejected"`.
141
+
142
+ The types say what a well-formed call sends. A model can send anything, so the calendar checks
143
+ the input when the step runs, and fails the step with a message that names the action's input.
144
+ The [agent reference](../agents/reference.md) has every input, result and error.
145
+
146
+ An app doesn't call these methods. An agent calls them by name through the bridge, where your
147
+ `allow` decides first.
148
+
149
+ ## Interaction
150
+
151
+ The keyboard, roving focus, drafts, the history binding and the announcer are written once, here.
152
+ An integration binds each in a few lines, with three shapes:
153
+
154
+ - **Stores** have `subscribe` and `getSnapshot`, and `getServerSnapshot` when the server reads
155
+ something else. React reads them with `useSyncExternalStore`, Solid with a store selector.
156
+ - **Element listeners** take the element and a getter for the latest options, and return a
157
+ cleanup, as `attachCalendarPointer(element, () => options)` does. The getter is read whenever an
158
+ event arrives, so new options never re-attach anything.
159
+ - **Queries** are memoized functions an integration calls while it renders, as often as it renders.
160
+
161
+ Most take the root's interaction runtime, `model.interaction` from `runtime.derive`, or the few
162
+ fields of it they use.
163
+
164
+ | Export | What it is |
165
+ | ---------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
166
+ | `createCalendarViewRuntime(getView)` | One rendered active view: `getView` reads the latest view, and `roving` is its roving focus store. Keep it on the root's focus with `roving.update(focus, calendarViewEntry(view))` after each render |
167
+ | `calendarViewEntry(view)` | Where focus enters a view, from its spatial navigation |
168
+ | `focusRovingTarget(interaction, target, days, event)` | What a cell or event does when it takes DOM focus itself: it becomes the calendar's focus |
169
+ | `calendarFocusKey(target)` | A key for a focus target, which changes exactly when the target does |
170
+ | `createCalendarKeyboard(interaction, viewRuntime, getOptions, getResources)` | A view's keyboard: `keyDown(event, wrapper?)` and `focusOut(event, region)` for the element around its cells. `wrapper` is the framework's own event, when it wraps DOM events as React does. Bind `keydown` on that element itself (`addEventListener` from a ref in Solid): a handler delegated to the document stops Escape too late |
171
+ | `interaction.draft` | A store of the change being drafted: the keyboard's session while there is one, else the pointer's draft |
172
+ | `createBusyResourcesQuery()`, `createDraftBusyQuery()` | Queries for the resources busy in a range, and for one resource during the draft |
173
+ | `bindCalendarHistory(interaction, history, getOptions)` | An event history bound to a root, as a store of `{ undo, redo, canUndo, canRedo, … }` |
174
+ | `attachCalendarHistoryShortcuts(interaction, getConfig)` | The undo and redo keys, a `keydown` listener on the document for keys inside `scope`; returns a cleanup |
175
+ | `createAnnouncerLiveText()` | A live region's text as a store. Pass its `speak` to `interaction.announcements.mount` and render the snapshot |
176
+ | `subscribeAnchorDateRequests(interaction, listener)` | Hears every date the root is asked to show, with the range the active view shows for it |
177
+ | `createResourceExpansionCommands(interaction, resourceId)` | `expand`, `collapse` and `toggle` for one resource of a tree |
178
+ | `createResourceStatusClock(source, compute)` | A store of a status that depends on the time, such as whether a resource is open now, sampled on `source`'s clock once a minute while subscribed, and `null` on the server. Only the clock is read: when `source.now` is fixed, compute at it yourself |
179
+
180
+ A view that unmounts mid-gesture leaves nothing grabbed when its integration calls
181
+ `interaction.keyboard.set(null)` on unmount. Its React binding, `useCalendarKeyboard`, is this:
182
+
183
+ ```ts title="keyboard.ts"
184
+ const keyboard = useMemo(
185
+ () =>
186
+ createCalendarKeyboard(
187
+ interaction,
188
+ view,
189
+ () => latest.current.options,
190
+ () => latest.current.resources,
191
+ ),
192
+ [interaction, view],
193
+ );
194
+ useEffect(() => () => interaction.keyboard.set(null), [interaction.keyboard]);
195
+ return {
196
+ onBlur: (event) => keyboard.focusOut(event.nativeEvent, event.currentTarget),
197
+ onKeyDown: (event) => keyboard.keyDown(event.nativeEvent, event),
198
+ };
199
+ ```
200
+
201
+ ## Writing an integration
202
+
203
+ `@moltenship/calendar-solid` is the model to read: it binds everything React's does, in less code. An integration
204
+ does four things:
205
+
206
+ 1. Creates the runtime and the primitive in its factory, as `createCalendar` does.
207
+ 2. In its `Root`, connects the runtime to a store (`runtime.connect`), merges controlled state, and
208
+ calls `runtime.derive(inputs)` in the framework's reactive idiom. `derive` is synchronous and
209
+ memoized per root.
210
+ 3. Renders the primitive's slots as parts through the framework's ui-sdk package.
211
+ 4. Passes the model to custom views and hooks through a context of its own.
212
+
213
+ The interaction below is shared from here as stores and plain functions. The pointer layer is
214
+ `@moltenship/calendar-dnd`, which imports no framework either: bind `attachCalendarPointer` as
215
+ `useCalendarPointer` does in both integrations.
216
+
217
+ There's no guide beyond this page yet, and the runtime's types change as the Solid integration
218
+ grows. If you plan an integration, open an issue first.