Calendar
The device's calendars and their events, from the calendar plugin: reading them, and adding or
editing an event through the system's own screens. To put an event into the user's calendar, use
Calendar.openEditor() — it opens the system's editor and needs no permission; Calendar.list() reads
the events and asks the calendar permission. A date field in a form is UIInput with type
'date', not this.
- add an event to the user's calendar ("add to calendar" button)
- show the user's events for today, this week, a date range
- list the device's calendars with their colors, read one calendar only
- handle all-day events and repeating events
- ask for the calendar permission, handle a refusal
- open an event to edit or delete it
- refresh when the calendar changes
Platforms: iOS, Android; not on the web, in the web player, on desktop or in headless tests —
check Calendar.supported.
At a glance
// app.json: "plugins": { "calendar": "*" }
const HOUR = 60 * 60 * 1000
const addToCalendar = async () => {
const start = Date.now() + 24 * HOUR
try {
const saved = await Calendar.openEditor({ // the system's editor, no permission
title: 'Dinner at Luigi',
start, end: start + 2 * HOUR, // ms since the epoch
location: '12 Main Street',
})
toast(saved ? 'Added to your calendar' : 'Not added')
} catch (e) {
toast(e.message === 'unavailable' ? 'The calendar is not available here' : 'Could not open the calendar')
}
}
Router.init(UIScreen(
UIButton(UIText('Add to calendar')).onClick(addToCalendar),
).style({ p: 20, pt: 'safe-top' }))Add the calendar plugin to the app: app.json
The calendar is the calendar plugin: list it in the project's app.json —
"plugins": { "calendar": "*" }. The list is one for every platform: a plugin it does not name is
not there, and the compile warns about one the app uses and does not list. The plugin brings what
the platforms need declared: the iOS usage texts (NSCalendarsFullAccessUsageDescription, and
NSCalendarsUsageDescription for iOS 15 / 16) and Android's READ_CALENDAR. It declares no write
permission — an event is written by the system's own editor. The le.codes viewer app has the
plugin from the release that carries it; an older viewer answers Calendar.supported === false.
Add an event to the user's calendar: the system's editor, Calendar.openEditor
Calendar.openEditor(draft: {
title?: string
start?: number // ms since the epoch; left out: the editor's own default
end?: number // ms since the epoch; left out: an hour after start (a day for an all-day event)
allDay?: boolean
location?: string
notes?: string
url?: string
}): Promise<boolean> // true: the user saved the event; false: they left without savingopenEditor opens the system's "new event" editor filled from the draft; the user may change
anything, chooses the calendar and saves it themselves. One call is one editor on screen: the app
writes nothing on its own, so there is no write permission. There is no call that creates, changes
or deletes an event without the user, and none that adds several at once.
It rejects "unavailable" (no calendar app, a host without the plugin), "busy" while another
screen of the plugin is up, and "failed".
const DAY = 24 * 60 * 60 * 1000
const midnight = (daysFromToday: number) => {
const d = new Date()
d.setHours(0, 0, 0, 0)
d.setDate(d.getDate() + daysFromToday)
return d.getTime()
}
// A two-day all-day event: from the midnight its first day begins to the midnight after its last.
const addTrip = () => Calendar.openEditor({ title: 'Trip to Rome', allDay: true, start: midnight(7), end: midnight(9) })
.then(saved => toast(saved ? 'Saved' : 'Not saved'))
.catch(e => toast(e.message))
UIButton(UIText('Save the trip')).onClick(addTrip)on iOS 15 and 16 the system's editor itself needs the calendar permission:
openEditor asks it first there, and a refusal rejects "denied". From iOS 17 on, and on Android, it asks none.
on Android the editor is the phone's calendar app. true means the app could tell the
event was saved — it can when it may read the calendars; an editor that does not say answers
false. An Android event has no link of its own: a draft's url is put at the end of the notes.
Where two apps can add an event, Android first asks the user which one to use.
Times, all-day events and repeating events
Every time is milliseconds since the epoch (Date.now(), date.getTime(), new Date(ms)).
- All-day:
startis the local midnight the first day begins at andendthe local midnight AFTER the last day, in the device's time zone, on both platforms — a one-day event is exactly 24 hours (23 or 25 across a clock change), and it ends where the next day starts. A draft follows the same rule. - Repeating: one event with many occurrences.
listanswers one entry per occurrence in the range: the sameid, each with its ownstartandend,recurring: true.startis what tells them apart —openEvent(id, start)opens that one.
const when = (e: CalendarEvent): string => {
const day = (ms: number) => new Date(ms).toLocaleDateString()
const time = (ms: number) => new Date(ms).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
if (!e.allDay) return `${day(e.start)} ${time(e.start)} – ${time(e.end)}`
const last = e.end - 1 // the last day itself: `end` is the midnight after it
return day(e.start) === day(last) ? day(e.start) : `${day(e.start)} – ${day(last)}`
}on Android an occurrence the user edited or moved on its own is an event of its own:
it comes with its own id.
Show the user's events for a date range: Calendar.list
Calendar.list(options: {
from: number // ms since the epoch
to: number // the events that overlap [from, to); at most four years after `from`
calendars?: string[] // only these calendars (CalendarInfo.id); default: every calendar
}): Promise<CalendarEvent[]> // sorted by start; a repeating event once per occurrence
interface CalendarEvent {
id: string // this device's id of the event: what get() and openEvent() take
calendarId: string
title: string // '' for an event without a title
start: number // ms since the epoch
end: number
allDay: boolean
recurring: boolean // one occurrence of a repeating event
location?: string
notes?: string
url?: string // iOS only
}list reads the events. The first call shows the OS permission dialog; a refusal rejects
"denied". It throws for a range that is not one (to not after from, more than four years),
and rejects "unavailable" on a host without the plugin.
const today = signal<CalendarEvent[]>([])
const note = signal('')
const loadToday = () => {
const from = new Date()
from.setHours(0, 0, 0, 0)
const to = new Date(from)
to.setDate(to.getDate() + 1)
return Calendar.list({ from: from.getTime(), to: to.getTime() })
.then(events => { today.value = events; note.value = events.length ? '' : 'Nothing today' })
.catch(e => { note.value = e.message === 'denied' ? 'The calendar is off for this app' : 'The calendar is not available' })
}
Router.init(UIScreen(
UIText('Today').style({ fontSize: 22 }),
UIText(() => note.value),
UIColumn(() => today.value.map(e =>
UIText(e.allDay ? `All day ${e.title}` : `${new Date(e.start).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })} ${e.title}`))).style({ gap: 8 }),
).style({ p: 20, pt: 'safe-top', gap: 12 }))
loadToday()The device's calendars and their colors: Calendar.calendars
Calendar.calendars(): Promise<CalendarInfo[]>
interface CalendarInfo {
id: string // this device's id of the calendar: what `calendars` of list() takes
title: string // as the device shows it: "Work", "Birthdays"
color: string // "#RRGGBB"
account?: string // the account it belongs to ("iCloud", an email address); absent for a local one
writable: boolean // events can be added to it (not a subscribed or a birthdays calendar)
}calendars is behind the calendar permission, like list. An event's calendarId is one of
these ids: use it to color a row, and calendars of list to read some calendars only.
const rows = signal<{ title: string, color: string }[]>([])
const loadWeek = async () => {
const cals = await Calendar.calendars()
const own = cals.filter(c => c.writable) // leave out birthdays and subscriptions
const now = Date.now()
const events = await Calendar.list({ from: now, to: now + 7 * 24 * 60 * 60 * 1000, calendars: own.map(c => c.id) })
rows.value = events.map(e => ({ title: e.title, color: cals.find(c => c.id === e.calendarId)?.color ?? '#888888' }))
}
loadWeek().catch(e => toast(e.message))
UIColumn(() => rows.value.map(r =>
UIRow(
UIBox().style({ width: 10, height: 10, borderRadius: 5, bgColor: r.color }),
UIText(r.title),
).style({ gap: 8, alignItems: 'center' })))One event, and its card to edit or delete it: Calendar.get, Calendar.openEvent
Calendar.get(id: string): Promise<CalendarEvent | null> // of a repeating event: its first occurrence; null: no such event
Calendar.openEvent(id: string, start?: number): Promise<void> // `start`: which occurrence of a repeating event; resolves when the card closesBoth are behind the calendar permission. openEvent opens the system's card of an event — where the
user sees it, edits it or deletes it; pass the occurrence's start for a repeating event (left
out: its first). It rejects "notFound" for an id that is no event, and "denied", "busy",
"unavailable", "failed". Whether anything was changed in the card is what onChange says.
const openEvent = (e: CalendarEvent) => Calendar.openEvent(e.id, e.start)
.catch(err => toast(err.message === 'notFound' ? 'This event is gone' : 'Could not open the event'))The calendar permission and a refusal: permissions.query('calendar')
permissions.query('calendar'): Promise<'granted' | 'denied' | 'prompt'> // the state, never a dialog
permissions.request('calendar'): Promise<'granted' | 'denied' | 'prompt'> // ask nowThe calendar permission is asked and read like every other one, through permissions
(permissions.md): the OS asks at the first calendars / list /
get / openEvent, or when the app calls permissions.request('calendar'); openEditor does
not ask (iOS 15 / 16 excepted). "prompt" is never asked — the first read asks. After a refusal
iOS never asks again: permissions.openSettings() opens the app's page of the system settings.
const blocked = signal(false)
const openAgenda = async () => {
if ((await permissions.query('calendar')) === 'denied') { blocked.value = true; return }
const now = Date.now()
const events = await Calendar.list({ from: now, to: now + 24 * 60 * 60 * 1000 }) // the dialog comes here the first time
toast(`${events.length} events in the next 24 hours`)
}
UIColumn(() => [blocked.value
? UIButton(UIText('Turn the calendar on in Settings')).onClick(() => permissions.openSettings())
: UIButton(UIText('Show my day')).onClick(() => openAgenda().catch(e => { blocked.value = e.message === 'denied' }))])permissions.query('calendar') says whether a dialog stands between the app and the
calendars, not whether there are any: where the plugin is absent it answers "granted", and
Calendar.supported is the answer to "can I read the calendar here".
Refresh when the calendar changes: Calendar.onChange
Calendar.onChange(listener: () => void): () => void // returns a function that stops listeningThe listener runs when an event is added, edited or deleted — by this app's openEditor /
openEvent screens, by the user in the calendar app, by a sync. It carries nothing: read the
range again. It is heard from the app's first call to the plugin on (the list it refreshes),
while the app may read the calendars, and never on a host without the plugin.
const titles = signal<string[]>([])
const reload = () => {
const now = Date.now()
return Calendar.list({ from: now, to: now + 7 * 24 * 60 * 60 * 1000 })
.then(events => { titles.value = events.map(e => e.title) }).catch(() => {})
}
const screen = UIScreen(UIColumn(() => titles.value.map(t => UIText(t))))
const stop = Calendar.onChange(reload)
screen.onClose(stop)
reload()Where it works, and why a call failed: Calendar.supported, the codes
Calendar.supported: boolean // this host registered the "calendar" servicesupported is false on the web, in the web player, on desktop, in headless tests and in a shell
built without the plugin. Nothing throws there for a well-formed call: every call rejects
"unavailable". A call rejects with a code as e.message:
| code | when |
|---|---|
"denied" |
the user refused the calendar permission, now or earlier (calendars, list, get, openEvent; openEditor on iOS 15 / 16) |
"unavailable" |
no calendar here: a host without the plugin, a device with no calendar app |
"busy" |
a screen of the plugin is already up (an editor, a card) |
"notFound" |
openEvent: no event has that id |
"failed" |
the screen could not be shown (the app is in the background), or a read failed |
Reminders (the to-do lists of iOS) are not part of the plugin.
UIColumn(() => [Calendar.supported
? UIButton(UIText('Add to calendar')).onClick(() => Calendar.openEditor({ title: 'Team call' }).catch(e => toast(e.message)))
: UIText('The calendar is not available on this device')])See also
- permissions.md —
permissions.request('calendar'),openSettings - contacts.md — the address book, the same way
- datetime.md — formatting and arithmetic on dates
- notifications.md — a reminder the app itself schedules