@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,264 @@
1
+ # Event changes
2
+
3
+ Proposals, changes, results, policies, placement helpers, and the pointer layer.
4
+
5
+ Source: https://time.molten.sh/docs/react/api/changes
6
+
7
+ Everything on this page is exported from `@moltenship/calendar`. [Interactions](../interactions.md)
8
+ explains how the pieces fit together.
9
+
10
+ ## Proposals
11
+
12
+ `actions.proposeEventChange(proposal)` takes one of these:
13
+
14
+ ```ts
15
+ type CalendarEventProposal =
16
+ | { cause: "create"; proposed: Placement; event?: TEvent }
17
+ | {
18
+ cause: "move" | "resize-start" | "resize-end" | "update";
19
+ eventId: EventId;
20
+ proposed: Placement;
21
+ }
22
+ | { cause: "delete"; eventId: EventId };
23
+ ```
24
+
25
+ A placement is a [range](./events.md#ranges) (`kind`, `start`, `end`) plus optional
26
+ `resourceIds`. Leaving out `resourceIds` keeps the event's current resources. A create may carry
27
+ one of your records as `event`, such as a deleted event an
28
+ [undo](../undo-redo.md#creates-and-deletes) restores; the change hands it on.
29
+
30
+ ## Changes
31
+
32
+ `onEventChange` and policies receive a `CalendarEventChange`:
33
+
34
+ | Field | `create` | `move`, `resize-*`, `update` | `delete` |
35
+ | ---------- | ---------------------------------------- | ---------------------------- | -------------------- |
36
+ | `cause` | `"create"` | the cause | `"delete"` |
37
+ | `id` | a change ID | a change ID | a change ID |
38
+ | `eventId` | `null` | the event's ID | the event's ID |
39
+ | `event` | `null`, or the record the create carries | your record | your record |
40
+ | `original` | `null` | the placement before | the placement before |
41
+ | `proposed` | the new placement | the new placement | `null` |
42
+ | `warnings` | reasons `warn` policies flagged, if any | the same | the same |
43
+
44
+ Placements in a change always include `resourceIds`. `original` is what the user saw, including any
45
+ change still pending for the same event. `warnings` is absent when no policy flagged the change.
46
+
47
+ ## Results
48
+
49
+ `proposeEventChange` resolves with `{ status: "committed", change }` or
50
+ `{ status: "rejected", reason, change?, error? }`. It never rejects. The
51
+ [reasons](../interactions.md#changing-events-from-your-own-ui) are listed on the Interactions page.
52
+ `Root`'s `onEventChangeResult` gets the same result for every proposal, with the detail it was
53
+ proposed with (`CalendarProposalDetail`): `{ input: "pointer" | "keyboard" | "api" | "agent" }`,
54
+ `history: "undo" | "redo"` on an event history's inverse, and `fields` when the proposer asked
55
+ for more than a placement. A detail that names no input reads `{ input: "api" }`. `"agent"` is an
56
+ AI agent's change, made through the [agent bridge](../agents.md). `onEventChange` gets the same
57
+ detail as its second argument, and a policy as `context.detail`, so both can
58
+ [refuse an agent's change](../agents/changes.md).
59
+
60
+ `fields` is what a change says beside where the event goes. The engine models placement only, so
61
+ a title, a colour or anything else of your record travels there, as it came and unchecked. An
62
+ agent's `createEvent` and `updateEvent` fill it, with the title as `fields.title`, and your
63
+ `onEventChange` reads it to [save what the agent sent](../agents/connect.md#save-what-the-agent-sent).
64
+ Your own code can send fields the same way, as `proposeEventChange(proposal, { input: "api", fields })`.
65
+
66
+ While a proposal is on its way, `useCalendarPendingChanges` lists it as a `CalendarPendingChange`,
67
+ `{ change, phase }`, with `phase` one of `"validating"`, `"saving"` and `"awaiting-events"`. See
68
+ [pending changes](../interactions.md#across-the-calendar).
69
+
70
+ ## Event history
71
+
72
+ `createEventHistory(options?)` records committed changes and undoes and redoes them through the
73
+ pipeline. Its members are plain functions: `record(result, detail)` for `onEventChangeResult`,
74
+ `undo(context)` and `redo(context)`, `clear()`, `getSnapshot()` and `subscribe(listener)`. The
75
+ context is `{ getEvents, propose, input?, whenSettled? }`. See [Undo and redo](../undo-redo.md)
76
+ for the options, the steps (`EventHistoryStep`), the outcomes (`EventHistoryOutcome`) and the
77
+ snapshot (`EventHistorySnapshot`), and `useCalendarHistory` binds a history to a `Root`.
78
+
79
+ ## Policies
80
+
81
+ ```ts
82
+ type CalendarPolicy = (
83
+ change: CalendarEventChange,
84
+ context: {
85
+ events: EventSnapshot;
86
+ timeZone: string;
87
+ availability?: AvailabilitySnapshot;
88
+ detail?: CalendarProposalDetail;
89
+ },
90
+ ) => Decision | Promise<Decision>;
91
+
92
+ type CalendarProposalDetail = {
93
+ input: "pointer" | "keyboard" | "api" | "agent";
94
+ history?: "undo" | "redo";
95
+ fields?: Readonly<Record<string, unknown>>;
96
+ };
97
+
98
+ type Decision =
99
+ | { type: "accept" }
100
+ | { type: "adjust"; proposed: Placement }
101
+ | { type: "reject"; reason: string }
102
+ | { type: "warn"; reason: string };
103
+ ```
104
+
105
+ `warn` accepts the change and adds `reason` to its `warnings`. `context.availability` holds the
106
+ root's working hours, for `availabilityPolicy`. `context.events` includes pending changes, so a
107
+ policy sees the calendar as the user does. `context.detail` says who proposed the change, so a
108
+ policy can [refuse an agent's change](../agents/changes.md#refuse-an-agents-change) and allow a
109
+ person's; it's absent when your own code calls a policy outside a proposal. A policy
110
+ that throws rejects the change with the reason `policy-error`.
111
+
112
+ | Policy | Behaviour |
113
+ | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
114
+ | `snapPolicy(increment)` | Rounds timed and floating changes to a wall-clock grid in the calendar's time zone, such as `{ minutes: 15 }`. Moves keep their length; resizes snap only the dragged edge. All-day changes pass through. The increment must divide an hour or a day evenly. |
115
+ | `minimumDurationPolicy(minimum)` | Lengthens timed and floating changes shorter than `minimum`. Resizing the start moves the start earlier; anything else moves the end later. |
116
+ | `boundsPolicy({ start, end })` | Rejects changes that reach outside `[start, end)`, with the reason `out-of-bounds`. Both bounds are optional instants. |
117
+ | `readOnlyPolicy()` | Rejects changes to events whose adapter `isReadOnly` returns `true`, with the reason `read-only`. `Root` runs it before your policies. |
118
+ | `availabilityPolicy({ mode })` | Rejects a change outside working hours, with the reason `outside-availability`, or with `mode: "warn"` saves it with that warning. See [Availability](../availability.md#keep-changes-inside). |
119
+ | `conflictPolicy({ mode, getResourceMode })` | Rejects a change that makes a busy event overlap another busy event on one of its resources, with the reason `resource-conflict`; with `mode: "warn"` saves it with that warning, and with `"allow"` as it is. `getResourceMode` gives a resource its own mode; the strictest decides. Deletes always pass. See [Availability](../availability.md#double-booking). |
120
+ | `readOnlyResourcesPolicy(isReadOnly)` | Rejects creating, deleting, or changing the time of an event on a resource `isReadOnly(resourceId)` marks, and adding or removing that resource, with the reason `read-only-resource`. |
121
+
122
+ ## Placement helpers
123
+
124
+ These build placements for proposals, with the same wall-clock rules the calendar's gestures use.
125
+
126
+ | Function | Returns |
127
+ | ----------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
128
+ | `eventPlacement(normalizedEvent)` | The placement of an event from the snapshot |
129
+ | `moveEventPlacement(placement, delta, { timeZone })` | The placement moved by a wall-clock delta, such as `{ days: 1, minutes: -30 }`. A 09:00 event moved by a week stays at 09:00 across a DST change. |
130
+ | `resizeEventPlacement(placement, edge, delta, { timeZone, minimumDuration })` | One edge moved, keeping at least `minimumDuration` (15 minutes by default; all-day events keep a day) |
131
+ | `createEventPlacement(anchor, focus, resourceIds)` | A placement covering two ranges of the same kind, such as the first and last slot of a drag |
132
+ | `toAllDayPlacement(placement, { timeZone })` | The dates a placement touches, as an all-day placement |
133
+ | `toTimedPlacement(placement, start, duration)` | A timed placement starting at a `Temporal.ZonedDateTime` |
134
+
135
+ For example, this moves an event to the same time on the next day:
136
+
137
+ ```tsx title="move-to-tomorrow.ts"
138
+ export function useMoveToTomorrow() {
139
+ const actions = Calendar.useCalendarActions();
140
+ const { eventSnapshot } = Calendar.useCalendarMeta();
141
+ const { timeZone } = Calendar.useCalendarState();
142
+
143
+ return (eventId: string) => {
144
+ const event = eventSnapshot.get(eventId);
145
+ if (event === undefined) return;
146
+ return actions.proposeEventChange({
147
+ cause: "move",
148
+ eventId,
149
+ proposed: moveEventPlacement(eventPlacement(event), { days: 1 }, { timeZone }),
150
+ });
151
+ };
152
+ }
153
+ ```
154
+
155
+ `createEventTransactions` and `applyEventOverlay` are the engine `Root` uses to run proposals and
156
+ draw pending changes. You only need them to handle changes outside React. The engine's
157
+ `getPending()` returns the pending placements `applyEventOverlay` draws, and `getPendingChanges()`
158
+ the changes `useCalendarPendingChanges` reads.
159
+
160
+ ## Pointer layer
161
+
162
+ `useCalendarPointer(options)` returns a ref for the element that contains a view's days, and turns
163
+ drags inside it into proposals. `attachCalendarPointer(element, getOptions)` does the same without
164
+ a framework and returns a cleanup function. `@moltenship/calendar` exports both: the hook comes from
165
+ `@moltenship/calendar-react`, and the function from `@moltenship/calendar-dnd`, which imports no
166
+ framework. `@moltenship/calendar-solid` exports a `useCalendarPointer` that takes the same options,
167
+ or an accessor of them, and passes them on untouched.
168
+
169
+ | Name | Type | Default | Description |
170
+ | ------------------------- | ------------------------------------------------------------------------------------ | ---------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
171
+ | `events` | `EventSnapshot` | | Required. The events as rendered, pending changes included: the Renderer's `events` prop. |
172
+ | `onPropose` | `(proposal, { input: "pointer" }) => void \| PromiseLike<CalendarTransactionResult>` | | Required. Receives one proposal per finished drag, and `{ input: "pointer" }`, and one per item dropped in from outside the calendar, with that drag's input. Usually `actions.proposeEventChange`, so `onEventChangeResult` hears the drag as the pointer's. Return the result, as it does, so the announcer says whether the change was saved. |
173
+ | `check` | `(proposal) => CalendarPolicyResult \| null` | | Asks the policies about the drop the preview shows, so the preview can mark it. Pass `actions.checkEventChange`. |
174
+ | `onPreview` | `(draft: { eventId, proposed } \| null) => void` | | Hears where a drop would land, once per change, and `null` when there's nowhere to drop or the gesture ends. Pass `useCalendarDraftReporter()` so `useCalendarDraft` and `useDraftBusy` follow pointer drags. |
175
+ | `timeZone` | `string` | | Required. The calendar's time zone. |
176
+ | `columns` | `readonly TimeGridColumn[]` | | The day columns of a time axis, a time grid's or an hour timeline's: `projection.days.map((day) => day.column)` in a time grid, `projection.columns` in resource columns or an hour timeline. Leave it out in a month grid or a day timeline. |
177
+ | `snap` | `{ increment, smallestUnit, mode? }` | `15 minutes` | The wall-clock grid for times. |
178
+ | `scrollContainer` | `{ current: Element \| null }` | `the nearest scrollable ancestor` | An object whose current is the element to scroll while dragging near its edges. It's read when a drag starts. |
179
+ | `sidewaysScrollContainer` | `{ current: Element \| null }` | `scrollContainer` | An object whose `current` is an element inside `scrollContainer` to scroll in its place at the left and right edges, for a view that scrolls its two axes in two elements. It's read when a drag starts. |
180
+ | `announcer` | `CalendarAnnouncer` | `silent; ranges in the runtime's locale` | Speaks each drag through the root's `Announcer` and labels the drag preview's range the same way. Pass `useCalendarAnnouncer()`. See [pointer gestures](../accessibility.md#pointer-gestures). |
181
+ | `ghostClassName` | `string` | | Extra classes for the drag preview. |
182
+ | `preview` | `"snapped" \| "free"` | `"snapped"` | How the drag preview moves. `"snapped"` draws the event where a drop would land, slot by slot. `"free"` moves a copy of a moved event with the pointer over a marker of where it would land, and slides the copy there on release; a resize or create on a time axis keeps its edge under the pointer. Both propose, check and announce the same snapped placement. See [snapped and free drags](../interactions.md#snapped-and-free-drags). |
183
+ | `disabled` | `boolean` | `false` | Turns gestures off. Pass the Renderer's `isReadOnly`, so a calendar without `onEventChange` starts none. `attachCalendarPointer` also reads it when it attaches, to listen for touch moves only when enabled, so attach again when it changes; `useCalendarPointer` does. |
184
+
185
+ While a gesture runs, the region has `data-interaction="move"`, `"resize"`, or `"create"`, and the
186
+ event being dragged has `data-dragging`. Preview elements have `data-calendar-ghost="event"` or
187
+ `"range"`, and `data-invalid` or `data-warning` when `check` says a policy would reject or flag the
188
+ drop. Range previews read `--calendar-ghost-background` and `--calendar-ghost-radius`, event
189
+ previews `--calendar-ghost-shadow` and `--calendar-ghost-opacity`, and both
190
+ `--calendar-ghost-z-index`. The registry's themes put the surface's background under an event
191
+ preview, so a chip of an app's without a background of its own stays readable while it moves; set
192
+ `--calendar-ghost-event-background` to change it. A month's timed chip, see-through at rest, takes
193
+ its event colour while it moves.
194
+
195
+ With `preview: "free"`, the copy that follows the pointer is an event preview too. The marker of
196
+ where the drop would land has `data-calendar-ghost="landing"`, sits one layer below the copy, and
197
+ takes `data-invalid` or `data-warning` like the other previews. It reads
198
+ `--calendar-ghost-landing-background`, `--calendar-ghost-landing-shadow` and
199
+ `--calendar-ghost-radius`. On release the copy has `data-settling` while it slides into place, over
200
+ `--calendar-ghost-settle-duration` (150ms) with `--calendar-ghost-settle-easing` (`ease-out`). Under
201
+ `prefers-reduced-motion: reduce` it doesn't slide, and a theme that sets the duration to `0s` turns
202
+ the slide off too.
203
+
204
+ ### Drags from and to the rest of the page
205
+
206
+ These connect the views to drags that start or end outside the calendar, such as tasks dragged in
207
+ from a list or events dragged out to a bin. A drag-and-drop library's binding calls them with the
208
+ points it tracks; [dnd-kit's](./dnd-kit.md) is
209
+ `@moltenship/calendar-dnd-kit`. Every view that uses
210
+ `useCalendarPointer` takes part, through the options it passes, and read-only views take none.
211
+
212
+ `startCalendarDrop(source, { input? })` follows one item dragged in:
213
+
214
+ | Source field | Meaning |
215
+ | ------------ | -------------------------------------------------------------------------------------------------------------------------- |
216
+ | `event` | Your record the new event copies, such as a task mapped to your event type. The create change carries it as `change.event` |
217
+ | `duration` | How long it is over a time column. An hour by default |
218
+ | `days` | How many days it covers over day cells, such as a month cell or the all-day row. 1 by default |
219
+ | `eventId` | An event the calendar shows, to move instead of creating one; its start lands where it's dropped. Not a read-only one |
220
+ | `title` | What announcements call it |
221
+
222
+ `input` is `"pointer"` by default, or `"keyboard"` for a library's keyboard sensor. The result has
223
+ three methods and a property:
224
+
225
+ - `move(point)` takes a viewport point `{ x, y }`. It finds the view under it, previews the
226
+ placement a drop there would make as range boxes, checks it with the view's `check`, reports it
227
+ to `onPreview`, and announces it. Over a time column the item starts at the slot under the
228
+ point; in a resource view it books that resource. `move(null)` means the point is over a drop
229
+ zone of your own, which clears the preview.
230
+ - `drop()` proposes once through the view's `onPropose`, with the `input`, and resolves with the
231
+ result. It resolves `null` when it proposed nothing, over no view or for a move that changes
232
+ nothing, and when `onPropose` returns no result.
233
+ - `cancel()` ends it without proposing.
234
+ - `placement` is where a drop would land now, or `null`, as it is once the drag has ended.
235
+
236
+ The topmost element under the point decides which view it's over, so anything over a view, such
237
+ as a sheet or a dialog, hides it. Give a drag image of your own `pointer-events: none`, as
238
+ dnd-kit's has. From the first `move()` until `drop()` or `cancel()`, a frame loop scrolls the view
239
+ under the point near its edges, once the point has been clear of them or has rested at one for a
240
+ quarter of a second, so a drag that crosses an edge on its way in doesn't scroll the view.
241
+
242
+ `monitorCalendarDrags(monitor)` offers each event a view starts to move to your drop zones, or to
243
+ an animation that follows it, and returns a function that stops. The monitor gets
244
+ `{ event, element, origin, refresh }` and returns a follower, or nothing to leave the drag alone:
245
+
246
+ | Follower method | Called |
247
+ | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
248
+ | `move(point)` | On every pointer move |
249
+ | `preview(preview)` | Whenever the view's preview changes, or moves as the view scrolls: `{ rects, label, validity }`, its boxes in viewport coordinates, the time range it shows (`null` for a plain box), and `"invalid"` or `"warning"` when a policy would reject or flag the drop. `null` when the view shows no preview |
250
+ | `claims()` | Whenever the preview updates. Return `true` while one of your zones is under the pointer: the calendar then shows no preview, and a release there proposes and announces nothing |
251
+ | `end(dropped, landing)` | When the drag ends: `dropped` is `true` if it was released while you claimed it, so handle the drop; `false` after a drop in the calendar, Escape, or a release over nowhere. `landing` is the preview a release in the view proposed the move at, policies still to run, or `null` when it proposed nothing. No `preview(null)` comes first |
252
+
253
+ Call `refresh()` when your answer to `claims()` changes without the pointer moving. While a
254
+ follower with `claims` is on a drag, the view counts only where it's the topmost thing under the
255
+ pointer, as for drags in: over a sheet of your zones that covers it, it shows no preview and a
256
+ release proposes nothing. Off the view, covered or claimed, a copy of the event follows the
257
+ pointer, with `data-outside`. The view scrolls only while the pointer is over it, and once the
258
+ pointer has left, only after it has been clear of the edges again or rested at one. A follower
259
+ without `claims` only watches, as the [Motion guide](../guides/motion.md)'s card does, and changes
260
+ none of that: as without a follower, nothing shows off the view. Resizes and creates aren't
261
+ offered.
262
+
263
+ `observeCalendarRegions(observer)` hears the views on the page, `{ element, disabled }` each, now
264
+ and whenever one attaches or detaches, so a binding can register them with its library.
@@ -0,0 +1,245 @@
1
+ # Components and hooks
2
+
3
+ createCalendar, Root and its props, the components, hooks, actions, meta, and diagnostics.
4
+
5
+ Source: https://time.molten.sh/docs/react/api/components
6
+
7
+ Everything on this page is exported from `@moltenship/calendar`.
8
+
9
+ ## createCalendar
10
+
11
+ ```ts
12
+ const Calendar = createCalendar<TEvent, TResource, TSelection, TFocus>()(options);
13
+ ```
14
+
15
+ Creates a calendar: a set of components and hooks typed to your records. Call it once at module
16
+ scope. It's called twice: the first call takes your types, and the second infers the view names
17
+ from `views` and the ID types from the adapter.
18
+
19
+ - `TEvent`: your event record. Required.
20
+ - `TResource`: your resource record. Defaults to `unknown`; use `never` if you don't have resources.
21
+ - `TSelection`, `TFocus`: the types of the `selection` and `focus` state. Default to
22
+ `CalendarSelection` and `CalendarFocus`, the days, slots, and events the built-in views read and
23
+ write. A calendar with only custom views can use its own types.
24
+
25
+ | Name | Type | Default | Description |
26
+ | -------------------- | ------------------------------ | ------------------- | ------------------------------------------------------------------------------------------ |
27
+ | `eventAdapter` | `EventAdapter<TEvent>` | | Required. How to read your records. See [adapter](./events.md#adapter). |
28
+ | `views` | `readonly CalendarView[]` | | Views made with `defineCalendarView`. The first is the default view. Names must be unique. |
29
+ | `invalidEventPolicy` | `"report-and-skip" \| "throw"` | `"report-and-skip"` | What to do with invalid records. |
30
+
31
+ The returned object holds the components and hooks below, plus `views`, the list you passed in.
32
+ Use it to derive the view-name type: `(typeof Calendar.views)[number]["name"]`.
33
+
34
+ ## defineCalendarView
35
+
36
+ ```ts
37
+ const view = defineCalendarView({ name, defaultOptions, strategy, Renderer });
38
+ ```
39
+
40
+ Defines a view. `defaultOptions` is required only when the strategy's options can't be `undefined`.
41
+ [Custom views](../views/custom-views.md) covers the strategy, the projection input, and the
42
+ Renderer props. The related types are `CalendarViewStrategy`, `CalendarViewProjectionInput`, and
43
+ `CalendarViewRendererProps`.
44
+
45
+ `resolveViewInstantRange(range, timeZone)` turns visible dates into the instant range that `Root`
46
+ passes to `project` as `instantRange`, and `resolveViewLoadRange(strategy, anchor, environment,
47
+ options, range)` gives the `loadRange` it passes. Use them to run a strategy outside `Root`, for
48
+ example in a test.
49
+
50
+ `withAsciiSpaces(text)` writes the thin and narrow no-break spaces in `Intl` output as plain spaces.
51
+ Node.js and browsers disagree on them in date ranges, so wrap `formatRange` output that renders on
52
+ the server, as the built-in titles and views do, and hydration matches.
53
+
54
+ ## Root
55
+
56
+ `<Calendar.Root>` holds the state and provides it to everything inside. It renders no element of its
57
+ own.
58
+
59
+ | Name | Type | Default | Description |
60
+ | -------------------------------------------------- | ------------------------------------------------------------- | --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
61
+ | `events` | `readonly TEvent[] \| CalendarEventSource<TEvent>` | | Required. Your events. A new array holding the same records is treated as unchanged. A source is an external store `Root` subscribes to; see [events from an external store](../concepts/events.md#events-from-an-external-store). |
62
+ | `locale` | `Intl.Locale \| string` | | Required. Used by views to format dates and times. |
63
+ | `weekRules` | `CalendarWeekRules` | | Required. `{ firstDay, minimalDays, weekend }`, with days numbered 1 (Monday) to 7 (Sunday). `minimalDays` is the minimum number of days in the first week of a year. |
64
+ | `defaultAnchorDate` | `Temporal.PlainDate` | | Initial date, uncontrolled. Pass this or `anchorDate`. |
65
+ | `anchorDate` | `Temporal.PlainDate` | | Controlled date. |
66
+ | `defaultTimeZone` | `string` | | Initial IANA time zone, uncontrolled. Pass this or `timeZone`. |
67
+ | `timeZone` | `string` | | Controlled time zone. |
68
+ | `secondaryTimeZones` | `readonly (string \| { timeZone: string; label?: string })[]` | `[]` | Other IANA time zones that time grids label their hours in, beside the calendar's. A `label` names a zone in the header. Invalid entries are left out and reported as diagnostics. See [secondary time zones](../concepts/time.md#secondary-time-zones). |
69
+ | `defaultView` | `view name` | `the first registered view` | Initial view, uncontrolled. |
70
+ | `view` | `view name` | | Controlled view. |
71
+ | `viewOptions` | `{ [view]: Partial<options> }` | | Overrides for each view's `defaultOptions`, keyed by view name. |
72
+ | `defaultSelection / selection` | `TSelection \| null` | | Uncontrolled or controlled selection. |
73
+ | `defaultFocus / focus` | `TFocus \| null` | | Uncontrolled or controlled focus. |
74
+ | `defaultExpandedResourceIds / expandedResourceIds` | `readonly TResourceId[]` | | Uncontrolled or controlled expanded resources. |
75
+ | `onViewChange, onAnchorDateChange, …` | `(next, detail) => void` | | One handler per value. `detail` has `previous`, `controlled`, `slice`, why it changed (`reason`), who caused it (`source`, `"agent"` for an AI agent), the DOM `event` and `cancel()`. See [what a handler hears](../concepts/state.md#what-a-handler-hears). |
76
+ | `onEventChange` | `(change, detail) => void \| Promise<void>` | | Saves a proposed change. Return a promise to keep it pending until it settles. Without it the calendar is read-only. `detail.input` says what proposed it, as for `onEventChangeResult`, and `detail.fields` has what an agent sent beside the times, such as a title. See [Interactions](../interactions.md) and [saving what an agent sent](../agents/connect.md#save-what-the-agent-sent). |
77
+ | `onEventChangeResult` | `(result, detail) => void` | | Hears how each proposal ended, once it settles: the result `proposeEventChange` resolves with, and the detail it was proposed with, whose `input` is `"pointer"`, `"keyboard"`, `"api"` or `"agent"`. Pass an event history's `record` here to [undo and redo](../undo-redo.md). See [how changes end](../interactions.md#how-changes-end). |
78
+ | `policies` | `readonly CalendarPolicy[]` | | Run in order on every proposed change, after the built-in read-only check. See [policies](./changes.md#policies). |
79
+ | `resources` | `readonly TResource[]` | `[]` | Rooms, people, or anything else events are assigned to. |
80
+ | `availability` | `CalendarAvailability` | | Working hours: `weekly` rules, dated `exceptions`, and an optional `timeZone`. Views shade the closed time. See [Availability](../availability.md). |
81
+ | `annotations` | `readonly CalendarAnnotation[]` | `[]` | Read-only marks beside the events, such as sleep or music. See [Annotations](../annotations.md). |
82
+ | `annotationSources` | `readonly CalendarAnnotationSource[]` | `[]` | The annotation sources, in display order. A source left out is hidden. |
83
+ | `now` | `Temporal.Instant` | | Fixes the current time, so server and browser agree. Pass `now` or `clock`, not both. |
84
+ | `clock` | `{ instant(): Temporal.Instant }` | | A source of the current time. Without now or clock, Time uses the system clock. |
85
+ | `direction` | `"ltr" \| "rtl"` | `"ltr"` | Which way the arrow keys move. A view gets it as `environment.direction`, to scroll sideways and to set `dir` on its grid by it. `Root` doesn't set `dir` itself: set it on an ancestor to match; see [right-to-left](../accessibility.md#right-to-left). |
86
+ | `disambiguation` | `"compatible" \| "earlier" \| "later" \| "reject"` | `"compatible"` | Given to views as `environment.disambiguation`, for your own views to resolve skipped or repeated wall-clock times, and used for the wall-clock times an [agent](../agents/reference.md#events) sends. The registry's views, the pointer and the keyboard don't read it. See [daylight saving time](../concepts/time.md#daylight-saving-time). |
87
+ | `onVisibleRangeChange` | `(range: CalendarVisibleRange) => void` | | Called after mount and whenever the active view, its dates, or the time zone change, with the visible `range` and the `loadRange` to have events for. Each change is reported once, and never on the server. |
88
+ | `onDiagnosticsChange` | `(diagnostics) => void` | | Called after mount and whenever the [diagnostics](#diagnostics) change. |
89
+ | `id` | `string` | `a generated ID` | Base for element IDs, such as `{id}-frame`. |
90
+ | `label` | `string` | | The calendar's name, such as `"Team calendar"`. `Frame` takes it as its `aria-label`, so screen readers and [AI agents](../agents/connect.md#name-the-calendar) find the calendar by a name that stays the same while it navigates. Without it, the frame is labelled by the title. |
91
+ | `allowAgentDelete` | `boolean` | `false` | Gives an AI agent the `deleteEvent` action. Without it the calendar has no such action, a step that asks for it fails, and a delete an agent causes another way, such as by pressing a button of yours, is refused. Turn it on only with an agent bridge that asks a person first. See [Deleting](../agents/deleting.md). |
92
+ | `formatAgentEventLabel` | `(event: CalendarAgentEvent) => string` | | Names each visible event in the list an AI agent reads. By default the title and the times in ISO 8601 in the calendar's time zone. See the [agent reference](../agents/reference.md#snapshot-entry). |
93
+ | `store` | `CalendarStore` | | Use a store you created. See [State store](./store.md). |
94
+
95
+ You can write most props inline. `locale`, `weekRules`, `secondaryTimeZones`, `availability`, `now`,
96
+ and a controlled `anchorDate`, `timeZone` or `view` are compared by value; `events`, `resources`,
97
+ `annotations`, `annotationSources` and a controlled `expandedResourceIds` are compared item by item;
98
+ `policies`, `onDiagnosticsChange`, and the change handlers are read from the latest render.
99
+ `viewOptions` is too, but the active view's options are compared one option at a time, so keep
100
+ functions and objects in them stable. A
101
+ `clock` object and a controlled `selection` or `focus` are compared by identity: keep them stable,
102
+ for example in state or at module scope.
103
+
104
+ `onVisibleRangeChange` reports each change once under Strict Mode too, and when a hidden `Activity`
105
+ is revealed. See [loading events](../views/scrolling.md#loading-events-as-you-scroll) and
106
+ [TanStack Query](../guides/tanstack-query.md).
107
+
108
+ `Root` throws on its first render if it has no date (`calendar-root-requires-anchor-date`), no
109
+ time zone (`calendar-root-requires-time-zone`), or no view (`calendar-root-requires-view`).
110
+
111
+ ## Components
112
+
113
+ Use these inside `Root`. Each renders one plain element with a `data-calendar-part` attribute and
114
+ accepts that element's usual props, including `className`, `style`, `ref`, and event handlers.
115
+
116
+ | Component | Renders | Notes |
117
+ | ----------------- | ----------- | -------------------------------------------------------------------------------------------- |
118
+ | `Frame` | `<section>` | Outer wrapper. Gets the `{id}-frame` ID, and its name from `Root`'s `label` or the title. |
119
+ | `Toolbar` | `<header>` | Wrapper for controls. |
120
+ | `Title` | `<span>` | The active view's title, or its children. Gets the `{id}-title` ID. |
121
+ | `PreviousTrigger` | `<button>` | Moves back one step of the active view. Disabled when no view is active. |
122
+ | `NextTrigger` | `<button>` | Moves forward one step of the active view. Disabled when no view is active. |
123
+ | `TodayTrigger` | `<button>` | Moves to today in the calendar's time zone, from `now`, `clock`, or the system clock. |
124
+ | `ViewSwitcher` | `<select>` | One option per view. Requires `getViewLabel(name)`. |
125
+ | `Viewport` | `<div>` | Wrapper for the view. Gets the `{id}-viewport` ID. |
126
+ | `ActiveView` | view output | Renders the active view, or `fallback` if it isn't registered. |
127
+ | `Event` | your output | Looks up one event by `eventId` and calls `children` with it. |
128
+ | `Announcer` | `<div>` | A hidden live region that speaks moves, resizes, and creates. Requires `messages`. |
129
+
130
+ - The buttons default to `type="button"` and set `aria-controls` to the viewport. Give each one
131
+ text or an `aria-label`.
132
+ - Your `onClick` or `onChange` runs first. Call `event.preventDefault()` in it to skip the built-in
133
+ action.
134
+ - `Frame`, `Title`, and `Viewport` don't accept `id`. Set `id` on `Root` instead, so the IDs and
135
+ `aria-controls` always match.
136
+ - The parts are [ui-sdk](https://ui-sdk.dev) components, which is how an
137
+ [agent bridge](../agents/connect.md) finds a calendar. A calendar is listed for agents only when
138
+ it renders `Frame`. Events and cells stay elements your views render.
139
+
140
+ `Event` passes your record and its normalized form:
141
+
142
+ ```tsx
143
+ <Calendar.Event eventId="standup" fallback={<p>Not found</p>}>
144
+ {({ event, normalized }) => (
145
+ <p>
146
+ {event.title} starts at {normalized.start.toString()}
147
+ </p>
148
+ )}
149
+ </Calendar.Event>
150
+ ```
151
+
152
+ ## Hooks
153
+
154
+ The hooks on your calendar work anywhere inside its `Root`. Using them, or any component above,
155
+ outside `Root` throws `calendar-hook-outside-root`.
156
+
157
+ | Hook | Returns |
158
+ | --------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
159
+ | `useCalendar()` | `{ state, actions, meta }` |
160
+ | `useCalendarState()` | The six [state](../concepts/state.md) values |
161
+ | `useCalendarActions()` | The actions below. The object never changes. |
162
+ | `useCalendarMeta()` | The [meta](#meta) object |
163
+ | `useCalendarSelector(selector, opts?)` | `selector(state)`. Re-renders only when it changes. |
164
+ | `useCalendarPendingChanges(selector?, opts?)` | The changes still on their way, or `selector(changes)`. See [pending changes](../interactions.md#across-the-calendar). |
165
+ | `useVisibleRange()` | The active view's visible dates, or `null` |
166
+ | `useViewProjection()` | The active view and its projection, or `null` |
167
+
168
+ `useCalendarSelector` and `useCalendarPendingChanges` compare results with `Object.is`. Pass
169
+ `{ isEqual }` to compare another way. The selector can be an inline function.
170
+
171
+ `useCalendarHistory(history, { messages? })` is exported on its own too. It binds an event history
172
+ to the nearest `Root`, with `undo`, `redo`, `canUndo` and `canRedo`, and
173
+ `useCalendarHistoryShortcuts(history, options)` adds its keys, with the options `scope`, `undo`,
174
+ `redo` and `disabled`; see
175
+ [Undo and redo](../undo-redo.md).
176
+
177
+ `useCalendarPointer(options)` is exported on its own too. It returns the ref that turns drags in
178
+ a custom view into proposals; see the [pointer layer](./changes.md#pointer-layer). It's in
179
+ `@moltenship/calendar-react` from 2.0 on, and was in `@moltenship/calendar-dnd` in 1.x.
180
+
181
+ `Announcer`'s messages, and the keyboard hooks for your own views (`useCalendarKeyboard`,
182
+ `useRovingFocus`, `useCalendarInteraction`, `useCalendarAnnouncer`), are covered in
183
+ [Accessibility](../accessibility.md#announcements).
184
+
185
+ `useNow({ intervalMs })` is exported on its own, not from your calendar. It returns the current
186
+ instant from the nearest `Root`'s `now` or `clock`, or the system clock, and samples it every
187
+ `intervalMs` (one minute by default). It returns `null` during server rendering and hydration unless
188
+ `Root` has `now`.
189
+
190
+ `useAnchorDateRequests(listener)` calls `listener(date, range)` with every date the calendar is
191
+ asked to show: from Previous, Next, Today, keys paging past the view, or `setAnchorDate`. That
192
+ includes a date that is already the anchor. `range` holds the dates the active view shows for
193
+ `date`, so a week view can tell Today inside its week from a date that moves it. A view whose
194
+ scroll position can run ahead of the anchor uses it to show its range again when Today asks for
195
+ it. The [scrolling views](../views/scrolling.md) do this.
196
+
197
+ ### Actions
198
+
199
+ | Action | Effect |
200
+ | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
201
+ | `setView(name, options?)` | Changes the view. Every setter and navigation action takes `{ event?, reason?, source? }` last, for the [change handler](../concepts/state.md#what-a-handler-hears) |
202
+ | `setAnchorDate(date)` | Changes the date |
203
+ | `setTimeZone(zone)` | Changes the time zone |
204
+ | `setSelection(value)` | Changes the selection (`null` clears it) |
205
+ | `setFocus(value)` | Changes the focus (`null` clears it) |
206
+ | `setExpandedResourceIds(ids)` | Changes the expanded resources |
207
+ | `navigatePrevious()`, `navigateNext()` | Moves by one step of the active view |
208
+ | `navigateToday()` | Moves to today in the calendar's time zone |
209
+ | `proposeEventChange(proposal, detail?)` | Proposes a change to an event and resolves with the outcome. `detail.input` names the input for policies, `onEventChange` and `onEventChangeResult`, `"api"` by default. See [Interactions](../interactions.md#changing-events-from-your-own-ui). |
210
+ | `checkEventChange(proposal, detail?)` | Runs the policies on a proposal without showing or saving it. Returns `{ status: "accepted", change }` or `{ status: "rejected", change, reason }`, or `null` for an unknown event or an async policy. |
211
+
212
+ Setting the current value again (the same date, view, time zone or resource IDs, or the same
213
+ `selection` or `focus` object) doesn't change state or call its handler, unless the value is
214
+ controlled and you haven't applied a change the calendar asked for (see
215
+ [State](../concepts/state.md)). `useAnchorDateRequests` still hears a request for the current anchor
216
+ date. Calling two actions in a row builds on the
217
+ first, so `navigateNext(); navigateNext()` moves two steps, even for controlled values.
218
+
219
+ ### Meta
220
+
221
+ | Name | Type | Description |
222
+ | --------------- | ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
223
+ | `eventSnapshot` | `EventSnapshot` | Validated, indexed events. See [snapshots](./events.md#snapshots). |
224
+ | `resources` | `readonly TResource[]` | The resources prop. |
225
+ | `environment` | `CalendarEnvironment` | `locale`, `timeZone`, `secondaryTimeZones`, `weekRules`, `direction`, `disambiguation`, and `now` or `clock` when set. |
226
+ | `activeView` | `CalendarView \| undefined` | The active view's definition, if it's registered. |
227
+ | `views` | `readonly CalendarView[]` | The registered views. |
228
+ | `diagnostics` | `readonly CalendarDiagnostic[]` | See below. |
229
+ | `ids` | `{ frame, title, viewport }` | Element IDs. |
230
+ | `refs` | `{ frame, title, toolbar, viewport }` | Refs to the rendered elements. |
231
+ | `instanceId` | `string` | The base for the element IDs. |
232
+ | `label` | `string \| undefined` | Root's label prop. |
233
+
234
+ ## Diagnostics
235
+
236
+ Problems that don't stop rendering are collected in `meta.diagnostics` and passed to
237
+ `onDiagnosticsChange`. Time doesn't log them.
238
+
239
+ | `code` | `severity` | Cause |
240
+ | ----------------------------- | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
241
+ | `unregistered-active-view` | error | The `view` state names a view that isn't registered. |
242
+ | `invalid-event` | error | A record was skipped. `issue` has the details ([issue codes](./events.md#invalid-records)). |
243
+ | `invalid-annotation` | error | An annotation was skipped. `issue` has its `code`, `index`, and the `annotation`. |
244
+ | `invalid-availability` | error | A working-hours rule, exception, or time zone was left out. `issue` has the `code`, the `value`, and the `resourceId` when it's a resource's. |
245
+ | `invalid-secondary-time-zone` | error | An entry of `secondaryTimeZones` was left out. `issue` has the `value`, and its `index` in a list. |