@moltenship/calendar 1.0.0-rc.2 → 2.0.0-beta.1

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 (70) hide show
  1. package/README.md +24 -4
  2. package/dist/index.d.mts +2 -2
  3. package/docs/accessibility.md +304 -0
  4. package/docs/agents/changes.md +449 -0
  5. package/docs/agents/coding-agents.md +117 -0
  6. package/docs/agents/connect.md +435 -0
  7. package/docs/agents/deleting.md +296 -0
  8. package/docs/agents/reference.md +512 -0
  9. package/docs/agents/server.md +317 -0
  10. package/docs/agents/webmcp.md +153 -0
  11. package/docs/agents.md +353 -0
  12. package/docs/annotations.md +196 -0
  13. package/docs/api/changes.md +248 -0
  14. package/docs/api/dnd-kit.md +267 -0
  15. package/docs/api/events.md +152 -0
  16. package/docs/api/ics.md +524 -0
  17. package/docs/api/primitives.md +168 -0
  18. package/docs/api/react.md +236 -0
  19. package/docs/api/recurrence.md +586 -0
  20. package/docs/api/solid.md +460 -0
  21. package/docs/api/store.md +92 -0
  22. package/docs/api/temporal.md +172 -0
  23. package/docs/api.md +57 -0
  24. package/docs/availability.md +573 -0
  25. package/docs/comparison.md +279 -0
  26. package/docs/concepts/anatomy.md +73 -0
  27. package/docs/concepts/events.md +164 -0
  28. package/docs/concepts/how-it-works.md +95 -0
  29. package/docs/concepts/recurrence.md +127 -0
  30. package/docs/concepts/state.md +244 -0
  31. package/docs/concepts/time.md +170 -0
  32. package/docs/guides/dnd-kit.md +333 -0
  33. package/docs/guides/google-calendar-sync.md +1246 -0
  34. package/docs/guides/google-calendar.md +367 -0
  35. package/docs/guides/ics.md +486 -0
  36. package/docs/guides/motion.md +414 -0
  37. package/docs/guides/nextjs-app-router.md +630 -0
  38. package/docs/guides/nextjs.md +149 -0
  39. package/docs/guides/performance.md +103 -0
  40. package/docs/guides/recurring-events.md +583 -0
  41. package/docs/guides/tanstack-query.md +485 -0
  42. package/docs/index.md +118 -0
  43. package/docs/installation.md +194 -0
  44. package/docs/interactions.md +408 -0
  45. package/docs/llms.txt +86 -0
  46. package/docs/migrating-to-2.md +322 -0
  47. package/docs/quick-start.md +159 -0
  48. package/docs/stylex.md +265 -0
  49. package/docs/testing.md +581 -0
  50. package/docs/theme-builder.md +81 -0
  51. package/docs/theming.md +169 -0
  52. package/docs/undo-redo.md +339 -0
  53. package/docs/views/agenda.md +221 -0
  54. package/docs/views/custom-views.md +192 -0
  55. package/docs/views/month.md +109 -0
  56. package/docs/views/resource-columns.md +261 -0
  57. package/docs/views/resource-timeline.md +225 -0
  58. package/docs/views/scrolling.md +192 -0
  59. package/docs/views/week-and-day.md +257 -0
  60. package/docs/views/year.md +138 -0
  61. package/docs/views.md +69 -0
  62. package/package.json +41 -14
  63. package/skills/moltenship-time/SKILL.md +75 -0
  64. package/skills/moltenship-time/references/agent-ready.md +272 -0
  65. package/skills/moltenship-time/references/changes.md +188 -0
  66. package/skills/moltenship-time/references/compose.md +168 -0
  67. package/skills/moltenship-time/references/mistakes.md +98 -0
  68. package/skills/moltenship-time/references/solid.md +202 -0
  69. package/skills/moltenship-time/references/state.md +129 -0
  70. package/skills/moltenship-time/references/testing.md +176 -0
