Components and hooks
createCalendar, Root and its props, the components, hooks, actions, meta, and diagnostics.
Everything on this page is exported from @moltenship/calendar-solid, the calendar for
SolidJS 2.
Installation has the packages and the compiler's setup, and the
Quick start builds the Calendar and the Meeting type that the samples here
import from ./calendar.
New in 2.0
This package is new in 2.0. It has every part and hook, and the registry has ready-made Solid views: see What Solid doesn't have for the rest.
| Export | What it is |
|---|---|
createCalendar<TEvent, TResource, TSelection, TFocus>()(options) | The factory. Takes eventAdapter, views and invalidEventPolicy |
defineCalendarView({ name, defaultOptions, strategy, Renderer }) | A view. Renderer is a Solid component |
createCalendarStore(options) | The state store |
createStateSelector(source, selector, options?) | An accessor of one value of a store |
resolveViewOptions(view, overrides) | A view's options: its defaultOptions with a root's viewOptions over them |
It also exports the hooks below, the types of all of these, and the state types:
CalendarPublicState, CalendarActions, CalendarStore, CalendarStateChangeDetail,
CalendarCommandOptions and the others that Primitives
lists.
createCalendar
const Calendar = createCalendar<TEvent, TResource, TSelection, TFocus>()(options);Creates a calendar: a set of components and hooks typed to your records. Call it once at module
scope. It's called twice: the first call takes your types, and the second infers the view names
from views and the ID types from the adapter.
TEvent: your event record. Required.TResource: your resource record. Defaults tounknown; useneverif you don't have resources.TSelection,TFocus: the types of theselectionandfocusstate. Default toCalendarSelectionandCalendarFocus, the days, slots, and events the keyboard hooks read and write. A calendar whose views bind no keyboard can use its own types.
Prop
Type
The returned object holds the components and hooks below, plus views, the list you passed in.
Use it to derive the view-name type: (typeof Calendar.views)[number]["name"].
defineCalendarView
const view = defineCalendarView({ name, defaultOptions, strategy, Renderer });Defines a view. defaultOptions is required only when the strategy's options can't be undefined.
Custom views covers the strategy, the projection input, and the
Renderer props. The related types are CalendarViewStrategy, CalendarViewProjectionInput, and
CalendarViewRendererProps.
resolveViewInstantRange(range, timeZone) turns visible dates into the instant range that Root
passes to project as instantRange, and resolveViewLoadRange(strategy, anchor, environment, options, range) gives the loadRange it passes. Use them to run a strategy outside Root, for
example in a test.
withAsciiSpaces(text) writes the thin and narrow no-break spaces in Intl output as plain spaces.
Node.js and browsers disagree on them in date ranges, so wrap formatRange output that renders on
the server, as the engine's titles do, and hydration matches.
Root
<Calendar.Root> holds the state and provides it to everything inside. It renders no element of its
own.
Prop
Type
Pass a signal's value for a prop that changes: events={meetings()}, view={view()}. You can
write most props inline. locale, weekRules, secondaryTimeZones, availability, now, and a
controlled anchorDate, timeZone or view are compared by value; events, resources,
annotations, annotationSources and a controlled expandedResourceIds are compared item by
item; policies, onDiagnosticsChange, and the change handlers are read when they're called. The
active view's options are compared one option at a time, so keep functions and objects in them
stable. A clock object and a controlled selection or focus are compared by identity: keep
them stable, in a signal or at module scope.
Root throws on its first render if it has no date (calendar-root-requires-anchor-date), no
time zone (calendar-root-requires-time-zone), or no view (calendar-root-requires-view).
Components
Use these inside Root. Each renders one plain element with a data-calendar-part attribute and
accepts that element's usual props, including class, style, ref, and event handlers.
| Component | Renders | Notes |
|---|---|---|
Frame | <section> | Outer wrapper. Gets the {id}-frame ID, and its name from Root's label or the title. |
Toolbar | <header> | Wrapper for controls. |
Title | <span> | The active view's title, or its children. Gets the {id}-title ID. |
PreviousTrigger | <button> | Moves back one step of the active view. Disabled when no view is active. |
NextTrigger | <button> | Moves forward one step of the active view. Disabled when no view is active. |
TodayTrigger | <button> | Moves to today in the calendar's time zone, from now, clock, or the system clock. |
ViewSwitcher | <select> | One option per view. Requires getViewLabel(name). |
Viewport | <div> | Wrapper for the view. Gets the {id}-viewport ID. |
ActiveView | view output | Renders the active view, or fallback if it isn't registered. |
Event | your output | Looks up one event by eventId and calls children with it, as an accessor. |
Announcer | <div> | A hidden live region that speaks moves, resizes, and creates. Requires messages. |
- The buttons default to
type="button"and setaria-controlsto the viewport. Give each one text or anaria-label. - Your
onClickoronChangeruns first. Callevent.preventDefault()in it to skip the built-in action. Frame,Title, andViewportdon't acceptid. SetidonRootinstead, so the IDs andaria-controlsalways match.- The parts are ui-sdk components, which is how an
agent bridge finds a calendar. A calendar is listed for agents only when
it renders
Frame. Events and cells stay elements your views render.
Event passes your record and its normalized form:
export function StandupLine() {
return (
<Calendar.Event eventId="standup" fallback={<p>Not found</p>}>
{(entry) => (
<p>
{entry().event.title} starts at {entry().normalized.start.toString()}
</p>
)}
</Calendar.Event>
);
}The children stay rendered while the event changes, and the accessor has the event as it shows.
Hooks
The hooks on your calendar work anywhere inside its Root. Using them, or any component above,
outside Root throws calendar-hook-outside-root.
A hook that reads a value returns an accessor, so call it where you use the value: state().view,
range(). useCalendarActions() returns a plain object, and useCalendar()'s state and meta
are getters: read them in JSX, a memo or an effect, and don't destructure them.
import { Calendar } from "./calendar";
// Render it inside <Calendar.Root>.
export function Status() {
const state = Calendar.useCalendarState();
const range = Calendar.useVisibleRange();
const view = Calendar.useCalendarSelector((current) => current.view);
const saving = Calendar.useCalendarPendingChanges((changes) => changes.size > 0);
const actions = Calendar.useCalendarActions();
return (
<p>
{view()} from {range()?.start.toString()}, anchored on {state().anchorDate.toString()}
{saving() ? ", saving" : ""}
<button type="button" onClick={() => actions.navigateToday()}>
Today
</button>
</p>
);
}| Hook | Returns |
|---|---|
useCalendar() | { state, actions, meta } |
useCalendarState() | The six state values |
useCalendarActions() | The actions below. The object never changes. |
useCalendarMeta() | The meta object |
useCalendarSelector(selector, opts?) | selector(state). Updates only when it changes. |
useCalendarPendingChanges(selector?, opts?) | The changes still on their way, or selector(changes). See pending changes. |
useVisibleRange() | The active view's visible dates, or null |
useViewProjection() | The active view and its projection, or null |
useCalendarSelector and useCalendarPendingChanges compare results with Object.is. Pass
{ isEqual } to compare another way. The selector can be an inline function.
useCalendarHistory(history, { messages? }) is exported on its own too. It binds an event history
to the nearest Root, with undo, redo, canUndo and canRedo, and
useCalendarHistoryShortcuts(history, options) adds its keys, with the options scope, undo,
redo and disabled, as an object or an accessor of one; see
Undo and redo.
useCalendarPointer(options) is exported on its own too. It returns the ref that turns drags in
a custom view into proposals; see the pointer layer.
Announcer's messages, and the keyboard hooks for your own views (useCalendarKeyboard,
useRovingFocus, useCalendarInteraction, useCalendarAnnouncer), are covered in
Accessibility.
useNow({ intervalMs }) is exported on its own, not from your calendar. It returns the current
instant from the nearest Root's now or clock, or the system clock, and samples it every
intervalMs (one minute by default). It returns null during server rendering and hydration unless
Root has now.
useAnchorDateRequests(listener) calls listener(date, range) with every date the calendar is
asked to show: from Previous, Next, Today, keys paging past the view, or setAnchorDate. That
includes a date that is already the anchor. range holds the dates the active view shows for
date, so a week view can tell Today inside its week from a date that moves it. A view whose
scroll position can run ahead of the anchor uses it to show its range again when Today asks for
it. The scrolling views do this.
The package also exports the hooks a view is built with. Each takes an accessor wherever an argument can change:
| Hook | Returns |
|---|---|
useCalendarKeyboard(options?) | A ref for the element around the view's cells. Binds keydown and focusout on it |
useRovingFocus(target, options?) | The props for one focusable day, slot or event: tabindex, onFocus and ref. Spread them |
useCalendarFocus(selector), useCalendarSelection(selector) | Accessor of the focus or the selection, or of what selector picks from it |
useCalendarInteraction(selector?) | Accessor of the keyboard gesture in progress, or null |
useCalendarPointer(options) | A ref for the element around the view's days. Turns drags into proposals |
useCalendarDraft(), useCalendarDraftReporter() | Accessor of the pointer or keyboard draft, and the function a pointer layer reports it to |
useDraftBusy(resourceId), useBusyResources(range, options?) | Accessor of a resource during the draft, and of the busy resources in a range |
useCalendarAnnouncer() | The announcer useCalendarPointer takes, which speaks through Announcer |
useVisibleResources(), useResourceExpansion(resourceId) | Accessor of the resource rows, and the controls that expand and collapse them |
useResourceStatus(resourceId, at?) | Accessor of a resource's availability and busy state, or null |
useCalendarAvailability(), useClosedDates(range) | Accessor of the availability snapshot, and of the closed dates in range |
useTimeGridAvailability(columns, id?), useTimelineAvailability(…) | Accessor of the closed time per column, or per resource row |
useCalendarAnnotations(), useTimeGridAnnotations(columns) | Accessor of the annotations, and of those laid out on a time grid |
Accessibility covers the keyboard hooks,
Interactions the pointer, Availability
and Annotations theirs. eventIdAttributes(id) and resourceIdAttributes(id)
return the data attributes the pointer layer reads on an event and a resource, so a numeric ID
stays a number.
Actions
| Action | Effect |
|---|---|
setView(name, options?) | Changes the view. Every setter and navigation action takes { event?, reason?, source? } last, for the change handler |
setAnchorDate(date) | Changes the date |
setTimeZone(zone) | Changes the time zone |
setSelection(value) | Changes the selection (null clears it) |
setFocus(value) | Changes the focus (null clears it) |
setExpandedResourceIds(ids) | Changes the expanded resources |
navigatePrevious(), navigateNext() | Moves by one step of the active view |
navigateToday() | Moves to today in the calendar's time zone |
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. |
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. |
Setting the current value again (the same date, view, time zone or resource IDs, or the same
selection or focus object) doesn't change state or call its handler, unless the value is
controlled and you haven't applied a change the calendar asked for (see
State). useAnchorDateRequests still hears a request for the current anchor
date. Calling two actions in a row builds on the
first, so navigateNext(); navigateNext() moves two steps, even for controlled values.
Meta
Prop
Type
useCalendarMeta() returns an accessor of this object, and refs holds accessors of the elements:
meta().refs.viewport().
Diagnostics
Problems that don't stop rendering are collected in meta.diagnostics and passed to
onDiagnosticsChange. Time doesn't log them.
code | severity | Cause |
|---|---|---|
unregistered-active-view | error | The view state names a view that isn't registered. |
invalid-event | error | A record was skipped. issue has the details (issue codes). |
invalid-annotation | error | An annotation was skipped. issue has its code, index, and the annotation. |
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. |
invalid-secondary-time-zone | error | An entry of secondaryTimeZones was left out. issue has the value, and its index in a list. |
Server rendering
Root, the parts and every hook render on the server with @solidjs/web's renderToString, and
hydrate without a mismatch. On the server the calendar doesn't read the clock, the host time zone
or window. Without now, useNow gives null on the server and while hydrating, and the tab
stop is the view's entry, which is today only when now is set. A store with getServerSnapshot
renders that snapshot on the server and while hydrating. The keyboard and pointer refs attach
nothing until the page hydrates.