Interactions
Save moved, resized, created, and deleted events, show them while they save, and decide which changes to allow.
Time never edits your events itself. When someone moves, resizes, creates, or deletes an event, the
calendar proposes a change. Your onEventChange handler saves it and updates your events. While
it saves, the calendar shows the change as pending; if saving fails, the event goes back to where
it was.
This page uses the Calendar and Meeting from the Quick start.
Saving changes
Pass onEventChange to Root. Without it, the calendar is read-only: the views start no drags or
keyboard grabs and draw no resize handles, and every change proposed through actions is rejected
as read-only.
export function EditableCalendar() {
const [meetings, setMeetings] = useState(initialMeetings);
// Number changes as they start, and remember the newest one applied to each event, so a slow
// save never replaces a newer saved edit.
const nextOrder = useRef(0);
const lastApplied = useRef(new Map<string, number>());
return (
<Calendar.Root
events={meetings}
onEventChange={async (change) => {
const order = ++nextOrder.current;
await saveToServer(change);
if (change.eventId !== null) {
if ((lastApplied.current.get(change.eventId) ?? 0) > order) return;
lastApplied.current.set(change.eventId, order);
}
setMeetings((current) => applyChange(current, change));
}}
policies={[timedOnly, snapPolicy({ minutes: 15 }), minimumDurationPolicy({ minutes: 15 })]}
defaultAnchorDate={Temporal.PlainDate.from("2026-10-08")}
defaultTimeZone="Europe/Berlin"
locale="en-US"
weekRules={weekRules}
>
<Calendar.ActiveView />
</Calendar.Root>
);
}The handler receives a change object:
| Field | Contents |
|---|---|
cause | "move", "resize-start", "resize-end", "create", "delete", or "update" |
eventId | The event's ID, or null for "create" |
event | Your record. For "create", null, or the record an undo restores |
original | Where the event was, as the user saw it, or null for "create" |
proposed | Where it should go: a range with kind, start, end, and resourceIds, or null for "delete" |
id | Identifies the change within this calendar, such as change-3. It isn't an event ID |
warnings | Reasons policies flagged the change with but let through, such as "outside-availability". Absent when there are none |
The handler's second argument is the detail the change was proposed with: { input }, one of
"pointer", "keyboard", "api" or "agent". "api" is your own proposeEventChange call, and
"agent" is an AI agent acting through the agent bridge. A change an
event history proposes also has history, "undo" or "redo". An agent that
names or renames an event sends the title in detail.fields, which a handler has to read to save
it: see Save what the agent sent.
applyChange turns a change into new state. A created event needs an ID of your own, usually from
your server; this example makes one up. Records you don't touch stay the same objects:
import {
eventPlacement,
minimumDurationPolicy,
moveEventPlacement,
snapPolicy,
type CalendarEventChange,
type CalendarPolicy,
type CalendarProposalDetail,
type CalendarTransactionResult,
} from "@moltenship/calendar";
import { useEffect, useRef, useState } from "react";
import { Calendar, meetings as initialMeetings, weekRules, type Meeting } from "./quick-start";
type MeetingChange = CalendarEventChange<Meeting, string, never>;
function applyChange(meetings: readonly Meeting[], change: MeetingChange): readonly Meeting[] {
if (change.cause === "delete") {
return meetings.filter((meeting) => meeting.id !== change.eventId);
}
if (change.proposed.kind !== "timed") return meetings;
const { start, end } = change.proposed;
if (change.cause === "create") {
const id = crypto.randomUUID();
return [...meetings, { id, title: "New meeting", color: "blue", start, end }];
}
return meetings.map((meeting) =>
meeting.id === change.eventId ? { ...meeting, start, end } : meeting,
);
}Pending changes
How long a change stays pending depends on your handler:
- A handler that returns nothing (or doesn't
await) commits the change right away. Update your events in the same handler. - A handler that returns a promise keeps the change pending until the promise settles. The event
shows in its new place in the meantime.
- If the promise resolves, the calendar keeps showing the change until your
eventsnext change. From then on youreventsdecide where the event is, so include the saved change in that update, assetMeetingsdoes in the example. If another update arrives first, such as a refetch that doesn't have the change yet, the event moves to where that update puts it. - If it rejects or the handler throws, the change is undone.
- If the promise resolves, the calendar keeps showing the change until your
async function saveToServer(change: MeetingChange): Promise<void> {
const response = await fetch("/api/meeting-changes", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(change),
});
if (!response.ok) throw new Error(`Saving failed with ${response.status}`);
}Pending events have isPending: true in projections, in meta.eventSnapshot, and in
Calendar.Event. Every built-in view renders them at 60% opacity with data-pending and
aria-busy, and adds "saving" to the event's accessible name. Target those attributes to style
pending events your own way. A keyboard gesture previews the grabbed event the same way, so it also
reads isPending: true until the gesture ends; the built-in views don't show it as saving.
If the same event changes again before the first change finishes saving, the calendar shows the
newer change. Your handler still receives both, unless an async policy was still deciding on the
first; that one is rejected with the reason superseded and never reaches your handler. Their saves can finish in either
order, or one can fail. The example numbers each change as it starts. When a save succeeds, it updates the state
only if no newer change to that event has been applied yet. So a slow save never replaces a newer
saved edit, and if the newer save fails, the older one that succeeded is still shown. Your server
needs the same care, for example by rejecting writes that carry an outdated version.
Across the calendar
Calendar.useCalendarPendingChanges() lists every change still on its way, for a calendar-wide
"Saving…" or a question before the page closes. It returns a read-only Map from change ID to
{ change, phase }, in the order the changes were proposed:
phase | Meaning |
|---|---|
validating | An async policy is still deciding; your handler hasn't seen the change yet |
saving | Your handler's promise is still running |
awaiting-events | The promise resolved, but your events don't show the change yet; it ends with your next ones |
The map includes creates, and an older change to an event that is still saving after a newer one replaced it on screen. A change that never waits, with policies that answer at once and a handler that returns no promise, never shows. Neither does a keyboard gesture's preview: it isn't a change yet.
Pass a selector, and the component re-renders only when what it picks changes; { isEqual }
compares another way than Object.is. Without one, it re-renders whenever a change starts, moves to
its next phase, or ends.
// Anywhere inside Root, such as in the toolbar.
export function SavingStatus() {
// Saved changes that only wait for your events don't count.
const saving = Calendar.useCalendarPendingChanges((changes) =>
[...changes.values()].some(({ phase }) => phase !== "awaiting-events"),
);
useEffect(() => {
if (!saving) return;
// Ask before the page closes while a change is still on its way.
const warn = (event: BeforeUnloadEvent) => event.preventDefault();
window.addEventListener("beforeunload", warn);
return () => window.removeEventListener("beforeunload", warn);
}, [saving]);
return <output>{saving ? "Saving…" : "All changes saved"}</output>;
}How changes end
onEventChangeResult on Root hears how every proposal ended: drags, keyboard moves and creates,
and your own proposeEventChange calls. It gets the result proposeEventChange resolves with, and
the detail it was proposed with, { input }: "pointer", "keyboard", "api", or "agent" for
an AI agent's change. Use it for a toast when a drop is refused or a save fails, to log what happens, or to record changes to
undo:
// <Calendar.Root onEventChangeResult={reportOutcome} … />
export function reportOutcome(
result: CalendarTransactionResult<Meeting, string, never>,
{ input }: CalendarProposalDetail,
) {
if (result.status === "committed") return;
// An AbortError is your own handler cancelling the change, not a failed save.
if (result.error instanceof DOMException && result.error.name === "AbortError") return;
console.warn(`A ${input} change wasn't saved: ${result.reason}`, result.error);
}- It's called once per proposal, after the proposal settles, before code that awaits
proposeEventChangegoes on. A cancelled drag or keyboard gesture proposes nothing, so it isn't called. It's read from the latest render, so it can be inline. committedmeans your handler finished. After an async save the change can still wait for yourevents, asawaiting-eventsabove.- Each result belongs to its own proposal. When a newer change to an event replaced an older one, the older one's late failure is still reported, though the newer change stays on screen.
- A rejected result has a reason. If the callback throws, the
error is reported with
reportError, as an uncaught error is, and the result stays as it was.
Policies
Policies decide which changes are allowed. Each one looks at a change and accepts it, adjusts it,
rejects it, or accepts it with a warning in change.warnings. They run in order, and each sees the change as adjusted by the ones before it. Pass
them to Root as policies, as in the example above.
| Policy | What it does |
|---|---|
snapPolicy({ minutes: 15 }) | Rounds timed and floating changes to a grid in the calendar's time zone |
minimumDurationPolicy({ minutes: 15 }) | Lengthens timed and floating events that would be shorter than the minimum |
boundsPolicy({ start, end }) | Rejects changes that end up outside the given instants |
availabilityPolicy({ mode }) | Blocks changes outside working hours, or saves them with a warning in change.warnings |
conflictPolicy({ mode, getResourceMode }) | Blocks a change that makes a busy event overlap another busy event on one of its resources, saves it with a warning, or allows it, by a mode per resource. Deletes always pass. See double booking |
readOnlyResourcesPolicy(isReadOnly) | Rejects changes to the schedule of the resources isReadOnly(resourceId) marks |
readOnlyPolicy() | Rejects changes to events your adapter marks with isReadOnly. Root always runs it first, so you don't need to pass it. |
A policy is a function, so you can write your own. This one keeps meetings out of the all-day row.
Policies can also be async, for example to check availability on your server.
A policy's second argument is a context: the events as the user sees them, the calendar's
timeZone, its availability, and the proposal's detail. Read detail?.input to treat one input differently, such as refusing an
agent's change that a person may make. detail is
absent when a policy runs outside a proposal.
// Meetings always have a time, so refuse drops onto the all-day row.
const timedOnly: CalendarPolicy<Meeting, string, never> = ({ proposed }) =>
proposed === null || proposed.kind === "timed"
? { type: "accept" }
: { type: "reject", reason: "meetings-need-a-time" };Changing events from your own UI
Buttons, forms, and dialogs can propose changes too, with proposeEventChange from
useCalendarActions() (or the actions prop inside a view). The change goes through the same
policies, pending state, and handler as a drag. The returned promise tells you how it ended; it
never rejects. onEventChange, policies and onEventChangeResult hear it with the input "api"; a
gesture layer of your own can name its input as the second argument, as in
proposeEventChange(proposal, { input: "pointer" }).
export function PushBackButton({ meeting }: { readonly meeting: Meeting }) {
const actions = Calendar.useCalendarActions();
const [message, setMessage] = useState("");
async function pushBack() {
const result = await actions.proposeEventChange({
cause: "move",
eventId: meeting.id,
proposed: {
kind: "timed",
start: meeting.start.add({ hours: 1 }),
end: meeting.end.add({ hours: 1 }),
},
});
setMessage(result.status === "committed" ? "Moved" : `Not moved: ${result.reason}`);
}
return (
<>
<button type="button" onClick={pushBack}>
Push back an hour
</button>
<output>{message}</output>
</>
);
}A rejected result has a reason, and the change it would have made, except for
unknown-event:
reason | Meaning |
|---|---|
read-only | The event is read-only, or Root has no onEventChange |
| a policy's reason | A policy rejected it, such as out-of-bounds |
superseded | A newer change for the same event replaced it |
handler-error | Your handler threw or its promise rejected; error has the cause |
policy-error | A policy threw |
invalid-placement | The proposed range is empty or reversed |
unknown-event | No event has that ID |
agent-delete-not-allowed | An agent caused a delete, and Root has no allowAgentDelete |
To create an event, propose { cause: "create", proposed: { kind, start, end } }. To delete one,
propose { cause: "delete", eventId }.
Drag, resize, and create
Once Root has an onEventChange handler, the built-in views let people edit events with the
mouse, a pen, or touch:
| View | Move | Resize | Create |
|---|---|---|---|
| Week and day | Across days and times. Dropping on the all-day row makes it all-day. | Drag the top or bottom edge | Drag across empty time, or across all-day cells |
| Month | Across days. Timed events keep their time. | – | Drag across days to make an all-day event |
The resource columns and resource timeline views, and the scrolling week, day and month views, use
the same pointer layer; a drop on another resource swaps that resource in the event's
resourceIds.
Each finished drag sends exactly one change to your handler, so the policies and pending state above apply. A few details:
- Time grids snap to 15 minutes, and a resized event keeps at least one slot. Hour timelines snap to 30 minutes, and day timelines step whole days.
- A movement under 4px is a click, so clicking an event still works. The click that ends a drag doesn't count as a click.
- Escape cancels a drag, and so does dropping outside the view.
- On touch screens, press and hold for about half a second to start a drag; a finger that moves sooner scrolls. Once a drag starts, the page holds still under it. While the calendar is editable, the built-in views select no text and show no callout on a touch screen, so a long-press only picks events up.
- The view scrolls when you drag near any edge of its scroll container.
- Read-only events (your adapter's
isReadOnly) can't be dragged and have no resize handles. - While dragging, the original event dims (it has
data-dragging) and a preview shows where it would land. Dragging never re-renders the view.
Clicking an empty slot doesn't create an event; creating needs a drag.
Snapped and free drags
By default the preview snaps: it draws the event where a drop would land, so it steps from slot to
slot. Set a view's dragPreview option to "free" and the preview follows the pointer instead:
- Move: a copy of the event moves with the pointer, pixel for pixel, over a marker of where a drop would land. On release the copy slides onto the event in its new place.
- Resize: on a time axis, the dragged edge stays under the pointer while the marker steps from slot to slot. A resized event still keeps at least one slot.
- Create: on a time axis, the new range grows with the pointer, from the slot you pressed in.
In a month grid or a day timeline, a resize or create still steps whole days, as it does when snapped.
<Calendar.Root viewOptions={{ week: { dragPreview: "free" } }} />The drop is the same in both modes. Your handler, the policies, the draft hooks, the announcements and your own drop zones all hear the snapped placement, never the pointer's exact position.
The copy settles in 150ms with an ease-out curve. Under prefers-reduced-motion: reduce it doesn't
slide: the event just appears in its new place. Escape, a drop outside the view, and a drop that a
policy or your handler refuses right away all send the copy back to where the event started.
If your handler returns nothing and updates your events only later, after a save, the copy slides to where the drop landed and disappears before the event shows up there. Return the save's promise instead, so the event shows in its new place while it's pending.
The pointer layer documents the marker's styling hooks.
From the rest of the page
Items of your own, such as unscheduled tasks, can be dragged into the calendar, and events dragged
out to your own drop zones. With dnd-kit, @moltenship/calendar-dnd-kit does
both, as Drag tasks in with dnd-kit shows live; without it, the pointer layer's drags from and to the rest of the page
take the points of any drag library. A dropped item is a create carrying your record as
change.event, through the same policies and handler.
In your own views
The built-in views use useCalendarPointer, and your views can too. Call it in the Renderer with
the props the Renderer receives, and put the returned ref on the element that contains the days.
Pass isReadOnly as disabled, so a calendar without onEventChange starts no drags, and draw no
resize handles while it's set:
import { defineCalendarView, timeGridStrategy, useCalendarPointer } from "@moltenship/calendar";
export const myWeekView = defineCalendarView({
name: "week",
strategy: timeGridStrategy({ kind: "week" }),
Renderer: function MyWeek({ actions, environment, events, isReadOnly, projection }) {
const ref = useCalendarPointer({
columns: projection.days.map((day) => day.column),
disabled: isReadOnly,
events,
onPropose: actions.proposeEventChange,
timeZone: environment.timeZone,
});
return (
<div
ref={ref}
// On a touch screen, a long-press picks an event up instead of selecting its text.
className={
isReadOnly
? undefined
: "pointer-coarse:select-none pointer-coarse:[-webkit-touch-callout:none]"
}
>
{/* Day columns with data-date, events with data-event-id */}
</div>
);
},
});Pass columns in views with a time axis: a time grid, resource columns or an hour timeline. A month
grid or a day timeline finds days by their data-date. The hook reads these attributes from your markup:
| Element | Attribute |
|---|---|
| A day column in a time grid, covering 24 hours | data-date="2026-10-08" |
| An all-day cell | data-date="…" data-all-day |
| A day cell in a month grid | data-date="…" |
An event (render it as a <button>) | data-event-id |
| A resize handle inside an event | data-resize="start" or "end" |
| A control that never starts a drag | data-calendar-pointer="none" |
| A cell or row of one resource, in a resource view | data-resource-id, from resourceIdAttributes(id) |
| An event whose ID is a number | data-event-id-type="number", from eventIdAttributes(id) |
| The element inside an event that shows its time | data-event-time |
| A part over the cells, such as a sticky header | data-occludes |
A timeline's time strip for one date, its date in columns | data-date="…" data-axis="inline" |
On touch screens, a long-press should pick an event up rather than select its text: while
isReadOnly is false, give the element with the ref user-select: none and
-webkit-touch-callout: none for a coarse pointer, as the built-in views do with
pointer-coarse:select-none pointer-coarse:[-webkit-touch-callout:none].
The pointer layer reference lists the hook's options and styling hooks.