@@ -0,0 +1,169 @@
1
+ # Theming
2
+
3
+ Calendar color tokens, dark mode, and the event color palette.
4
+
5
+ Source: https://time.molten.sh/docs/theming
6
+
7
+ The packages don't ship any CSS. The styled parts in the registry read their colors and sizes from
8
+ CSS variables defined in `calendar-theme.css`. The `calendar-theme` item, which every view brings,
9
+ adds its tokens and rules to your global CSS, as described in
10
+ [UI source](./installation.md#ui-source-optional). Override the variables in your own CSS to
11
+ restyle the calendar, as [Changing tokens](#changing-tokens) shows: each `shadcn add` writes the
12
+ theme's own block again. To try changes live and copy the CSS, use the
13
+ [Theme builder](./theme-builder.md).
14
+
15
+ This page covers the Tailwind baseline. The `stylex-*` items keep the same token names, as StyleX
16
+ variables you override with `stylex.createTheme`; see [StyleX](./stylex.md#change-the-tokens).
17
+
18
+ ## Tokens
19
+
20
+ `calendar-theme.css` defines the standard shadcn/ui tokens (`--background`, `--primary`,
21
+ `--border`, and so on) plus these calendar tokens. `shadcn add` adds only the calendar tokens, since
22
+ your app has its own shadcn theme:
23
+
24
+ | Variable | Used for | Tailwind class |
25
+ | ----------------------------- | ----------------------------------------------------- | --------------------------------- |
26
+ | `--calendar-surface` | Behind sticky headers, between events | `bg-calendar-surface` |
27
+ | `--calendar-grid` | Lines between days and hours | `border-calendar-grid` |
28
+ | `--calendar-axis` | Hour and weekday labels | `text-calendar-axis` |
29
+ | `--calendar-today` | Today's date marker | `bg-calendar-today` |
30
+ | `--calendar-today-foreground` | Text on today's marker | `text-calendar-today-foreground` |
31
+ | `--calendar-now` | The current-time line | `bg-calendar-now` |
32
+ | `--calendar-selection` | Selected days and time ranges | `bg-calendar-selection` |
33
+ | `--calendar-weekend` | Weekend background | `bg-calendar-weekend` |
34
+ | `--calendar-unavailable` | Closed time in time grids and timelines | `bg-calendar-unavailable` |
35
+ | `--calendar-closed` | Closed days in the month and year views | `bg-calendar-closed` |
36
+ | `--calendar-busy` | A resource status's busy dot | `bg-calendar-busy` |
37
+ | `--calendar-free` | A resource status's free dot | `bg-calendar-free` |
38
+ | `--calendar-invalid` | A preview the policies would reject | `outline-calendar-invalid` |
39
+ | `--calendar-warning` | A preview the policies would flag | `outline-calendar-warning` |
40
+ | `--calendar-event` | Event background | `bg-calendar-event` |
41
+ | `--calendar-event-foreground` | Event text | `text-calendar-event-foreground` |
42
+ | `--calendar-event-border` | Event accent edge | `border-calendar-event-border` |
43
+ | `--calendar-hour-height` | Height of one hour in time grids (`3rem`) | `h-(--calendar-hour-height)` |
44
+ | `--calendar-event-padding-x` | Padding at the sides of time-grid events (`0.375rem`) | `px-(--calendar-event-padding-x)` |
45
+ | `--calendar-event-padding-y` | Padding above and below time-grid events (`0.25rem`) | `py-(--calendar-event-padding-y)` |
46
+
47
+ The color tokens work with any Tailwind color utility, so `text-calendar-today` and
48
+ `ring-calendar-now` work too. Most calendar tokens derive from the shadcn tokens: `--calendar-grid`
49
+ is your `--border`, and the default event colors mix your `--primary` into `--background`.
50
+
51
+ The event padding tokens set how roomy events are in the week, day and resource columns views,
52
+ along with `--calendar-hour-height`. The views fall back to the default padding where they read
53
+ them, so a copy of `calendar-theme.css` from before these tokens keeps working.
54
+
55
+ ## Changing tokens
56
+
57
+ Every token is declared inside `@layer base`, so a plain rule in your own CSS wins without
58
+ `!important`. Set the light values on `:root` and the dark values on `.dark`:
59
+
60
+ ```css title="globals.css"
61
+ :root {
62
+ --calendar-today: oklch(0.55 0.17 150);
63
+ --calendar-hour-height: 4rem;
64
+ }
65
+
66
+ .dark {
67
+ --calendar-today: oklch(0.72 0.15 150);
68
+ }
69
+ ```
70
+
71
+ If your app already defines the shadcn tokens, the calendar follows them automatically.
72
+
73
+ `--calendar-surface` is unset by default and falls back to `--background`. Set it on the
74
+ calendar's container when that container has its own background, such as a card, so sticky
75
+ headers and gutters match it:
76
+
77
+ ```tsx
78
+ <main className="bg-card [--calendar-surface:var(--card)]">
79
+ ```
80
+
81
+ ## Dark mode
82
+
83
+ The theme switches when an ancestor of the calendar has the `dark` class, which is how shadcn/ui
84
+ and `next-themes` work. shadcn apps already define the matching Tailwind `dark` variant. If yours
85
+ doesn't, add `@custom-variant dark (&:is(.dark *));` below the imports in your global CSS.
86
+
87
+ ## Event colors
88
+
89
+ The theme has a palette of nine event colors: `blue`, `green`, `red`, `orange`, `yellow`,
90
+ `purple`, `pink`, `teal`, and `gray`. Put one in a `data-color` attribute and that element's three
91
+ event tokens switch to the color, in both light and dark mode:
92
+
93
+ ```html
94
+ <div data-color="green" class="bg-calendar-event text-calendar-event-foreground">Standup</div>
95
+ ```
96
+
97
+ `EventChip`, the event button in `registry/calendar`, sets `data-color` from its `color` prop. The
98
+ names are exported from `event-colors.ts` as `calendarEventColors`, with the type
99
+ `CalendarEventColor`.
100
+
101
+ ### Choosing a color per event
102
+
103
+ Every built-in view takes an optional `getEventColor` option: a function from your event record to
104
+ a color name. Pass it when you create the view, as the [Quick start](./quick-start.md) does, or
105
+ per calendar with the `viewOptions` prop on `Root`:
106
+
107
+ ```tsx
108
+ const getEventColor = (meeting: Meeting) => (meeting.title === "Standup" ? "green" : "blue");
109
+
110
+ // On Root:
111
+ viewOptions={{ month: { getEventColor }, agenda: { getEventColor } }}
112
+ ```
113
+
114
+ Define the function outside your component, so it keeps its identity between renders. See
115
+ [Performance](./guides/performance.md#keep-functions-in-options-stable). Without `getEventColor`,
116
+ events use the theme's default event tokens.
117
+
118
+ To support it in your own view, add it to the view's options and pass the result to `EventChip`:
119
+
120
+ ```tsx title="upcoming-view.tsx"
121
+ import {
122
+ defineCalendarView,
123
+ plainDateInterval,
124
+ type CalendarViewProjectionInput,
125
+ } from "@moltenship/calendar";
126
+
127
+ import { EventChip } from "@/components/calendar/event-chip";
128
+ import type { CalendarEventColor } from "@/components/calendar/event-colors";
129
+
130
+ import type { Meeting } from "./quick-start";
131
+
132
+ interface UpcomingOptions {
133
+ readonly getEventColor?: (meeting: Meeting) => CalendarEventColor;
134
+ }
135
+
136
+ export const upcomingView = defineCalendarView({
137
+ name: "upcoming",
138
+ defaultOptions: {},
139
+ strategy: {
140
+ getRange: (anchor) => plainDateInterval(anchor, anchor.add({ days: 7 })),
141
+ navigate: (anchor, delta) => anchor.add({ weeks: delta }),
142
+ getTitle: (range, { locale }) => range.start.toLocaleString(locale, { dateStyle: "medium" }),
143
+ project: ({ snapshot, instantRange }: CalendarViewProjectionInput<UpcomingOptions, Meeting>) =>
144
+ snapshot.queryTimed(instantRange),
145
+ },
146
+ Renderer: ({ projection, options }) => (
147
+ <ul>
148
+ {projection.map(({ event }) => (
149
+ <li key={event.id}>
150
+ <EventChip color={options.getEventColor?.(event)}>{event.title}</EventChip>
151
+ </li>
152
+ ))}
153
+ </ul>
154
+ ),
155
+ });
156
+ ```
157
+
158
+ ### Adding a color
159
+
160
+ Each palette entry only sets a hue and a chroma; the `[data-color]` rule turns them into the three
161
+ event tokens for light and dark mode. To add a color, add its name to `calendarEventColors` in
162
+ `event-colors.ts` and give it a hue and chroma in your CSS:
163
+
164
+ ```css title="globals.css"
165
+ [data-color="brand"] {
166
+ --calendar-event-hue: 285;
167
+ --calendar-event-chroma: 0.2;
168
+ }
169
+ ```
@@ -0,0 +1,339 @@
1
+ # Undo and redo
2
+
3
+ Record the changes people make, and take them back through the same pipeline that saved them.
4
+
5
+ Source: https://time.molten.sh/docs/undo-redo
6
+
7
+ > Live example: see it at https://time.molten.sh/docs/undo-redo
8
+
9
+ An event history records the changes your calendar commits, and undoes them by proposing the
10
+ inverse change. The inverse goes through the same pipeline as a drag: your policies check it, the
11
+ calendar shows it while it saves, and your `onEventChange` saves it. Redo proposes the change again.
12
+
13
+ It's opt-in, and each part is separate: recording, the buttons you draw, the keyboard shortcuts and
14
+ the registry's undo toast. A calendar without a history records nothing, listens for no keys, and
15
+ bundles none of its code.
16
+
17
+ This page uses the `Calendar` and `Meeting` from the [Quick start](./quick-start.md). The example
18
+ above also renders the [undo toast](#undo-toast).
19
+
20
+ ## Connect a history
21
+
22
+ Create a history with `createEventHistory` and pass its `record` to `Root`'s `onEventChangeResult`,
23
+ which hears how every proposal ended. If you have your own `onEventChangeResult`, call
24
+ `history.record(result, detail)` from it.
25
+
26
+ ```tsx title="undoable-calendar.tsx"
27
+ export function UndoableCalendar() {
28
+ const [meetings, setMeetings] = useState(initialMeetings);
29
+ // The meeting each create became, by change ID, so the history can find it to undo.
30
+ const [createdIds] = useState(() => new Map<string, string>());
31
+ const [history] = useState(() =>
32
+ createEventHistory<Meeting, string, never>({
33
+ limit: 50,
34
+ // Once the meetings show it.
35
+ createdEventId: (change, events) => {
36
+ const id = createdIds.get(change.id);
37
+ return id !== undefined && events.get(id) !== undefined ? id : undefined;
38
+ },
39
+ }),
40
+ );
41
+
42
+ return (
43
+ <Calendar.Root
44
+ events={meetings}
45
+ onEventChange={(change) => {
46
+ // A restored meeting keeps its ID; one made from a range gets a new one.
47
+ const id =
48
+ change.cause === "create" ? (change.event?.id ?? crypto.randomUUID()) : undefined;
49
+ if (id !== undefined) createdIds.set(change.id, id);
50
+ setMeetings((current) => applyChange(current, change, id));
51
+ }}
52
+ onEventChangeResult={history.record}
53
+ policies={[timedOnly]}
54
+ defaultAnchorDate={Temporal.PlainDate.from("2026-10-08")}
55
+ defaultTimeZone="Europe/Berlin"
56
+ locale="en-US"
57
+ weekRules={weekRules}
58
+ >
59
+ <Calendar.Frame className="flex h-full flex-col">
60
+ <CalendarToolbar calendar={Calendar}>
61
+ <UndoButtons history={history} />
62
+ </CalendarToolbar>
63
+ <Calendar.Viewport className="min-h-0 flex-1">
64
+ <Calendar.ActiveView />
65
+ </Calendar.Viewport>
66
+ </Calendar.Frame>
67
+ <Calendar.Announcer messages={calendarAnnouncements} />
68
+ {/* An Undo toast after each change, with Mod+Z and Shift+Mod+Z in the frame. */}
69
+ <CalendarHistoryToast calendar={Calendar} history={history} />
70
+ </Calendar.Root>
71
+ );
72
+ }
73
+ ```
74
+
75
+ Inside `Root`, `useCalendarHistory(history)` binds the history to the calendar: `undo()` and
76
+ `redo()` propose through the root's `proposeEventChange`, and `canUndo` and `canRedo` say whether
77
+ there is anything to take.
78
+
79
+ ```tsx title="undoable-calendar.tsx"
80
+ // Anywhere inside Root.
81
+ function UndoButtons({ history }: { readonly history: MeetingHistory }) {
82
+ const { canRedo, canUndo, redo, undo } = useCalendarHistory(history, {
83
+ messages: calendarHistoryAnnouncements,
84
+ });
85
+
86
+ return (
87
+ <div className="flex gap-1">
88
+ <Button disabled={!canUndo} onClick={() => undo()} variant="ghost">
89
+ Undo
90
+ </Button>
91
+ <Button disabled={!canRedo} onClick={() => redo()} variant="ghost">
92
+ Redo
93
+ </Button>
94
+ </div>
95
+ );
96
+ }
97
+ ```
98
+
99
+ `useCalendarHistory` returns:
100
+
101
+ | Field | Contents |
102
+ | ------------------ | ----------------------------------------------------------------------------------------------------- |
103
+ | `undo({ input? })` | Takes the last step back. Resolves with the [outcome](#outcomes) |
104
+ | `redo({ input? })` | Takes the last undone step forward again. Resolves with the outcome |
105
+ | `canUndo` | Whether there is a step to undo |
106
+ | `canRedo` | Whether there is a step to redo |
107
+ | `past`, `future` | The steps undo and redo take, oldest first: each takes the last |
108
+ | `pending` | `{ direction, step }` while an undo or redo waits for its result, or `null` |
109
+ | `latest` | The latest thing the history did: `{ type: "record", step }` or `{ type: "undo" \| "redo", outcome }` |
110
+
111
+ `input` says where the command came from, `"api"` by default. Your `onEventChangeResult` gets it
112
+ back, with `history: "undo"` or `"redo"` on the detail, so it can tell an undo from a drag. The
113
+ server and hydration read an empty history.
114
+
115
+ ## Keyboard shortcuts
116
+
117
+ `useCalendarHistoryShortcuts(history, { scope })` adds undo and redo keys to an element, usually the
118
+ root's frame. They're Mod+Z to undo and Shift+Mod+Z or Ctrl+Y to redo, where Mod is ⌘ on Apple
119
+ platforms and Ctrl elsewhere.
120
+
121
+ ```tsx
122
+ const history = useCalendarHistory(eventHistory, { messages: calendarHistoryAnnouncements });
123
+ useCalendarHistoryShortcuts(history, { scope: Calendar.useCalendarMeta().refs.frame });
124
+ ```
125
+
126
+ | Option | Default | Effect |
127
+ | ---------- | --------------------------- | ----------------------------------------------------- |
128
+ | `scope` | required | The element whose keys undo and redo |
129
+ | `undo` | `["Mod+Z"]` | Keys that undo: modifiers joined by `+`, then the key |
130
+ | `redo` | `["Shift+Mod+Z", "Ctrl+Y"]` | Keys that redo. `[]` turns an action's keys off |
131
+ | `disabled` | `false` | Listens for nothing |
132
+
133
+ While it's mounted and enabled, the hook adds one `keydown` listener to the document, which acts
134
+ only on keys whose target is inside the scope, after the page's own handlers, React's included.
135
+ Keys elsewhere on the page are left alone, as are dialogs rendered in a portal outside the scope,
136
+ and so are keys:
137
+
138
+ - in a text field or an editable element, where the browser undoes the text;
139
+ - in a dialog, menu or list inside the scope;
140
+ - during a keyboard grab or a pointer drag, or while an input method composes text;
141
+ - that something else already handled.
142
+
143
+ A key matches by the letter it types. One that types no Latin letter, as on a Russian layout or
144
+ with Option on a Mac, matches by its position, so Ctrl+Z still works there. Commands from the keys
145
+ pass `{ input: "keyboard" }`.
146
+
147
+ ## Undo toast
148
+
149
+ The registry's `calendar-history-toast` item is an "Undo" toast built on Base UI's Toast. After each
150
+ change it offers to undo it, and after an undo, to redo it. It also adds the keys above in the
151
+ calendar's frame and speaks undo and redo through the `Announcer`. Install it with the
152
+ [shadcn CLI](./installation.md#ui-source-optional), then render it inside `Root`:
153
+
154
+ ```tsx
155
+ import { CalendarHistoryToast } from "@/components/calendar/calendar-history-toast/calendar-history-toast";
156
+
157
+ <Calendar.Root onEventChangeResult={history.record} …>
158
+ …
159
+ <CalendarHistoryToast calendar={Calendar} history={history} />
160
+ </Calendar.Root>;
161
+ ```
162
+
163
+ | Prop | Default | Effect |
164
+ | --------------- | ------------------------------ | ---------------------------------------------------------------------- |
165
+ | `calendar` | required | Your calendar, for its frame and event titles |
166
+ | `history` | required | The history `onEventChangeResult` records into |
167
+ | `messages` | `calendarHistoryToastMessages` | What the toast says: English, in the item's file, to edit or translate |
168
+ | `announcements` | `calendarHistoryAnnouncements` | What the `Announcer` says after an undo or redo; `null` says nothing |
169
+ | `shortcuts` | the default keys | `{ undo?, redo? }` to change them, `false` to turn them off |
170
+ | `timeout` | `6000` | How long a toast stays, in milliseconds |
171
+ | `className` | | Classes for the toast's region, such as where it sits |
172
+
173
+ One toast shows at a time, and a cleared history closes it. A message that returns `null` shows no
174
+ toast and closes the one on screen: the English set does so for an empty stack or a change you
175
+ cancelled. The toast's region doesn't speak, so nothing is said twice: changes made by a gesture
176
+ are announced as they're made, and undo and redo by the `Announcer`. Deletes, updates and changes
177
+ from your own UI, which no gesture announced, are spoken once with how to reach Undo
178
+ (`recordedAnnouncement`), and that toast stays at least 10 seconds, long enough to hear it out and
179
+ press F6. The region's name is `region`.
180
+
181
+ ## What gets recorded
182
+
183
+ A history records a change only when it committed: a policy's rejection, a failed save, a cancel or
184
+ a proposal a newer one superseded never becomes a step. Its own undos and redos don't either. A new
185
+ step clears what redo would take forward.
186
+
187
+ Each step changes one event: where it was before (`before`) and where the step left it (`after`),
188
+ with `null` where there's no event, as before a create or after a delete. A step also keeps its
189
+ `cause`, the `input` that made it, your record (`event`), the event's ID and the changes it was made
190
+ of.
191
+
192
+ An [AI agent](./agents.md)'s committed changes are recorded like anyone else's, with the input
193
+ `"agent"`, so one undo stack covers what people and agents did. To give agents an undo stack of
194
+ their own, see [Undo an agent's changes](./agents/changes.md#undo-an-agents-changes).
195
+
196
+ A step holds a placement and nothing else. When an agent renames an event, the history records
197
+ the change and its undo proposes the same placement, without the old title: restore the fields
198
+ your app saved yourself, from the step's `event`, as that section shows.
199
+
200
+ `createEventHistory` takes these options:
201
+
202
+ | Option | Default | Effect |
203
+ | -------------------------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
204
+ | `limit` | `100` | The most steps the undo stack keeps; the oldest drops. `0` records nothing |
205
+ | `inputs` | all four | The inputs whose changes are recorded: `"pointer"`, `"keyboard"`, `"api"`, `"agent"` |
206
+ | `filter(change, detail)` | keeps all | Records a change only when it returns `true` |
207
+ | `coalesce(change, step, detail)` | never | Return `true` to fold a change into the step on top, when both change the same event: the step keeps its `before`, takes the new `after` |
208
+ | `createdEventId(change, events)` | none | The event a committed create became. Without it, creates aren't recorded. See [creates and deletes](#creates-and-deletes) |
209
+
210
+ A keyboard grab is already one step: arrow keys move its preview, and Enter proposes once.
211
+ `coalesce` is for several proposals you want undone together, such as nudges from your own buttons.
212
+ A step that spans several events isn't supported yet.
213
+
214
+ ## How undo works
215
+
216
+ | Step | Undo proposes | Redo proposes |
217
+ | -------------------- | ------------------------------------------------------------------------ | ----------------------------------------- |
218
+ | move, resize, update | the same cause, with the placement `before`, resources included | the same, with the placement `after` |
219
+ | delete | a create with the deleted record: `{ cause: "create", event, proposed }` | a delete of the restored event |
220
+ | create | a delete of the event it became | a create with the record the undo removed |
221
+
222
+ Undos and redos run one at a time: pressing undo three times undoes three steps, in order. An undo
223
+ pressed while a change still saves waits for it, so it takes that change back rather than the one
224
+ before. It waits for every change in the calendar, so a save that never ends holds undo and redo.
225
+ When an inverse commits, its step moves to the other stack, with the placement that was saved,
226
+ since a policy may have adjusted it. A redo that commits after a new change goes back on top of the
227
+ undo stack.
228
+
229
+ ### Outcomes
230
+
231
+ `undo()` and `redo()` resolve with one of these. Through `useCalendarHistory`, they reject only if
232
+ your `createdEventId` throws.
233
+
234
+ | `status` | When |
235
+ | ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
236
+ | `"committed"` | The inverse saved. `result` is its transaction result, `step` the step as it is now |
237
+ | `"rejected"` | A policy rejected the inverse, the save failed, or a drag superseded it. Or `createdEventId` can't name the event yet (`unknown-event`). The step stays where it was, so the user can try again |
238
+ | `"stale"` | The step's event changed elsewhere since. The step is dropped and nothing is proposed |
239
+ | `"empty"` | There was nothing to undo or redo |
240
+
241
+ ### Changes from elsewhere
242
+
243
+ Before it proposes, the history checks that the event is still where the step left it: at `after`
244
+ for an undo, at `before` for a redo, gone for an undone create, and so on. If another user moved
245
+ it, a server push deleted it, or someone restored it first, the step is stale. The history drops it
246
+ rather than move the event back over that change, and the next undo goes on with the next step.
247
+
248
+ Only the placement counts. A title changed elsewhere doesn't make a step stale, and since an undo
249
+ proposes only a placement, your handler keeps the new title.
250
+
251
+ ## Creates and deletes
252
+
253
+ Undoing a delete proposes a create that carries the deleted record as `change.event`. Restore it in
254
+ your handler: a create with `event: null` is a new event, as from a range dragged out in a view.
255
+
256
+ ```tsx title="undoable-calendar.tsx"
257
+ function applyChange(
258
+ meetings: readonly Meeting[],
259
+ change: MeetingChange,
260
+ id = crypto.randomUUID(),
261
+ ): readonly Meeting[] {
262
+ if (change.cause === "delete") {
263
+ return meetings.filter((meeting) => meeting.id !== change.eventId);
264
+ }
265
+ if (change.proposed.kind !== "timed") return meetings;
266
+
267
+ const { start, end } = change.proposed;
268
+ if (change.cause === "create") {
269
+ // Undoing a delete proposes a create with the deleted meeting: bring it back as it was.
270
+ const meeting = change.event ?? { id, title: "New meeting", color: "blue" as const };
271
+ return [...meetings, { ...meeting, start, end }];
272
+ }
273
+ return meetings.map((meeting) =>
274
+ meeting.id === change.eventId ? { ...meeting, start, end } : meeting,
275
+ );
276
+ }
277
+ ```
278
+
279
+ The calendar can't tell which event a create became, so the history needs your help to undo one:
280
+
281
+ - **A restored event** is looked for under the ID it had. If you restore records as they were, under
282
+ their own IDs, there is nothing to do.
283
+ - **`createdEventId(change, events)`** returns the event a committed create became, or `undefined`
284
+ while your events don't show it yet. The history asks it when it undoes or redoes the step, not
285
+ when it records it. With it, creates are recorded, and a restored event that got a new ID, as
286
+ from a server that assigns them, is found under that ID. The other steps for the event follow it
287
+ to the new ID.
288
+ - **An event it can't name** leaves the step for another try (`unknown-event`). If newer events
289
+ still don't have it, it was deleted somewhere the history didn't see, and the step is dropped as
290
+ stale.
291
+
292
+ If your handler can't restore a deleted record, leave deletes out:
293
+ `filter: (change) => change.cause !== "delete"`.
294
+
295
+ ## Recurring events
296
+
297
+ Changes to occurrences of a recurring event aren't supported yet. Your handler turns such a change
298
+ into an edit of the series ("this event", "this and following", "all events"), and taking back a
299
+ split series or a shifted one isn't a change of one event's placement. Leave them out with the
300
+ recurrence package's `isRecurringChange`:
301
+
302
+ ```ts
303
+ import { isRecurringChange } from "@moltenship/calendar-recurrence";
304
+
305
+ const history = createEventHistory<TeamEvent, string, string>({
306
+ filter: (change) => !isRecurringChange(change),
307
+ });
308
+ ```
309
+
310
+ ## Announcements
311
+
312
+ With `messages`, `useCalendarHistory` speaks each undo and redo outcome through the root's
313
+ `Announcer`, such as "Undid the move: Design review is back at Thursday, October 8, 3:00 – 4:00
314
+ PM." The packages ship no text: the registry's `calendar/announcements.ts` has an English set,
315
+ `calendarHistoryAnnouncements`, to edit or translate. Each message gets the outcome and the
316
+ announcement context, with the step's event when the calendar shows it.
317
+
318
+ ## Outside React
319
+
320
+ `createEventHistory` doesn't use React. Record each result yourself, and pass `undo` and `redo` the
321
+ events the user sees and a function that proposes, such as `propose` from
322
+ [`createEventTransactions`](./api/changes.md#results). `getEvents` must return the same snapshot
323
+ until the events change: the history tells events that haven't caught up with its own saves by
324
+ that. Pass `whenSettled` too, a promise for when no change is validating or saving, so an undo
325
+ waits for a change still saving:
326
+
327
+ ```ts
328
+ const history = createEventHistory<Meeting, string, never>();
329
+ history.record(result, { input: "api" });
330
+
331
+ await history.undo({
332
+ getEvents: () => visibleEvents(),
333
+ propose: (proposal, detail) => proposeAndRecord(proposal, detail),
334
+ whenSettled: () => changesSettled(),
335
+ });
336
+ ```
337
+
338
+ `history.subscribe` and `history.getSnapshot` follow the store contract, and `history.clear()`
339
+ empties both stacks.