API Reference
The public API is at CALENDARIA.api. Use it from macros or from another module.
Time management
Section titled “Time management”advanceTime(), setDateTime(), jumpToDate(), and advanceTimeToPreset() require the changeDateTime permission. A non-GM who has it does not move the clock directly. The call emits a request to the GM and returns at once. On a player client, advanceTime(), setDateTime(), and advanceTimeToPreset() resolve with the world time as it stood before the request.
API calls do not play the cinematic overlay. Pass cinematic: true to opt in.
getCurrentDateTime()
Section titled “getCurrentDateTime()”Get the current world date and time.
const now = CALENDARIA.api.getCurrentDateTime();// Returns: { year, month, day, hour, minute, second, ... }Returns: object - Time components with year adjusted for yearZero and 1-indexed month and day.
advanceTime(delta, options)
Section titled “advanceTime(delta, options)”Advance time by a delta. When delta is an object with day, hour, minute, second keys, it is converted to seconds using the active calendar’s time configuration.
await CALENDARIA.api.advanceTime({ hour: 8 });await CALENDARIA.api.advanceTime({ day: 1, hour: 6 });await CALENDARIA.api.advanceTime(3600); // advance by raw secondsawait CALENDARIA.api.advanceTime({ hour: 8 }, { cinematic: true });| Parameter | Type | Description |
|---|---|---|
delta | number|object | Seconds or time delta object (e.g., {day: 1, hour: 2}) |
options.cinematic | boolean | Trigger the cinematic overlay (default: false) |
Returns: Promise<number> - New world time in seconds.
setDateTime(components, options)
Section titled “setDateTime(components, options)”Set time to specific values.
await CALENDARIA.api.setDateTime({ year: 1492, month: 5, day: 15, hour: 10, minute: 30 });await CALENDARIA.api.setDateTime({ year: 1492, month: 5, day: 15 }, { cinematic: true });| Parameter | Type | Description |
|---|---|---|
components | object | Time components to set |
options.cinematic | boolean | Trigger the cinematic overlay (default: false) |
Returns: Promise<number> - New world time in seconds.
jumpToDate(options, advanceOptions)
Section titled “jumpToDate(options, advanceOptions)”Jump to a specific date while preserving the current time of day.
await CALENDARIA.api.jumpToDate({ year: 1492, month: 5, // 1-indexed day: 1});await CALENDARIA.api.jumpToDate({ year: 1492, month: 5, day: 1 }, { cinematic: true });| Parameter | Type | Description |
|---|---|---|
options.year | number | Target year |
options.month | number | Target month (1-indexed) |
options.day | number | Target day of month (1-indexed) |
advanceOptions.cinematic | boolean | Trigger the cinematic overlay (default: false) |
Returns: Promise<void>
advanceTimeToPreset(preset, options)
Section titled “advanceTimeToPreset(preset, options)”Advance time to the next occurrence of a preset time.
await CALENDARIA.api.advanceTimeToPreset('sunrise');await CALENDARIA.api.advanceTimeToPreset('midnight');await CALENDARIA.api.advanceTimeToPreset('sunrise', { cinematic: true });| Parameter | Type | Description |
|---|---|---|
preset | string | 'sunrise', 'midday', 'noon', 'sunset', or 'midnight' |
options.cinematic | boolean | Trigger the cinematic overlay (default: false) |
Returns: Promise<number> - New world time in seconds.
Clock control
Section titled “Clock control”isClockRunning()
Section titled “isClockRunning()”Check whether the real-time clock is running.
const running = CALENDARIA.api.isClockRunning();Returns: boolean - True if the clock is running.
startClock()
Section titled “startClock()”Start the real-time clock. Requires the changeDateTime permission. The call is a no-op when the clock is locked, when the real-time speed is set to 0, during active combat, or when the game is paused with clock-pause sync enabled.
CALENDARIA.api.startClock();Returns: void
stopClock()
Section titled “stopClock()”Stop the real-time clock.
CALENDARIA.api.stopClock();Returns: void
toggleClock()
Section titled “toggleClock()”Toggle the real-time clock on or off.
CALENDARIA.api.toggleClock();Returns: void
getClockSpeed()
Section titled “getClockSpeed()”Get the current real-time clock speed in game seconds per real second.
const speed = CALENDARIA.api.getClockSpeed();Returns: number - Clock speed multiplier.
Calendar access
Section titled “Calendar access”Calendar collections are stored as keyed objects with string IDs, not arrays. Use the array getters for ordered iteration.
| Getter | Collection |
|---|---|
monthsArray | months.values |
weekdaysArray | days.values |
seasonsArray | seasons.values |
moonsArray | moons |
cyclesArray | cycles |
erasArray | eras |
festivalsArray | festivals |
canonicalHoursArray | canonicalHours |
namedWeeksArray | weeks.names |
namedDaysArray | days.names |
weatherZonesArray | weather.zones |
The daysInWeek getter returns weekdaysArray.length || 7.
const calendar = CALENDARIA.api.getActiveCalendar();const months = calendar.monthsArray; // ordered arrayconst weekCount = calendar.daysInWeek; // number of weekdays or 7getActiveCalendar()
Section titled “getActiveCalendar()”Get the currently active calendar.
const calendar = CALENDARIA.api.getActiveCalendar();Returns: object|null - The active calendar or null.
getCalendar(id)
Section titled “getCalendar(id)”Get a specific calendar by ID.
const calendar = CALENDARIA.api.getCalendar('harptos');| Parameter | Type | Description |
|---|---|---|
id | string | Calendar ID |
Returns: object|null - The calendar or null if not found.
getAllCalendars()
Section titled “getAllCalendars()”Get all registered calendars.
const calendars = CALENDARIA.api.getAllCalendars();Returns: Map<string, object> - Map of calendar ID to calendar.
getAllCalendarMetadata()
Section titled “getAllCalendarMetadata()”Get metadata for all calendars.
const metadata = CALENDARIA.api.getAllCalendarMetadata();Returns: object[] - Array of calendar metadata.
addCalendar(id, definition)
Section titled “addCalendar(id, definition)”Add a new calendar.
await CALENDARIA.api.addCalendar('myCalendar', calendarDefinition);| Parameter | Type | Description |
|---|---|---|
id | string | Unique calendar ID |
definition | object | Calendar definition object |
Returns: Promise<object|null> - The registered calendar. Passing an id that is already registered returns the existing calendar. Returns null on failure.
switchCalendar(id)
Section titled “switchCalendar(id)”Switch to a different calendar. Requires the changeActiveCalendar permission.
await CALENDARIA.api.switchCalendar('greyhawk');| Parameter | Type | Description |
|---|---|---|
id | string | Calendar ID to switch to |
Returns: Promise<boolean> - True if switched successfully.
setActiveCalendar(id, options)
Section titled “setActiveCalendar(id, options)”Set the active calendar. Requires the changeActiveCalendar permission.
await CALENDARIA.api.setActiveCalendar('greyhawk', { useCalendarDefaults: true });| Parameter | Type | Description |
|---|---|---|
id | string | Calendar ID to activate |
options.useCalendarDefaults | boolean | When true, rewrites the world DISPLAY_FORMATS setting from the new calendar’s dateFormats so every location maps to calendarDefault. Defaults to false |
Returns: Promise<boolean> - True if activated successfully.
convertDate(date, fromCalendarId, toCalendarId)
Section titled “convertDate(date, fromCalendarId, toCalendarId)”Convert a date from one calendar to another via shared world time.
const converted = CALENDARIA.api.convertDate({ year: 1492, month: 5, day: 15 }, 'harptos', 'greyhawk');// Returns: { year, month, day, hour, minute }| Parameter | Type | Description |
|---|---|---|
date | object | Date to convert {year, month (1-indexed), day (1-indexed), hour?, minute?} |
fromCalendarId | string | Source calendar ID |
toCalendarId | string | Target calendar ID |
Returns: object|null - Converted date or null.
getEquivalentDates(date, calendarId)
Section titled “getEquivalentDates(date, calendarId)”Get equivalent dates for a date on all other registered calendars. The input date accepts optional hour, minute, and second fields. Each result’s formatted value applies the target calendar’s crossCalendar format to those components. Omit the time fields and they default to midnight.
const equivalents = CALENDARIA.api.getEquivalentDates({ year: 1492, month: 5, day: 15, hour: 14, minute: 30 });| Parameter | Type | Description |
|---|---|---|
date | object | Date {year, month (1-indexed), day (1-indexed), hour?, minute?, second?} |
calendarId | string | Source calendar ID (defaults to active calendar) |
Returns: Array<{calendarId, calendarName, date, formatted}> - Equivalent dates on all other calendars.
getCurrentDateOn(calendarId)
Section titled “getCurrentDateOn(calendarId)”Get the current date expressed on a specific (non-active) calendar.
const date = CALENDARIA.api.getCurrentDateOn('greyhawk');// Returns: { year, month, day, hour, minute }| Parameter | Type | Description |
|---|---|---|
calendarId | string | Target calendar ID |
Returns: object|null - Date on the target calendar, or null.
showSecondaryCalendar(calendarId)
Section titled “showSecondaryCalendar(calendarId)”Open a secondary calendar viewer for a non-active calendar. The viewer stays synced with worldTime.
CALENDARIA.api.showSecondaryCalendar('greyhawk');| Parameter | Type | Description |
|---|---|---|
calendarId | string | Calendar ID to view |
Returns: SecondaryCalendar - The viewer instance.
Moon phases
Section titled “Moon phases”getMoonPhase(moonIndex)
Section titled “getMoonPhase(moonIndex)”Get the current phase of a specific moon. Returns null for a moon hidden from players when the caller is not a GM.
const phase = CALENDARIA.api.getMoonPhase(0);// Returns: { name, icon, position, dayInCycle }| Parameter | Type | Description |
|---|---|---|
moonIndex | number | Index of the moon (default: 0) |
Returns: object|null - Moon phase data.
getAllMoonPhases()
Section titled “getAllMoonPhases()”Get phases for all moons in the active calendar.
const moons = CALENDARIA.api.getAllMoonPhases();Returns: Array<object|null> - One entry per configured moon, in stored order. Each entry includes moonIndex and moonName alongside the phase data. A slot is null when the moon has no phase on the current date or is hidden from a non-GM caller.
getMoonPhasePosition(moon, date)
Section titled “getMoonPhasePosition(moon, date)”Get the phase position (0 to 1) for a moon on a given date. Pass a moon definition object, not an index. The moon is resolved with moonsArray.indexOf(moon), so a number returns 0. getMoonPhase() is the index-based call.
const calendar = CALENDARIA.api.getActiveCalendar();const position = CALENDARIA.api.getMoonPhasePosition(calendar.moonsArray[0]);| Parameter | Type | Description |
|---|---|---|
moon | object | Moon definition from calendar.moonsArray |
date | object | Optional date (defaults to today) |
Returns: number - Phase position from 0 (new moon) to 1.
isMoonFull(moon, date)
Section titled “isMoonFull(moon, date)”Check whether a moon is in its full phase.
const calendar = CALENDARIA.api.getActiveCalendar();const isFull = CALENDARIA.api.isMoonFull(calendar.moonsArray[0]);| Parameter | Type | Description |
|---|---|---|
moon | object | Moon definition from calendar.moonsArray |
date | object | Optional date |
Returns: boolean - True if the moon is in its full phase.
getNextFullMoon(moon, startDate, options)
Section titled “getNextFullMoon(moon, startDate, options)”Get the date of the next full moon, or null if none is found within the search range.
const calendar = CALENDARIA.api.getActiveCalendar();const date = CALENDARIA.api.getNextFullMoon(calendar.moonsArray[0]);// Returns: { year, month, day }| Parameter | Type | Description |
|---|---|---|
moon | object | Moon definition from calendar.moonsArray |
startDate | object | Start date (defaults to the current date) |
options.maxDays | number | Maximum days to search |
Returns: object|null - Date of next full moon { year, month, day }, or null.
getNextConvergence(moons, startDate, options)
Section titled “getNextConvergence(moons, startDate, options)”Get the date when all moons are simultaneously full. Pass the moons array as the first argument.
const calendar = CALENDARIA.api.getActiveCalendar();const date = CALENDARIA.api.getNextConvergence(calendar.moonsArray);| Parameter | Type | Description |
|---|---|---|
moons | object[] | Moon definitions from calendar.moonsArray |
startDate | object | Start date (defaults to the current date) |
options.maxDays | number | Maximum days to search |
Returns: object|null - Date of next convergence, or null if not found within the search range.
getConvergencesInRange(moons, startDate, endDate)
Section titled “getConvergencesInRange(moons, startDate, endDate)”Get all dates within a range where all moons are simultaneously full. Pass the moons array as the first argument.
const calendar = CALENDARIA.api.getActiveCalendar();const dates = CALENDARIA.api.getConvergencesInRange(calendar.moonsArray, { year: 1492, month: 1, day: 1 }, { year: 1493, month: 1, day: 1 });| Parameter | Type | Description |
|---|---|---|
moons | object[] | Moon definitions from calendar.moonsArray |
startDate | object | Range start |
endDate | object | Range end |
Returns: object[] - Array of convergence dates.
Eclipses
Section titled “Eclipses”getEclipse(moonOrIndex, date)
Section titled “getEclipse(moonOrIndex, date)”Get eclipse data for a moon on a specific date.
const eclipse = CALENDARIA.api.getEclipse(0);// Returns: { type: 'totalSolar', proximity: 0.95 } or { type: null }| Parameter | Type | Description |
|---|---|---|
moonOrIndex | object|number | Moon definition or index into moonsArray |
date | object | Date to check {year, month, day} (defaults to current date) |
Returns: object - Eclipse result { type, proximity } or { type: null } if no eclipse. type is 'totalSolar', 'partialSolar', 'annularSolar', 'totalLunar', 'partialLunar', or 'penumbralLunar'.
isEclipse(date)
Section titled “isEclipse(date)”Check whether any eclipse occurs on a date, across all moons.
const eclipseToday = CALENDARIA.api.isEclipse();const eclipseOnDate = CALENDARIA.api.isEclipse({ year: 1492, month: 6, day: 21 });| Parameter | Type | Description |
|---|---|---|
date | object | Date to check (defaults to current date) |
Returns: boolean - True if any eclipse occurs.
getNextEclipse(moonOrIndex, startDate, options)
Section titled “getNextEclipse(moonOrIndex, startDate, options)”Find the next eclipse for a moon.
const next = CALENDARIA.api.getNextEclipse(0);// Returns: { date: { year, month, day }, type: 'totalLunar', proximity: 1.0 }| Parameter | Type | Description |
|---|---|---|
moonOrIndex | object|number | Moon definition or index into moonsArray |
startDate | object | Start searching from (defaults to current date) |
options.maxDays | number | Maximum days to search |
Returns: object|null - { date, type, proximity } or null if not found.
getEclipsesInRange(moonOrIndex, startDate, endDate, options)
Section titled “getEclipsesInRange(moonOrIndex, startDate, endDate, options)”Get all eclipses for a moon within a date range.
const eclipses = CALENDARIA.api.getEclipsesInRange(0, { year: 1492, month: 1, day: 1 }, { year: 1493, month: 1, day: 1 });// Returns: [{ date, type, proximity }, ...]| Parameter | Type | Description |
|---|---|---|
moonOrIndex | object|number | Moon definition or index into moonsArray |
startDate | object | Range start {year, month, day} |
endDate | object | Range end {year, month, day} |
options | object | Search options |
Returns: object[] - Array of { date, type, proximity }.
Seasons and sun
Section titled “Seasons and sun”getCurrentSeason(timestamp)
Section titled “getCurrentSeason(timestamp)”Get the season containing a given time.
const season = CALENDARIA.api.getCurrentSeason();const winter = CALENDARIA.api.getCurrentSeason(someWorldTime);| Parameter | Type | Description |
|---|---|---|
timestamp | number | World time in seconds; defaults to the current world time |
Returns: object|null - Season data with name and properties. This call returns the raw calendar season without alias resolution. For display values, use WeatherManager.getAliasedSeason.
getAliasedSeason({ scene, zoneId, time })
Section titled “getAliasedSeason({ scene, zoneId, time })”Static WeatherManager helper that resolves the current season and applies the active zone’s alias.
const season = CALENDARIA.managers.WeatherManager.getAliasedSeason({ scene, zoneId, time });| Parameter | Type | Description |
|---|---|---|
scene | Scene | Scene used to resolve the active zone when zoneId is omitted (optional) |
zoneId | string | Explicit zone ID; bypasses scene resolution (optional) |
time | number | World time in seconds used to resolve the season; defaults to the current world time |
Returns: object|null - The resolved season with alias overrides merged onto name, abbreviation, icon, and color, or null when no calendar is active.
For an explicit season + zone pair, call WeatherManager.applySeasonAlias(season, zone) directly.
getCycleValues()
Section titled “getCycleValues()”Get the current value of every cycle on the active calendar.
const cycles = CALENDARIA.api.getCycleValues();// Returns: { text, values: [{ cycleName, entryName, index }] }Returns: object|null - Current cycle values.
getSunrise(zone)
Section titled “getSunrise(zone)”Get today’s sunrise time in hours. A zone that sets both sunriseOverride and sunsetOverride returns the override unchanged across the year, skipping latitude and shortest/longest interpolation. The overrides apply only while sunrise < sunset and both sit within 0 to hoursPerDay.
const sunrise = CALENDARIA.api.getSunrise();// With explicit zone:const sunrise = CALENDARIA.api.getSunrise(myZone);// Returns: 6.5 (meaning 6:30 AM)| Parameter | Type | Description |
|---|---|---|
zone | object|null | Climate zone object (default: active scene’s zone) |
Returns: number|null - Sunrise time in hours.
getSunset(zone)
Section titled “getSunset(zone)”Get today’s sunset time in hours. A zone that sets both sunriseOverride and sunsetOverride returns the override unchanged across the year. The overrides apply only while sunrise < sunset and both sit within 0 to hoursPerDay.
const sunset = CALENDARIA.api.getSunset();// With explicit zone:const sunset = CALENDARIA.api.getSunset(myZone);// Returns: 18.5 (meaning 6:30 PM)| Parameter | Type | Description |
|---|---|---|
zone | object|null | Climate zone object (default: active scene’s zone) |
Returns: number|null - Sunset time in hours.
getDaylightHours(zone)
Section titled “getDaylightHours(zone)”Get hours of daylight today. A zone that sets both sunriseOverride and sunsetOverride returns sunsetOverride - sunriseOverride as a constant across the year.
const hours = CALENDARIA.api.getDaylightHours();// With explicit zone:const hours = CALENDARIA.api.getDaylightHours(myZone);| Parameter | Type | Description |
|---|---|---|
zone | object|null | Climate zone object (default: active scene’s zone) |
Returns: number|null - Hours of daylight.
getProgressDay(zone)
Section titled “getProgressDay(zone)”Get progress through the day period (0 = sunrise, 1 = sunset).
const progress = CALENDARIA.api.getProgressDay();// With explicit zone:const progress = CALENDARIA.api.getProgressDay(myZone);| Parameter | Type | Description |
|---|---|---|
zone | object|null | Climate zone object (default: active scene’s zone) |
Returns: number|null - Progress value between 0-1.
getProgressNight(zone)
Section titled “getProgressNight(zone)”Get progress through the night period (0 = sunset, 1 = sunrise).
const progress = CALENDARIA.api.getProgressNight();// With explicit zone:const progress = CALENDARIA.api.getProgressNight(myZone);| Parameter | Type | Description |
|---|---|---|
zone | object|null | Climate zone object (default: active scene’s zone) |
Returns: number|null - Progress value between 0-1.
getTimeUntilTarget(targetHour)
Section titled “getTimeUntilTarget(targetHour)”Get time until a specific hour of day.
const time = CALENDARIA.api.getTimeUntilTarget(12);// Returns: { hours, minutes, seconds }| Parameter | Type | Description |
|---|---|---|
targetHour | number | Target hour (0 to hoursPerDay) |
Returns: object|null - Time remaining as { hours, minutes, seconds }.
getTimeUntilSunrise()
Section titled “getTimeUntilSunrise()”Get time until next sunrise.
const time = CALENDARIA.api.getTimeUntilSunrise();// Returns: { hours, minutes, seconds }Returns: object|null - Time remaining.
getTimeUntilSunset()
Section titled “getTimeUntilSunset()”Get time until next sunset.
const time = CALENDARIA.api.getTimeUntilSunset();Returns: object|null - Time remaining.
getTimeUntilMidnight()
Section titled “getTimeUntilMidnight()”Get time until midnight.
const time = CALENDARIA.api.getTimeUntilMidnight();Returns: object|null - Time remaining.
getTimeUntilMidday()
Section titled “getTimeUntilMidday()”Get time until midday (noon).
const time = CALENDARIA.api.getTimeUntilMidday();Returns: object|null - Time remaining.
isDaytime(zone)
Section titled “isDaytime(zone)”Check whether it is currently daytime.
const daytime = CALENDARIA.api.isDaytime();| Parameter | Type | Description |
|---|---|---|
zone | object|null | Climate zone object (default: active scene’s zone) |
Returns: boolean - True if between sunrise and sunset.
isNighttime(zone)
Section titled “isNighttime(zone)”Check whether it is currently nighttime.
const nighttime = CALENDARIA.api.isNighttime();| Parameter | Type | Description |
|---|---|---|
zone | object|null | Climate zone object (default: active scene’s zone) |
Returns: boolean - True if before sunrise or after sunset.
Weekdays and rest days
Section titled “Weekdays and rest days”getCurrentWeekday()
Section titled “getCurrentWeekday()”Get the current weekday information.
const weekday = CALENDARIA.api.getCurrentWeekday();// Returns: { index, name, abbreviation, isRestDay }Returns: object|null - Weekday data.
getCurrentWeek()
Section titled “getCurrentWeek()”Get the current named week for the active world time. Exposed on the active calendar instance, not on CALENDARIA.api.
const calendar = CALENDARIA.managers.CalendarManager.getActiveCalendar();const week = calendar?.getCurrentWeek();// Returns: { weekName, weekAbbr, weekNumber, index }Returns: object|null - Named week data, or null if no named weeks are defined or no entry matches the current date.
getCurrentDayName()
Section titled “getCurrentDayName()”Get the current named day for the active world time. Exposed on the active calendar instance, not on CALENDARIA.api.
const calendar = CALENDARIA.managers.CalendarManager.getActiveCalendar();const day = calendar?.getCurrentDayName();// Returns: { dayName, dayAbbr, dayNumber, index }Pass a time value or an internal date object to resolve a different date.
Returns: object|null - Named day data, or null if no named days are defined or no entry matches the date.
isRestDay()
Section titled “isRestDay()”Check whether today is a rest day.
const isRest = CALENDARIA.api.isRestDay();Returns: boolean - True if current day is a rest day.
Festivals
Section titled “Festivals”getCurrentFestival()
Section titled “getCurrentFestival()”Get the festival on the current date, if any.
const festival = CALENDARIA.api.getCurrentFestival();Returns: object|null - Festival data with name, month, day.
isFestivalDay()
Section titled “isFestivalDay()”Check whether today is a festival day.
const isFestival = CALENDARIA.api.isFestivalDay();Returns: boolean - True if current date is a festival.
createFestival(calendarId, festivalData)
Section titled “createFestival(calendarId, festivalData)”Create a festival note for a calendar. Requires the editCalendars permission.
await CALENDARIA.api.createFestival('harptos', { name: 'Midsummer', content: '<p>The feast of Midsummer.</p>', startDate: { year: 1492, month: 7, day: 1 }, color: '#f0a500', icon: 'fa-sun', duration: 1, categories: ['festival']});| Parameter | Type | Description |
|---|---|---|
calendarId | string | Calendar ID |
festivalData.name | string | Festival name |
festivalData.content | string | Description (HTML) |
festivalData.startDate | object | Start date {year, month (1-indexed), day (1-indexed)} |
festivalData.color | string | Festival color (hex) |
festivalData.icon | string | Icon class (e.g., 'fa-sun') |
festivalData.duration | number | Duration in days (default: 1) |
festivalData.conditionTree | object | Condition tree for recurrence |
festivalData.categories | string[] | Preset IDs |
Returns: Promise<object|null> - Created note page, or null on failure.
getFestivals(calendarId)
Section titled “getFestivals(calendarId)”Get all festival notes for a calendar.
const festivals = CALENDARIA.api.getFestivals();// Or for a specific calendar:const festivals = CALENDARIA.api.getFestivals('harptos');| Parameter | Type | Description |
|---|---|---|
calendarId | string | Calendar ID (defaults to active calendar) |
Returns: object[] - Array of festival note stubs.
Formatting
Section titled “Formatting”formatDate(components, formatOrPreset)
Section titled “formatDate(components, formatOrPreset)”Format date and time components as a string.
// Using presetsconst formatted = CALENDARIA.api.formatDate(null, 'dateLong');const formatted = CALENDARIA.api.formatDate(null, 'datetime12');
// Using custom formatconst formatted = CALENDARIA.api.formatDate({ year: 1492, month: 5, day: 15 }, 'DD MMMM YYYY');| Parameter | Type | Description |
|---|---|---|
components | object | Time components (defaults to current time) |
formatOrPreset | string | Preset name or format string (default: 'dateLong') |
Presets:
| Category | Presets |
|---|---|
| Utility | 'off' |
| Approximate | 'approxDate', 'approxTime', 'approxDateTime' |
| Standard | 'dateShort', 'dateMedium', 'dateLong', 'dateFull' |
| Regional | 'dateUS', 'dateUSFull', 'dateISO', 'dateNumericUS', 'dateNumericEU' |
| Ordinal/Fantasy | 'ordinal', 'ordinalLong', 'ordinalEra', 'ordinalFull', 'seasonDate' |
| Year/Week | 'yearOnly', 'yearEra', 'weekHeader' |
| Time | 'time12', 'time12Sec', 'time24', 'time24Sec' |
| DateTime | 'datetimeShort12', 'datetimeShort24', 'datetime12', 'datetime24' |
| Stopwatch | 'stopwatchRealtimeFull', 'stopwatchRealtimeNoMs', 'stopwatchRealtimeMinSec', 'stopwatchRealtimeSecOnly', 'stopwatchGametimeFull', 'stopwatchGametimeMinSec', 'stopwatchGametimeSecOnly' |
Returns: string - Formatted date/time string.
timeSince(targetDate, currentDate)
Section titled “timeSince(targetDate, currentDate)”Get relative time description between two dates.
const relative = CALENDARIA.api.timeSince({ year: 1492, month: 5, day: 15 });// Returns: "3 days ago" or "in 2 weeks"| Parameter | Type | Description |
|---|---|---|
targetDate | object | Target date { year, month (1-indexed), day (1-indexed) } |
currentDate | object or null | Current date (defaults to current time) |
Returns: string - Relative time string.
getFormatTokens()
Section titled “getFormatTokens()”Get available format tokens and their descriptions.
const tokens = CALENDARIA.api.getFormatTokens();// Returns: [{ token, descriptionKey, type }, ...]Returns: Array<{token: string, descriptionKey: string, type: string}> - Available format tokens.
getFormatPresets()
Section titled “getFormatPresets()”Get default format presets.
const presets = CALENDARIA.api.getFormatPresets();Returns: object - Format preset definitions.
Date/time conversion
Section titled “Date/time conversion”timestampToDate(timestamp)
Section titled “timestampToDate(timestamp)”Convert a world time timestamp to date components.
const date = CALENDARIA.api.timestampToDate(86400);// Returns: { year, month, ordinal, monthName, intercalary, day, hour, minute }| Parameter | Type | Description |
|---|---|---|
timestamp | number | World time in seconds |
Returns: object|null - Date components:
| Field | Type | Description |
|---|---|---|
year | number | Year (adjusted for yearZero) |
month | number | 1-based sequential month index (includes intercalary months) |
ordinal | number | Traditional month ordinal (may be shared by intercalary and regular months) |
monthName | string | Month name exactly as stored on the calendar. Bundled calendars store a localization key here, so run it through game.i18n.localize() before displaying it |
intercalary | boolean | Whether this month is an intercalary (festival) month |
day | number | 1-based day of month |
hour | number | Hour |
minute | number | Minute |
dateToTimestamp(date)
Section titled “dateToTimestamp(date)”Convert date components to a world time timestamp.
// Using sequential month indexconst timestamp = CALENDARIA.api.dateToTimestamp({ year: 1492, month: 5, day: 15, hour: 10, minute: 30});
// Using ordinal (prefers non-intercalary months when ordinals are shared)const timestamp2 = CALENDARIA.api.dateToTimestamp({ year: 729, ordinal: 7, day: 1});| Parameter | Type | Description |
|---|---|---|
date | object | Date components |
date.year | number | Year |
date.month | number | 1-based sequential month index (takes priority over ordinal) |
date.ordinal | number | Traditional month ordinal (used if month is not provided) |
date.day | number | 1-based day of month |
date.hour | number | Hour (optional, default 0) |
date.minute | number | Minute (optional, default 0) |
date.second | number | Second (optional, default 0) |
Returns: number - World time in seconds.
chooseRandomDate(startDate, endDate)
Section titled “chooseRandomDate(startDate, endDate)”Generate a random date within a range.
const randomDate = CALENDARIA.api.chooseRandomDate({ year: 1492, month: 1, day: 1 }, { year: 1492, month: 12, day: 31 });| Parameter | Type | Description |
|---|---|---|
startDate | object | Start date (defaults to current date) |
endDate | object | End date (defaults to 1 year from start) |
Returns: object - Random date components.
Date arithmetic
Section titled “Date arithmetic”addDays(date, days)
Section titled “addDays(date, days)”Add days to a date.
const newDate = CALENDARIA.api.addDays({ year: 1492, month: 5, day: 15 }, 10);// Returns date 10 days later| Parameter | Type | Description |
|---|---|---|
date | object | Date { year, month, day } |
days | number | Days to add (negative to subtract) |
Returns: object - New date components.
addMonths(date, months)
Section titled “addMonths(date, months)”Add months to a date.
const newDate = CALENDARIA.api.addMonths({ year: 1492, month: 5, day: 15 }, 3);| Parameter | Type | Description |
|---|---|---|
date | object | Date { year, month, day } |
months | number | Months to add (negative to subtract) |
Returns: object - New date components.
addYears(date, years)
Section titled “addYears(date, years)”Add years to a date.
const newDate = CALENDARIA.api.addYears({ year: 1492, month: 5, day: 15 }, 10);| Parameter | Type | Description |
|---|---|---|
date | object | Date { year, month, day } |
years | number | Years to add (negative to subtract) |
Returns: object - New date components.
addHours(date, hours)
Section titled “addHours(date, hours)”Add hours to a date.
const newDate = CALENDARIA.api.addHours({ year: 1492, month: 5, day: 15, hour: 10 }, 8);| Parameter | Type | Description |
|---|---|---|
date | object | Date { year, month, day, hour?, minute? } |
hours | number | Hours to add (negative to subtract) |
Returns: object - New date components.
addMinutes(date, minutes)
Section titled “addMinutes(date, minutes)”Add minutes to a date.
const newDate = CALENDARIA.api.addMinutes({ year: 1492, month: 5, day: 15, hour: 10, minute: 30 }, 45);| Parameter | Type | Description |
|---|---|---|
date | object | Date { year, month, day, hour?, minute? } |
minutes | number | Minutes to add (negative to subtract) |
Returns: object - New date components.
addSeconds(date, seconds)
Section titled “addSeconds(date, seconds)”Add seconds to a date.
const newDate = CALENDARIA.api.addSeconds({ year: 1492, month: 5, day: 15, hour: 10 }, 3600);| Parameter | Type | Description |
|---|---|---|
date | object | Date { year, month, day, hour?, minute? } |
seconds | number | Seconds to add (negative to subtract) |
Returns: object - New date components.
daysBetween(startDate, endDate)
Section titled “daysBetween(startDate, endDate)”Calculate the number of days between two dates.
const days = CALENDARIA.api.daysBetween({ year: 1492, month: 5, day: 1 }, { year: 1492, month: 5, day: 15 });// Returns: 14| Parameter | Type | Description |
|---|---|---|
startDate | object | Start date { year, month, day } |
endDate | object | End date { year, month, day } |
Returns: number - Days between dates (positive if endDate is later).
monthsBetween(startDate, endDate)
Section titled “monthsBetween(startDate, endDate)”Calculate the number of months between two dates.
const months = CALENDARIA.api.monthsBetween({ year: 1492, month: 1, day: 1 }, { year: 1492, month: 7, day: 1 });// Returns: 6| Parameter | Type | Description |
|---|---|---|
startDate | object | Start date { year, month, day } |
endDate | object | End date { year, month, day } |
Returns: number - Months between dates.
hoursBetween(startDate, endDate)
Section titled “hoursBetween(startDate, endDate)”Calculate hours between two dates.
const hours = CALENDARIA.api.hoursBetween({ year: 1492, month: 5, day: 1, hour: 8 }, { year: 1492, month: 5, day: 1, hour: 17 });// Returns: 9| Parameter | Type | Description |
|---|---|---|
startDate | object | Start date { year, month, day, hour?, minute? } |
endDate | object | End date { year, month, day, hour?, minute? } |
Returns: number - Hours between dates (can be negative/fractional).
minutesBetween(startDate, endDate)
Section titled “minutesBetween(startDate, endDate)”Calculate minutes between two dates.
const minutes = CALENDARIA.api.minutesBetween({ year: 1492, month: 5, day: 1, hour: 8, minute: 0 }, { year: 1492, month: 5, day: 1, hour: 8, minute: 45 });// Returns: 45| Parameter | Type | Description |
|---|---|---|
startDate | object | Start date { year, month, day, hour?, minute? } |
endDate | object | End date { year, month, day, hour?, minute? } |
Returns: number - Minutes between dates (can be negative).
secondsBetween(startDate, endDate)
Section titled “secondsBetween(startDate, endDate)”Calculate seconds between two dates.
const seconds = CALENDARIA.api.secondsBetween({ year: 1492, month: 5, day: 1, hour: 8 }, { year: 1492, month: 5, day: 1, hour: 9 });// Returns: 3600| Parameter | Type | Description |
|---|---|---|
startDate | object | Start date { year, month, day, hour?, minute? } |
endDate | object | End date { year, month, day, hour?, minute? } |
Returns: number - Seconds between dates (can be negative).
compareDates(date1, date2)
Section titled “compareDates(date1, date2)”Compare two dates including time components.
const result = CALENDARIA.api.compareDates({ year: 1492, month: 5, day: 15, hour: 10 }, { year: 1492, month: 5, day: 15, hour: 14 });// Returns: -1 (date1 is earlier)| Parameter | Type | Description |
|---|---|---|
date1 | object | First date |
date2 | object | Second date |
Returns: number - -1 if date1 < date2, 0 if equal, 1 if date1 > date2.
compareDays(date1, date2)
Section titled “compareDays(date1, date2)”Compare two dates ignoring time components.
const result = CALENDARIA.api.compareDays({ year: 1492, month: 5, day: 15 }, { year: 1492, month: 5, day: 20 });// Returns: -1 (date1 is earlier)| Parameter | Type | Description |
|---|---|---|
date1 | object | First date |
date2 | object | Second date |
Returns: number - -1 if date1 < date2, 0 if same day, 1 if date1 > date2.
isSameDay(date1, date2)
Section titled “isSameDay(date1, date2)”Check whether two dates fall on the same day.
const same = CALENDARIA.api.isSameDay({ year: 1492, month: 5, day: 15, hour: 10 }, { year: 1492, month: 5, day: 15, hour: 20 });// Returns: true| Parameter | Type | Description |
|---|---|---|
date1 | object | First date |
date2 | object | Second date |
Returns: boolean - True if same calendar day.
dayOfWeek(date)
Section titled “dayOfWeek(date)”Get the weekday index for a date.
const weekday = CALENDARIA.api.dayOfWeek({ year: 1492, month: 5, day: 15 });// Returns: 0-6 depending on calendar weekdays| Parameter | Type | Description |
|---|---|---|
date | object | Date { year, month, day } |
Returns: number - Weekday index (0-based).
isValidDate(date)
Section titled “isValidDate(date)”Check whether a date is valid on the active calendar.
const valid = CALENDARIA.api.isValidDate({ year: 1492, month: 5, day: 31 });| Parameter | Type | Description |
|---|---|---|
date | object | Date { year, month, day } |
Returns: boolean - True if date exists in the calendar.
getAllNotes()
Section titled “getAllNotes()”Get all calendar notes.
const notes = CALENDARIA.api.getAllNotes();Returns: object[] - Array of note stubs with id, name, flagData, etc.
getNote(pageId)
Section titled “getNote(pageId)”Get a specific note by ID.
const note = CALENDARIA.api.getNote('abc123');| Parameter | Type | Description |
|---|---|---|
pageId | string | Journal entry page ID |
Returns: object|null - Note stub or null.
getNoteDocument(pageId)
Section titled “getNoteDocument(pageId)”Get the full Foundry JournalEntryPage document for a note.
const page = CALENDARIA.api.getNoteDocument('abc123');// Access full document propertiesconsole.log(page.text.content);| Parameter | Type | Description |
|---|---|---|
pageId | string | Journal entry page ID |
Returns: JournalEntryPage|null - Full Foundry document or null.
createNote(options)
Section titled “createNote(options)”Create a new calendar note. Players can create their own notes; a GM can create notes for anyone.
const note = await CALENDARIA.api.createNote({ name: 'Council Meeting', content: "<p>Meeting with the Lords' Alliance</p>", startDate: { year: 1492, month: 5, day: 15, hour: 14, minute: 0 }, endDate: { year: 1492, month: 5, day: 15, hour: 16, minute: 0 }, allDay: false, categories: ['meeting'], icon: 'fas fa-handshake', color: '#4a90e2', visibility: 'visible', openSheet: 'edit'});| Parameter | Type | Description |
|---|---|---|
options.name | string | Note title |
options.content | string | Note content (HTML). If omitted and categories are set, the preset’s content template is used |
options.startDate | object | Start date {year, month, day, hour?, minute?} (1-indexed month/day) |
options.endDate | object | End date (optional) |
options.allDay | boolean | All-day event (default: true) |
options.conditionTree | object | Condition tree for recurrence scheduling (see below) |
options.categories | string[] | Preset IDs |
options.icon | string | Icon path or class |
options.color | string | Event color (hex) |
options.visibility | string | 'visible', 'hidden', or 'secret' (default: 'visible') |
options.displayStyle | string | 'icon', 'pip', or 'banner' (default: 'icon') |
options.subjects | string[] | Document UUIDs the note is about |
options.reminderType | string | 'none', 'toast', 'chat', or 'dialog' |
options.reminderTargets | string | 'all', 'gm', 'author', 'specific', or 'viewers' |
options.reminderUsers | string[] | User IDs notified when reminderTargets is 'specific' |
options.reminderOffset | number | How far ahead of the note the reminder fires |
options.reminderUnit | string | Offset unit: 'hour', 'day', 'week', 'month', or 'year' |
options.openSheet | false|'edit'|'view' | Open the note sheet after creation in the given mode (default: 'edit'). Pass boolean false to skip |
Recurrence with conditionTree
Section titled “Recurrence with conditionTree”A conditionTree is a group of conditions evaluated against each candidate date. For a recurring annual event, use a fixed month/day group:
// Birthday on Aug 23 every yearawait CALENDARIA.api.createNote({ name: "Aldric's Birthday", startDate: { year: 1492, month: 8, day: 23 }, categories: ['birthday'], conditionTree: { type: 'group', mode: 'and', children: [ { type: 'condition', field: 'month', op: '==', value: 8 }, { type: 'condition', field: 'day', op: '==', value: 23 } ] }});The type: 'group' field is required on the root. Without it the tree is ignored and the note only fires on its exact startDate. Inside conditions, month and day are 1-indexed, matching the UI. Internally startDate.month and startDate.dayOfMonth are 0-indexed, and the public API converts between the two.
Returns: Promise<object|null> - The created note page. Resolves to null when the caller lacks the addNotes permission. It also resolves to null for a player who lacks Foundry’s journal-creation permission. That request goes to the GM, who creates the note, but the page never comes back to the calling client.
updateNote(pageId, updates)
Section titled “updateNote(pageId, updates)”Update an existing note. Requires a GM user or ownership of the note.
await CALENDARIA.api.updateNote('abc123', { name: 'Rescheduled Meeting', content: '<p>Moved to the upper hall.</p>', startDate: { year: 1492, month: 5, day: 16, hour: 14 }});| Parameter | Type | Description |
|---|---|---|
pageId | string | Journal entry page ID |
updates.name | string | New note title |
updates.content | string | New note content (HTML) |
updates.startDate | object | New start date {year, month, day, hour?, minute?} (1-indexed month/day) |
updates.endDate | object | New end date {year, month, day, hour?, minute?} (1-indexed month/day) |
updates.allDay | boolean | New all-day setting |
updates.conditionTree | object | New condition tree for recurrence |
updates.categories | string[] | New preset IDs |
updates.icon | string | New icon |
updates.color | string | New color |
updates.visibility | string | New visibility: 'visible', 'hidden', 'secret' |
updates.displayStyle | string | New display style: 'icon', 'pip', 'banner' |
updates.subjects | string[] | Document UUIDs the note is about |
Returns: Promise<object|null> - Updated note page.
deleteNote(pageId)
Section titled “deleteNote(pageId)”Delete a calendar note.
await CALENDARIA.api.deleteNote('abc123');| Parameter | Type | Description |
|---|---|---|
pageId | string | Journal entry page ID |
Returns: Promise<boolean> - True if deleted successfully.
deleteAllNotes()
Section titled “deleteAllNotes()”Delete all calendar notes. Requires the deleteNotes permission.
await CALENDARIA.api.deleteAllNotes();Returns: Promise<number> - Number of notes deleted.
setNoteVisibility(pageId, visibility)
Section titled “setNoteVisibility(pageId, visibility)”Set a note’s visibility level.
await CALENDARIA.api.setNoteVisibility('abc123', 'hidden');| Parameter | Type | Description |
|---|---|---|
pageId | string | Journal entry page ID |
visibility | string | 'visible', 'hidden', or 'secret' |
Setting 'secret' requires a GM user. A non-GM call leaves the visibility unchanged and shows a permission warning.
Returns: Promise<object|null> - Updated note page, or null on failure.
setNoteDisplayStyle(pageId, style)
Section titled “setNoteDisplayStyle(pageId, style)”Set a note’s display style.
await CALENDARIA.api.setNoteDisplayStyle('abc123', 'banner');| Parameter | Type | Description |
|---|---|---|
pageId | string | Journal entry page ID |
style | string | 'icon', 'pip', or 'banner' |
Returns: Promise<object|null> - Updated note page, or null on failure.
navigateToNote(pageId, options)
Section titled “navigateToNote(pageId, options)”Navigate an open calendar to a note’s date and open its sheet.
await CALENDARIA.api.navigateToNote('abc123');| Parameter | Type | Description |
|---|---|---|
pageId | string | Journal entry page ID |
options.context | string | Force target, opening it if closed: 'bigcal' or 'minical'. When omitted, navigation happens only in an already-open calendar and nothing is opened |
options.mode | string | 'view' or 'edit' for the note sheet (default: 'view') |
Returns: Promise<void>
navigateToDate(year, month, day)
Section titled “navigateToDate(year, month, day)”Navigate an open calendar to a date without touching a note.
await CALENDARIA.api.navigateToDate(1492, 5, 15);| Parameter | Type | Description |
|---|---|---|
year | number | Display year |
month | number | Month (1-indexed) |
day | number | Day of month (1-indexed) |
The target follows the Enricher Click Target setting. minical uses the MiniCal, bigcal uses the BigCal, and auto uses the MiniCal when it is already rendered and the BigCal is not, and otherwise uses the BigCal. The chosen calendar is opened if it is closed.
Returns: Promise<void>
openNote(pageId, options)
Section titled “openNote(pageId, options)”Open a note in the UI.
await CALENDARIA.api.openNote('abc123', { mode: 'edit' });| Parameter | Type | Description |
|---|---|---|
pageId | string | Journal entry page ID |
options.mode | string | 'view' or 'edit' (default: 'view') |
Returns: Promise<void>
Note queries
Section titled “Note queries”getNotesForDate(year, month, day, options)
Section titled “getNotesForDate(year, month, day, options)”Get notes on a specific date.
const notes = CALENDARIA.api.getNotesForDate(1492, 5, 15);// With full content:const notes = CALENDARIA.api.getNotesForDate(1492, 5, 15, { includeContent: true });| Parameter | Type | Description |
|---|---|---|
year | number | Display year |
month | number | Month (1-indexed) |
day | number | Day of month (1-indexed) |
options.includeContent | boolean | Include note HTML content in results (default: false) |
options.includeOccurrences | boolean | Add nextOccurrence to each stub, a public-format date or null (default: false) |
Returns: object[] - Array of note stubs.
getNotesForMonth(year, month, options)
Section titled “getNotesForMonth(year, month, options)”Get all notes in a month.
const notes = CALENDARIA.api.getNotesForMonth(1492, 5);// With full content:const notes = CALENDARIA.api.getNotesForMonth(1492, 5, { includeContent: true });| Parameter | Type | Description |
|---|---|---|
year | number | Display year |
month | number | Month (1-indexed) |
options.includeContent | boolean | Include note HTML content in results (default: false) |
options.includeOccurrences | boolean | Add nextOccurrence to each stub, a public-format date or null (default: false) |
Returns: object[] - Array of note stubs.
getNotesInRange(startDate, endDate, options)
Section titled “getNotesInRange(startDate, endDate, options)”Get notes within a date range.
const notes = CALENDARIA.api.getNotesInRange({ year: 1492, month: 5, day: 1 }, { year: 1492, month: 5, day: 31 });// With full content:const notes = CALENDARIA.api.getNotesInRange({ year: 1492, month: 5, day: 1 }, { year: 1492, month: 5, day: 31 }, { includeContent: true });| Parameter | Type | Description |
|---|---|---|
startDate | object | Start date {year, month, day} |
endDate | object | End date {year, month, day} |
options.includeContent | boolean | Include note HTML content in results (default: false) |
options.includeOccurrences | boolean | Add nextOccurrence to each stub, a public-format date or null (default: false) |
options.maxOccurrences | number | Cap on occurrences counted per note when includeOccurrences is set (default: 100) |
With includeOccurrences set, each stub also carries an occurrenceCount holding the number of times the note falls inside the queried range.
Returns: object[] - Array of note stubs.
searchNotes(searchTerm, options)
Section titled “searchNotes(searchTerm, options)”Search notes by name or content.
const results = CALENDARIA.api.searchNotes('dragon', { caseSensitive: false, categories: ['quest']});| Parameter | Type | Description |
|---|---|---|
searchTerm | string | Text to search for |
options.caseSensitive | boolean | Case-sensitive search (default: false) |
options.categories | string[] | Filter by category IDs |
Returns: object[] - Array of note stubs.
getNotesByPreset(presetId)
Section titled “getNotesByPreset(presetId)”Get notes with a specific preset (category).
const notes = CALENDARIA.api.getNotesByPreset('meeting');| Parameter | Type | Description |
|---|---|---|
presetId | string | Preset ID |
Returns: object[] - Array of note stubs.
getPresets()
Section titled “getPresets()”Get all preset (category) definitions.
const presets = CALENDARIA.api.getPresets();Returns: object[] - Array of preset definitions.
addPreset(options)
Section titled “addPreset(options)”Add a custom note preset. GM only.
const preset = await CALENDARIA.api.addPreset({ label: 'Session Log', color: '#51cf66', icon: 'fas fa-book-open', defaults: { allDay: true, displayStyle: 'icon', content: '<p><strong>Recap</strong></p><p></p><p><strong>Key Events</strong></p><p></p>' }});| Parameter | Type | Description |
|---|---|---|
options.label | string | Display name (required) |
options.color | string | Hex color |
options.icon | string | FontAwesome icon class |
options.playerUsable | boolean | Allow non-GM users to apply the preset (default: true) |
options.sortOrder | number | Explicit sort order (default: end of the list) |
options.defaults | object | Default values for notes created with this preset |
options.defaults.allDay | boolean | Default all-day setting |
options.defaults.displayStyle | string | 'icon', 'pip', or 'banner' |
options.defaults.visibility | string | 'visible', 'hidden', or 'secret' |
options.defaults.reminderType | string | 'toast', 'chat', or 'dialog' |
options.defaults.reminderOffset | number | Reminder offset in hours |
options.defaults.hasDuration | boolean | Default multi-day setting |
options.defaults.duration | number | Default duration in days |
options.defaults.macro | string | Macro ID to execute |
options.defaults.content | string | HTML content template pre-filled into new notes |
Returns: Promise<object> - The created preset.
updatePreset(presetId, updates)
Section titled “updatePreset(presetId, updates)”Update a note preset’s properties.
await CALENDARIA.api.updatePreset('session', { defaults: { content: '<p><strong>Session Notes</strong></p><p></p>' }});| Parameter | Type | Description |
|---|---|---|
presetId | string | Preset ID |
updates.label | string | New display name |
updates.color | string | New hex color |
updates.icon | string | New FontAwesome icon class |
updates.playerUsable | boolean | Allow non-GM users |
updates.sortOrder | number | New sort order |
updates.defaults | object | Default values (merged with existing) |
Returns: Promise<object|null> - Updated preset or null if not found.
deletePreset(presetId)
Section titled “deletePreset(presetId)”Delete a custom note preset.
await CALENDARIA.api.deletePreset('my-custom-preset');| Parameter | Type | Description |
|---|---|---|
presetId | string | Preset ID to delete |
Returns: Promise<boolean> - True if deleted.
Search
Section titled “Search”search(term, options)
Section titled “search(term, options)”Search calendar notes by title, preset label, and note content. Only notes the current user can see are returned.
const results = CALENDARIA.api.search('council', { limit: 10 });const meetings = CALENDARIA.api.search('preset:meeting');| Parameter | Type | Description |
|---|---|---|
term | string | Search term (minimum 2 characters) |
options.searchContent | boolean | Search note content (default: true) |
options.limit | number | Max results (default: 50) |
A term beginning with preset: switches to preset matching. The remainder is matched against preset labels, and every note carrying a matching preset is returned.
Returns: object[] - Array of results, each carrying type: 'note'.
Condition engine
Section titled “Condition engine”createCondition(field, op, …values)
Section titled “createCondition(field, op, …values)”Create a condition object for use in a condition tree.
const condition = CALENDARIA.api.createCondition('weekday', '==', 0);// Returns: { type: 'condition', field: 'weekday', op: '==', value: 0 }| Parameter | Type | Description |
|---|---|---|
field | string | Condition field (see conditionFields enum) |
op | string | Comparison operator (see conditionOperators enum) |
...values | * | Condition value(s). First is primary, second (if any) is secondary value |
Returns: object - Condition {type: 'condition', field, op, value, value2?}.
createConditionGroup(mode, children, options)
Section titled “createConditionGroup(mode, children, options)”Create a condition group for combining conditions with boolean logic.
const group = CALENDARIA.api.createConditionGroup('and', [CALENDARIA.api.createCondition('weekday', '==', 0), CALENDARIA.api.createCondition('month', '==', 5)]);// Returns: { type: 'group', mode: 'and', children: [...] }| Parameter | Type | Description |
|---|---|---|
mode | string | 'and', 'or', 'nand', 'xor', or 'count' |
children | object[] | Array of condition objects and/or nested groups |
options.threshold | number | Required match count for 'count' mode |
Returns: object - Group {type: 'group', mode, children, threshold?}.
evaluateNote(pageId, date, options)
Section titled “evaluateNote(pageId, date, options)”Check whether a note occurs on a date by evaluating its condition tree.
const matches = CALENDARIA.api.evaluateNote('abc123', { year: 1492, month: 5, day: 15 });// Silent evaluation (no hook):const matches = CALENDARIA.api.evaluateNote('abc123', { year: 1492, month: 5, day: 15 }, { silent: true });| Parameter | Type | Description |
|---|---|---|
pageId | string | Journal entry page ID |
date | object | Date to check {year, month (1-indexed), day (1-indexed)} |
options.silent | boolean | Skip firing the CONDITION_EVALUATED hook (default: false) |
Returns: boolean - True if the note occurs on this date.
Recurrence
Section titled “Recurrence”getNextOccurrences(pageId, count)
Section titled “getNextOccurrences(pageId, count)”Get the next N occurrences of a recurring note from the current date.
const dates = CALENDARIA.api.getNextOccurrences('abc123', 10);// Returns: [{ year, month, day }, ...]| Parameter | Type | Description |
|---|---|---|
pageId | string | Journal entry page ID |
count | number | Number of occurrences to find (default: 5) |
Returns: object[] - Array of date objects {year, month (1-indexed), day (1-indexed)}.
getNoteOccurrencesInRange(pageId, startDate, endDate, maxOccurrences)
Section titled “getNoteOccurrencesInRange(pageId, startDate, endDate, maxOccurrences)”Get all occurrences of a note within a date range.
const dates = CALENDARIA.api.getNoteOccurrencesInRange('abc123', { year: 1492, month: 1, day: 1 }, { year: 1493, month: 1, day: 1 });| Parameter | Type | Description |
|---|---|---|
pageId | string | Journal entry page ID |
startDate | object | Range start {year, month (1-indexed), day (1-indexed)} |
endDate | object | Range end {year, month (1-indexed), day (1-indexed)} |
maxOccurrences | number | Maximum occurrences to return (default: 100) |
Returns: object[] - Array of date objects {year, month (1-indexed), day (1-indexed)}.
Cinematic Time Skip
Section titled “Cinematic Time Skip”isCinematicActive()
Section titled “isCinematicActive()”Check whether a cinematic overlay is currently playing.
const active = CALENDARIA.api.isCinematicActive();Returns: boolean - True if a cinematic is playing.
playCinematic(payload)
Section titled “playCinematic(payload)”Play a cinematic overlay with a pre-built payload.
const payload = CALENDARIA.api.buildCinematicPayload(startTime, endTime);await CALENDARIA.api.playCinematic(payload);| Parameter | Type | Description |
|---|---|---|
payload | object | Cinematic payload (from buildCinematicPayload) |
Returns: Promise<void> - Resolves when the cinematic completes or is aborted.
abortCinematic()
Section titled “abortCinematic()”Abort the currently playing cinematic.
CALENDARIA.api.abortCinematic();Returns: void
pauseCinematic()
Section titled “pauseCinematic()”Pause the playing cinematic. The overlay stays on screen and the progress bar, date counter, and sky hold their position.
CALENDARIA.api.pauseCinematic();Returns: void
resumeCinematic()
Section titled “resumeCinematic()”Continue a paused cinematic from where it stopped. Time spent paused does not count against the animation.
CALENDARIA.api.resumeCinematic();Returns: void
isCinematicPaused()
Section titled “isCinematicPaused()”Check whether the playing cinematic is paused.
const paused = CALENDARIA.api.isCinematicPaused();Returns: boolean - True if a cinematic is playing and paused.
buildCinematicPayload(startTime, endTime)
Section titled “buildCinematicPayload(startTime, endTime)”Build a cinematic payload without playing it. Feed it to playCinematic().
const payload = CALENDARIA.api.buildCinematicPayload(game.time.worldTime, game.time.worldTime + 604800);| Parameter | Type | Description |
|---|---|---|
startTime | number | Start world time (seconds) |
endTime | number | End world time (seconds) |
Returns: object - Cinematic payload with keyframes and settings.
Fog of War
Section titled “Fog of War”isFogEnabled()
Section titled “isFogEnabled()”Check whether Fog of War is enabled.
const enabled = CALENDARIA.api.isFogEnabled();Returns: boolean
isDateRevealed(year, month, day, calendarId?)
Section titled “isDateRevealed(year, month, day, calendarId?)”Check whether a specific date is revealed for the current user. GMs always get true. Returns true if fog is disabled.
CALENDARIA.api.isDateRevealed(1492, 6, 15);CALENDARIA.api.isDateRevealed(1492, 6, 15, 'harptos');| Parameter | Type | Description |
|---|---|---|
year | number | Year |
month | number | Month (1-indexed) |
day | number | Day (1-indexed) |
calendarId | string | Calendar ID (optional, defaults to active) |
Returns: boolean
getRevealedRanges(calendarId?)
Section titled “getRevealedRanges(calendarId?)”Get all revealed date ranges for a calendar.
const ranges = CALENDARIA.api.getRevealedRanges();// [{ start: { year: 1492, month: 1, day: 1 }, end: { year: 1492, month: 6, day: 15 } }]| Parameter | Type | Description |
|---|---|---|
calendarId | string | Calendar ID (optional, defaults to active) |
Returns: Array<{start, end}> - Each with {year, month, day} (1-indexed).
revealDateRange(start, end, calendarId?)
Section titled “revealDateRange(start, end, calendarId?)”Reveal a date range. GM only. Overlapping and adjacent ranges merge automatically.
await CALENDARIA.api.revealDateRange({ year: 1492, month: 1, day: 1 }, { year: 1492, month: 6, day: 15 });| Parameter | Type | Description |
|---|---|---|
start | object | Start date {year, month (1-indexed), day (1-indexed)} |
end | object | End date {year, month (1-indexed), day (1-indexed)} |
calendarId | string | Calendar ID (optional, defaults to active) |
Returns: Promise<void>
clearRevealedRanges(calendarId?)
Section titled “clearRevealedRanges(calendarId?)”Clear all revealed ranges for a calendar. GM only.
await CALENDARIA.api.clearRevealedRanges();| Parameter | Type | Description |
|---|---|---|
calendarId | string | Calendar ID (optional, defaults to active) |
Returns: Promise<void>
Date picker
Section titled “Date picker”showDatePicker(options)
Section titled “showDatePicker(options)”Show a date picker dialog. The promise resolves with the selected date. Pass onSelect to also get a callback.
const date = await CALENDARIA.api.showDatePicker({ showTime: true });// Returns: { year, month, day, hour, minute } or null if cancelled
// With callback and positioning:CALENDARIA.api.showDatePicker({ title: 'Select Date', position: { x: 200, y: 300 }, onSelect: (date) => console.log('Selected:', date)});| Parameter | Type | Description |
|---|---|---|
options.date | object | Initial date {year, month (1-indexed), day (1-indexed)} (defaults to current) |
options.showTime | boolean | Show time inputs (default: false) |
options.title | string | Custom dialog title |
options.position | object | Dialog position {x, y} in pixels |
options.onSelect | Function | Callback fired with the selected date |
Returns: Promise<object|null> - Selected date or null if cancelled.
Application controls
Section titled “Application controls”All applications have show, hide, and toggle methods on the public API.
showBigCal(), showMiniCal(), showHUD(), showTimeKeeper(), showStopwatch(), and showChronicle() return null when the call is refused. A call is refused when the user lacks that application’s view permission, or when the application’s combat-blocking setting suppresses it during combat. showSunDial() returns nothing in the same cases. Check the return value before calling methods on it.
// BigCalCALENDARIA.api.showBigCal();CALENDARIA.api.hideBigCal();CALENDARIA.api.toggleBigCal();
// MiniCalCALENDARIA.api.showMiniCal();CALENDARIA.api.hideMiniCal();CALENDARIA.api.toggleMiniCal();
// HUDCALENDARIA.api.showHUD();CALENDARIA.api.hideHUD();CALENDARIA.api.toggleHUD();
// TimeKeeperCALENDARIA.api.showTimeKeeper();CALENDARIA.api.hideTimeKeeper();CALENDARIA.api.toggleTimeKeeper();
// Sun DialCALENDARIA.api.showSunDial();CALENDARIA.api.showSunDial({ closeOnClickOutside: true });CALENDARIA.api.hideSunDial();CALENDARIA.api.toggleSunDial();
// StopwatchCALENDARIA.api.showStopwatch();CALENDARIA.api.hideStopwatch();CALENDARIA.api.toggleStopwatch();
// ChronicleCALENDARIA.api.showChronicle();CALENDARIA.api.showChronicle({ startDate, endDate, lockedRange: true, calendarId });CALENDARIA.api.hideChronicle();CALENDARIA.api.toggleChronicle();
// Note Viewer (supports pre-filter options)CALENDARIA.api.showNoteViewer();CALENDARIA.api.showNoteViewer({ date: { year: 1492, month: 5, day: 15 } });CALENDARIA.api.showNoteViewer({ preset: 'meeting', search: 'dragon' });CALENDARIA.api.showNoteViewer({ visibility: 'hidden' });CALENDARIA.api.hideNoteViewer();CALENDARIA.api.toggleNoteViewer();
// Secondary CalendarCALENDARIA.api.showSecondaryCalendar('greyhawk');showChronicle(options)
Section titled “showChronicle(options)”Show the Chronicle with an optional locked date range.
| Parameter | Type | Description |
|---|---|---|
options.startDate | object | Range start {year, month (0-indexed), dayOfMonth (0-indexed)} |
options.endDate | object | Range end {year, month (0-indexed), dayOfMonth (0-indexed)} |
options.lockedRange | boolean | Locks the view to startDate/endDate |
options.calendarId | string | Calendar ID whose entries drive the view |
options.theme | string | 'parchment', 'logbook', 'arcane', or 'modern' |
options.categoryFilter | string[]|null | Preset IDs to restrict the view to; null restores the saved filter |
options.subjectFilter | string[]|null | Subject document UUIDs to restrict the view to; null clears the filter |
The Chronicle takes internal date components, not the 1-indexed form the rest of the API uses.
Returns: Chronicle - The chronicle instance, or null when the call is refused.
showNoteViewer(options)
Section titled “showNoteViewer(options)”Show the Note Viewer with optional pre-filters.
| Parameter | Type | Description |
|---|---|---|
options.date | object | Pre-filter to date {year, month (1-indexed), day (1-indexed)} |
options.preset | string | Pre-filter to preset ID |
options.search | string | Pre-filter with search term |
options.visibility | string | Pre-filter to visibility level |
Returns: NoteViewer - The viewer instance.
Stopwatch controls
Section titled “Stopwatch controls”CALENDARIA.api.startStopwatch(); // Show and startCALENDARIA.api.pauseStopwatch(); // Pause if runningCALENDARIA.api.resetStopwatch(); // Reset to zeroopenCalendarEditor(calendarId)
Section titled “openCalendarEditor(calendarId)”Open the calendar editor. Requires the editCalendars permission.
await CALENDARIA.api.openCalendarEditor(); // New calendarawait CALENDARIA.api.openCalendarEditor('custom'); // Edit existing| Parameter | Type | Description |
|---|---|---|
calendarId | string | Calendar ID to edit (omit for new) |
Returns: Promise<object|null> - The editor application.
Weather
Section titled “Weather”Every weather write requires the changeWeather permission: setWeather(), setCustomWeather(), clearWeather(), generateWeather(), setActiveZone(), addWeatherPreset(), removeWeatherPreset(), and updateWeatherPreset(). A caller without it changes nothing. setWeather(), setCustomWeather(), and generateWeather() return the current weather unchanged, the preset methods return null or false, and clearWeather() and setActiveZone() return nothing.
setWeather(), clearWeather(), and generateWeather() do not write directly when a non-GM with the permission calls them. The call is relayed to the GM over a socket. setWeather() and generateWeather() resolve with the state as it stood before the request. setCustomWeather() refuses outright for a non-GM caller and shows a warning.
getCurrentWeather(zoneId)
Section titled “getCurrentWeather(zoneId)”Get current weather state, optionally for a specific zone.
const weather = CALENDARIA.api.getCurrentWeather();// With specific zone:const weather = CALENDARIA.api.getCurrentWeather('desert');// Returns: { id, label, icon, color, temperature, wind, precipitation, severity, ... }| Parameter | Type | Description |
|---|---|---|
zoneId | string | Optional zone ID (defaults to active scene’s zone) |
Returns: object|null - Current weather state including wind { speed, direction, forced }, precipitation { type, intensity }, and a derived severity on a 0-10 scale.
severity is derived when you read the weather, not stored on it. Four scores feed it: wind speed, precipitation intensity, how far the temperature sits into the heat or cold extremes, and the darkness penalty. They are sorted highest first and stacked with descending weight, so the worst hazard contributes the most. When intraday weather is enabled, each entry under periods carries its own severity.
getWeatherSeverityLabel(severity)
Section titled “getWeatherSeverityLabel(severity)”Get the localized band label for a severity value.
const weather = CALENDARIA.api.getCurrentWeather();const label = CALENDARIA.api.getWeatherSeverityLabel(weather.severity);| Parameter | Type | Description |
|---|---|---|
severity | number | Severity on the 0-10 scale |
Returns: string - Localized band label, or an empty string when the value is missing.
getWeatherSeverityLevel(severity)
Section titled “getWeatherSeverityLevel(severity)”Get the named band a severity value falls into.
const band = CALENDARIA.api.getWeatherSeverityLevel(7);// Returns: { id: 'severe', min: 6, label: 'CALENDARIA.Weather.Severity.Severe' }| Parameter | Type | Description |
|---|---|---|
severity | number | Severity on the 0-10 scale |
Returns: object|null - Band descriptor { id, min, label }, or null when the value is missing.
getWeatherSeverityLevels()
Section titled “getWeatherSeverityLevels()”Get every named severity band in ascending order.
const bands = CALENDARIA.api.getWeatherSeverityLevels();// Returns: [{ id: 'none', min: 0, ... }, { id: 'light', min: 1, ... }, ...]Returns: Array<object> - Band descriptors { id, min, label }, ascending by min.
setWeather(presetId, options)
Section titled “setWeather(presetId, options)”Set weather by preset ID.
await CALENDARIA.api.setWeather('thunderstorm', { temperature: 65 });// Set weather for a specific intraday period:await CALENDARIA.api.setWeather('rain', { period: 'morning' });// Set all periods at once:await CALENDARIA.api.setWeather('snow', { allPeriods: true });// Override wind and precipitation on top of the preset:await CALENDARIA.api.setWeather('cloudy', { temperature: 11, wind: { speed: 2, direction: 'SW', forced: false }, precipitation: { type: null, intensity: 0 }});| Parameter | Type | Description |
|---|---|---|
presetId | string | Weather preset ID (e.g., 'clear', 'rain', 'thunderstorm') |
options.temperature | number | Optional temperature value |
options.wind | object | Wind override { speed, direction, forced } (falls back to preset wind when omitted) |
options.precipitation | object | Precipitation override { type, intensity } (falls back to preset precipitation when omitted) |
options.period | string | Specific period to set when intraday is enabled ('night', 'morning', 'afternoon', 'evening') |
options.allPeriods | boolean | Set all periods to this weather when intraday is enabled |
options.zoneId | string | Zone to write to (defaults to the active scene’s zone) |
Wind values: speed is an integer 0-5: calm, light, moderate, strong, severe, extreme. See WIND_SPEEDS in scripts/constants.mjs. direction takes a number in degrees (0 = N, 90 = E, 180 = S, 270 = W), a 16-point compass string ('N', 'NNE', 'NE', …, 'NW', 'NNW'), or null. Strings convert to degrees through COMPASS_DIRECTIONS, so pass a number when you need precise rotation. forced is a boolean that locks the wind against generator inertia.
Precipitation values: type is null, 'drizzle', 'rain', 'snow', 'sleet', or 'hail'. intensity is a number in the range 0-1.
Returns: Promise<object> - The set weather.
setCustomWeather(weatherData)
Section titled “setCustomWeather(weatherData)”Set custom weather with arbitrary values.
await CALENDARIA.api.setCustomWeather({ label: 'Magical Storm', icon: 'fas fa-bolt', color: '#9b59b6', description: 'Arcane lightning crackles overhead', temperature: 45});| Parameter | Type | Description |
|---|---|---|
weatherData.label | string | Display label |
weatherData.icon | string | Font Awesome icon class |
weatherData.color | string | Display color |
weatherData.description | string | Description text |
weatherData.temperature | number | Temperature value |
weatherData.zoneId | string | Zone to write to (defaults to the active scene’s zone) |
weatherData.period | string | Specific period to set when intraday is enabled |
weatherData.allPeriods | boolean | Set all periods to this weather when intraday is enabled |
Returns: Promise<object> - The set weather.
clearWeather()
Section titled “clearWeather()”Clear the current weather.
await CALENDARIA.api.clearWeather();Returns: Promise<void>
getCurrentWeatherPeriod()
Section titled “getCurrentWeatherPeriod()”Get the current intraday weather period based on the world clock.
const period = CALENDARIA.api.getCurrentWeatherPeriod();// Returns: 'night', 'morning', 'afternoon', or 'evening'Returns: string - Current period ID.
getWeatherForPeriod(periodName, zoneId)
Section titled “getWeatherForPeriod(periodName, zoneId)”Get weather for a specific intraday period from the current day.
const weather = CALENDARIA.api.getWeatherForPeriod('morning');// With specific zone:const weather = CALENDARIA.api.getWeatherForPeriod('evening', 'desert');| Parameter | Type | Description |
|---|---|---|
periodName | string | Period ID: 'night', 'morning', 'afternoon', 'evening' |
zoneId | string | Zone ID (defaults to active scene’s zone) |
Returns: object|null - Weather data for the period including its derived severity on a 0-10 scale, or null if intraday is disabled.
generateWeather(options)
Section titled “generateWeather(options)”Generate and set weather from the resolved climate and season.
await CALENDARIA.api.generateWeather();await CALENDARIA.api.generateWeather({ zoneId: 'desert', season: 'Summer' });await CALENDARIA.api.generateWeather({ randomize: true });| Parameter | Type | Description |
|---|---|---|
options.zoneId | string | Zone to generate for (defaults to the active scene’s zone) |
options.season | string | Season name used for zone season overrides (defaults to current season) |
options.randomize | boolean | Use true randomness instead of date-seeded generation |
The climate always comes from the resolved season and zone. There is no climate override parameter.
Returns: Promise<object> - Generated weather.
getWeatherForecast(options)
Section titled “getWeatherForecast(options)”Get a weather forecast for upcoming days.
const forecast = CALENDARIA.api.getWeatherForecast();// With options:const forecast = CALENDARIA.api.getWeatherForecast({ zoneId: 'desert', accuracy: 100 });// Returns: [{ year, month, dayOfMonth, preset, temperature, wind, precipitation, isVaried }, ...]| Parameter | Type | Description |
|---|---|---|
options.zoneId | string | Zone to get forecast for (defaults to active scene’s zone) |
options.accuracy | number | Override forecast accuracy (0 to 100). GMs default to 100 |
options.days | number | Number of days, capped at the Forecast Days setting (defaults to that setting) |
options.start | object | Internal date {year, month, dayOfMonth} to forecast from, defaulting to now |
options.playerView | boolean | Return the entries a player would receive |
Returns: object[] - Array of forecast entries. Forecast entries carry internal date fields, unlike the rest of the API: month and dayOfMonth are 0-indexed and there is no day key. preset is the full preset object with id, label, icon, color, category, description, and darknessPenalty, not a preset ID. isVaried records whether variance was applied. Only GM users get a periods property; other users receive entries without the period breakdown. A GM caller passing playerView gets the period breakdown stripped and forecast accuracy variance applied.
Permission: Requires viewWeatherForecast permission for non-GM users.
getWeatherForDate(year, month, day, zoneId)
Section titled “getWeatherForDate(year, month, day, zoneId)”Get recorded weather for a specific historical date on the active calendar.
const weather = CALENDARIA.api.getWeatherForDate(1492, 7, 15);// With zone:const weather = CALENDARIA.api.getWeatherForDate(1492, 7, 15, 'desert');| Parameter | Type | Description |
|---|---|---|
year | number | Year |
month | number | Month (1-indexed) |
day | number | Day of month (1-indexed) |
zoneId | string | Optional zone ID (defaults to active zone) |
Returns: object|null - Historical weather entry or null.
getWeatherHistory(options)
Section titled “getWeatherHistory(options)”Get the active calendar’s weather history.
const history = CALENDARIA.api.getWeatherHistory();const year = CALENDARIA.api.getWeatherHistory({ year: 1492, zoneId: 'desert' });| Parameter | Type | Description |
|---|---|---|
options.year | number | Filter to a specific display year |
options.month | number | Filter to a specific month (1-indexed, requires year) |
options.zoneId | string | Zone filter (defaults to the active scene’s zone) |
Returns: object|object[] - The raw nested history object when year is omitted. When year is supplied, a flat array of { year, month, dayOfMonth, ...entry } sorted by date. The flat entries use internal 0-indexed month and dayOfMonth.
clearWeatherHistory(options)
Section titled “clearWeatherHistory(options)”Clear weather history entries. GM only. Clearing affects the active calendar only; other calendars keep their entries. The forecast plan is cleared too by default, otherwise the deleted entries regenerate.
// Clear all historyawait CALENDARIA.api.clearWeatherHistory({ all: true });
// Clear future entries onlyawait CALENDARIA.api.clearWeatherHistory({ future: true });
// Clear a specific yearawait CALENDARIA.api.clearWeatherHistory({ year: 1492 });
// Clear a specific month (1-indexed)await CALENDARIA.api.clearWeatherHistory({ year: 1492, month: 7 });
// Clear without resetting forecast planawait CALENDARIA.api.clearWeatherHistory({ all: true, clearForecast: false });| Parameter | Type | Description |
|---|---|---|
options.all | boolean | Clear all history |
options.future | boolean | Clear entries after the current date |
options.year | number | Clear entries for a specific year |
options.month | number | Clear entries for a specific month (1-indexed, requires year) |
options.clearForecast | boolean | Clear the forecast plan (default: true) |
Returns: Promise<number> - Number of entries removed.
setSceneZoneOverride(scene, zoneId)
Section titled “setSceneZoneOverride(scene, zoneId)”Set a per-scene climate zone override.
await CALENDARIA.managers.WeatherManager.setSceneZoneOverride(game.scenes.active, 'tropical');// Explicitly disable zone (No Zone):await CALENDARIA.managers.WeatherManager.setSceneZoneOverride(game.scenes.active, null);// Clear override (revert to calendar default):await CALENDARIA.managers.WeatherManager.setSceneZoneOverride(game.scenes.active, undefined);Note: This method is on
WeatherManager, not on the public API object.
| Parameter | Type | Description |
|---|---|---|
scene | Scene | Scene document |
zoneId | string|null|undefined | Zone ID, null for “No Zone”, or undefined to clear |
Returns: Promise<void>
isZoneDisabled(scene)
Section titled “isZoneDisabled(scene)”Check whether a scene has explicitly disabled zone-based weather by selecting “No Zone”.
const disabled = CALENDARIA.managers.WeatherManager.isZoneDisabled(game.scenes.active);Note: This method is on
WeatherManager, not on the public API object.
| Parameter | Type | Description |
|---|---|---|
scene | Scene | Scene document |
Returns: boolean - True if the scene has “No Zone” set.
refreshEnvironmentOverrides(presetId)
Section titled “refreshEnvironmentOverrides(presetId)”Invalidate cached environment overrides for a preset. Called internally by the Weather Editor after saving changes.
CALENDARIA.managers.WeatherManager.refreshEnvironmentOverrides('thunderstorm');Note: This method is on
WeatherManager, not on the public API object.
| Parameter | Type | Description |
|---|---|---|
presetId | string | Weather preset ID |
Returns: void
refreshEnvironment()
Section titled “refreshEnvironment()”Recompute scene environment lighting on every synced scene. The recompute covers time-of-day hue, weather blend, climate zone overrides, and moon illumination.
await CALENDARIA.api.refreshEnvironment();Returns: Promise<void> - Resolves once the recompute completes.
resolveDisplayLabel(presetId, fallbackLabel, calendarId, zoneId)
Section titled “resolveDisplayLabel(presetId, fallbackLabel, calendarId, zoneId)”Resolve the display label for a weather preset. A per-zone alias from the Climate Editor wins first, then a name override from the Weather Editor, then the localized fallback label.
const label = CALENDARIA.managers.WeatherManager.resolveDisplayLabel('rain', 'Rain', 'harptos', 'desert');// Returns: "Monsoon" (if aliased) or "Rain" (fallback)Note: This method is on
WeatherManager, not on the public API object.
| Parameter | Type | Description |
|---|---|---|
presetId | string | Weather preset ID |
fallbackLabel | string | Default label if no alias is configured |
calendarId | string | Calendar ID for alias lookup |
zoneId | string | Zone ID for alias lookup |
Returns: string - Resolved display label.
getActiveZone()
Section titled “getActiveZone()”Get the active climate zone.
const zone = CALENDARIA.api.getActiveZone();Returns: object|null - Active zone config.
setActiveZone(zoneId)
Section titled “setActiveZone(zoneId)”Set the active climate zone. Fires the calendaria.weatherChange hook and broadcasts the change to all connected clients.
await CALENDARIA.api.setActiveZone('desert');| Parameter | Type | Description |
|---|---|---|
zoneId | string | Climate zone ID |
Returns: Promise<void>
getWeatherPresets()
Section titled “getWeatherPresets()”Get all available weather presets.
const presets = await CALENDARIA.api.getWeatherPresets();Returns: Promise<object[]> - Array of weather presets.
getCalendarZones()
Section titled “getCalendarZones()”Get all climate zones for the active calendar.
const zones = CALENDARIA.api.getCalendarZones();Returns: object[] - Array of zone configs.
addWeatherPreset(preset)
Section titled “addWeatherPreset(preset)”Add a custom weather preset.
await CALENDARIA.api.addWeatherPreset({ id: 'acid-rain', label: 'Acid Rain', icon: 'fas fa-skull', color: '#2ecc71', description: 'Corrosive precipitation', tempMin: 10, tempMax: 25, wind: { speed: 1, direction: null }, precipitation: { type: 'rain', intensity: 0.6 }, inertiaWeight: 0, hudEffect: 'rain-acid', fxPreset: 'acid-rain', soundFx: 'rain-acid-rain-blood-rain'});| Parameter | Type | Description |
|---|---|---|
preset.id | string | Unique ID |
preset.label | string | Display label |
preset.icon | string | Icon class |
preset.color | string | Display color |
preset.description | string | Description |
preset.tempMin | number | Min temperature (°C) |
preset.tempMax | number | Max temperature (°C) |
preset.wind | object | { speed, direction, forced } |
preset.precipitation | object | { type, intensity } |
preset.inertiaWeight | number | Inertia multiplier (0 to 2) |
preset.hudEffect | string | HUD particle effect |
preset.fxPreset | string | FXMaster effect name |
preset.soundFx | string | Sound loop filename |
Returns: Promise<object|null> - The added preset, or null when the caller lacks the changeWeather permission or the ID already belongs to a built-in or custom preset.
removeWeatherPreset(presetId)
Section titled “removeWeatherPreset(presetId)”Remove a custom weather preset.
await CALENDARIA.api.removeWeatherPreset('acid-rain');| Parameter | Type | Description |
|---|---|---|
presetId | string | Preset ID to remove |
Returns: Promise<boolean> - True if removed.
getTemperature(zoneId)
Section titled “getTemperature(zoneId)”Get the current temperature for a zone.
const temp = CALENDARIA.api.getTemperature();// With specific zone:const temp = CALENDARIA.api.getTemperature('desert');// Returns: 22| Parameter | Type | Description |
|---|---|---|
zoneId | string | Optional zone ID (defaults to active scene’s zone) |
Returns: number|null - Temperature in Celsius, or null when no weather is set. Use formatTemperature() to render it in the world’s temperature unit.
getPreset(presetId)
Section titled “getPreset(presetId)”Get a specific weather preset by ID.
const preset = CALENDARIA.api.getPreset('thunderstorm');// Returns: { id, label, icon, color, description, tempMin, tempMax, wind, precipitation, ... }| Parameter | Type | Description |
|---|---|---|
presetId | string | Preset ID (e.g., 'clear', 'rain', 'thunderstorm') |
Returns: object|null - Preset definition or null if not found.
updateWeatherPreset(presetId, updates)
Section titled “updateWeatherPreset(presetId, updates)”Update an existing custom weather preset. Only custom presets can be updated.
await CALENDARIA.api.updateWeatherPreset('acid-rain', { label: 'Caustic Rain', color: '#e74c3c', tempMax: 30});| Parameter | Type | Description |
|---|---|---|
presetId | string | Preset ID to update |
updates | object | Properties to update (label, icon, color, etc.) |
Returns: Promise<object|null> - Updated preset or null if not found.
formatTemperature(celsius)
Section titled “formatTemperature(celsius)”Format a temperature value for display using the world’s temperature unit setting.
const display = CALENDARIA.api.formatTemperature(22);// Returns: "72°F" (if unit is Fahrenheit) or "22°C" (if unit is Celsius)| Parameter | Type | Description |
|---|---|---|
celsius | number | Temperature in Celsius |
Returns: string - Formatted temperature string.
playWeatherSound(src, options)
Section titled “playWeatherSound(src, options)”Play a standalone weather sound effect with any Foundry audio path.
await CALENDARIA.api.playWeatherSound('sounds/rain-heavy.ogg');| Parameter | Type | Description |
|---|---|---|
src | string | Foundry audio file path |
options.volume | number | Volume 0-1 (defaults to the Weather Sound Volume setting) |
options.fade | number | Fade-in duration in ms (default: 2000) |
options.loop | boolean | Loop playback (default: true) |
options.context | object | Audio context override (default: game.audio.environment) |
Returns: Promise<boolean> - True if playback started. Returns false when weather sounds are disabled globally or muted for the current scene.
stopWeatherSound(options)
Section titled “stopWeatherSound(options)”Stop the currently playing weather sound with fade-out.
await CALENDARIA.api.stopWeatherSound();await CALENDARIA.api.stopWeatherSound({ fade: 500 });| Parameter | Type | Description |
|---|---|---|
options.fade | number | Fade-out duration in ms (default: 2000) |
Returns: Promise<boolean> - True if a sound was stopped.
playWeatherFX(presetName, options)
Section titled “playWeatherFX(presetName, options)”Play an FXMaster weather preset. Playback is exclusive: starting one preset stops any other. Requires the FXMaster module.
await CALENDARIA.api.playWeatherFX('rain');await CALENDARIA.api.playWeatherFX('snow', { density: 'heavy' });| Parameter | Type | Description |
|---|---|---|
presetName | string | FXMaster preset name (e.g., 'rain', 'snow', 'fog') |
options.density | string | Particle density |
options.speed | string | Particle speed |
options.color | string | Tint color |
options.direction | string | Cardinal direction (n, ne, e, se, s, sw, w, nw) |
options.topDown | boolean | Top-down particle view |
options.belowTokens | boolean | Render below token layer |
Returns: Promise<boolean> - True if FX started.
stopWeatherFX()
Section titled “stopWeatherFX()”Stop all active FXMaster weather effects. Requires the FXMaster module.
await CALENDARIA.api.stopWeatherFX();Returns: Promise<boolean> - True if effects were stopped.
getClimateZoneTemplates()
Section titled “getClimateZoneTemplates()”Get all climate zone templates.
const templates = CALENDARIA.api.getClimateZoneTemplates();// Returns array of template objectsReturns: Array<object> - Climate zone templates with id, name, temperatures, and weather weights.
createClimateZone(zoneConfig)
Section titled “createClimateZone(zoneConfig)”Create a new climate zone on the active calendar. GM only.
// Minimal: name onlyconst zone = await CALENDARIA.api.createClimateZone({ name: 'Frozen Wastes' });
// Full configconst zone = await CALENDARIA.api.createClimateZone({ name: 'Frozen Wastes', id: 'frozen-wastes', description: 'A harsh frozen climate zone', temperatures: { Winter: { min: -40, max: -10 }, Summer: { min: -20, max: 5 } }, presets: [], seasonOverrides: {}, windSpeedRange: { min: 2, max: 5 }, windDirections: { N: 30, NE: 20, E: 10 }, brightnessMultiplier: 0.8, environmentBase: { hue: 200, intensity: 0.3, luminosity: 0, saturation: -0.2, shadows: 0.5 }, environmentDark: { hue: 240, intensity: 0.5, luminosity: -0.5, saturation: -0.3, shadows: 0.8 }, shortestDay: 6, longestDay: 18, colorShift: { dawn: 30, dusk: 280, night: 240, transitionDuration: 1 }});| Parameter | Type | Required | Description |
|---|---|---|---|
name | string | Yes | Zone display name |
id | string | No | Zone ID (auto-generated from name if omitted). Must be unique |
description | string | No | Zone description text |
temperatures | object | No | Temperature ranges keyed by season name ({ 'Winter': { min, max } }). Defaults to { _default: { min: 10, max: 22 } } |
presets | Array|object | No | Weather preset configurations |
seasonOverrides | object | No | Per-season overrides |
windSpeedRange | object | No | Wind speed range ({ min, max }, tiers 0-5) |
windDirections | object | No | Wind direction weights by cardinal direction |
brightnessMultiplier | number | No | Scene darkness scaling (default: 1.0) |
environmentBase | object | No | Base (day) lighting overrides (hue, intensity, luminosity, saturation, shadows) |
environmentDark | object | No | Dark (night) lighting overrides |
shortestDay | number | No | Manual shortest day hours override |
longestDay | number | No | Manual longest day hours override |
colorShift | object | No | Time-of-day color shift settings (dawn/dusk/night hue, transition duration) |
Returns: Promise<object|null> - The created zone object, or null on failure.
getWeatherProbabilities(options)
Section titled “getWeatherProbabilities(options)”Get the weather probability breakdown for a zone and season.
const data = CALENDARIA.api.getWeatherProbabilities();const data = CALENDARIA.api.getWeatherProbabilities({ season: 'Winter' });const data = CALENDARIA.api.getWeatherProbabilities({ zoneId: 'arctic', season: 'Summer' });| Parameter | Type | Description |
|---|---|---|
zoneId | string | Zone ID (defaults to active zone) |
season | string | Season name (defaults to current season) |
Returns: object with:
zone-{ id, name }of the resolved zoneseason- Localized season nameentries- Array of{ id, label, icon, color, weight, percent }sorted by percent descendingtempRange-{ min, max }in Celsius
openWeatherProbabilities(options)
Section titled “openWeatherProbabilities(options)”Open the Weather Probability dialog.
CALENDARIA.api.openWeatherProbabilities();CALENDARIA.api.openWeatherProbabilities({ season: 'Winter' });| Parameter | Type | Description |
|---|---|---|
zoneId | string | Initial zone ID |
season | string | Initial season name |
Returns: The dialog instance.
isBundledCalendar(calendarId)
Section titled “isBundledCalendar(calendarId)”Check whether a calendar is one of the bundled calendars.
const isBundled = CALENDARIA.api.isBundledCalendar('harptos');// Returns: trueconst isBundled = CALENDARIA.api.isBundledCalendar('custom-mycal');// Returns: false| Parameter | Type | Description |
|---|---|---|
calendarId | string | Calendar ID to check |
Returns: boolean - True if bundled calendar.
Multiplayer & permissions
Section titled “Multiplayer & permissions”isPrimaryGM()
Section titled “isPrimaryGM()”Check whether the current user is the primary GM responsible for time saves and sync. The result mirrors the primary GM resolved by 3DS:ATLAS, which honors the ATLAS Primary GM setting and falls back to Foundry’s active GM.
const isPrimary = CALENDARIA.api.isPrimaryGM();Returns: boolean
canModifyTime()
Section titled “canModifyTime()”Check whether the current user can modify time.
const canModify = CALENDARIA.api.canModifyTime();Returns: boolean
canManageNotes()
Section titled “canManageNotes()”Check whether the current user can create/edit notes.
const canManage = CALENDARIA.api.canManageNotes();Returns: boolean
Permissions
Section titled “Permissions”Permission checks live on the CALENDARIA.permissions namespace. See Permissions for the full permission list and defaults.
The namespace carries one boolean check per view permission. Alongside the checks documented below it exposes canViewChronicle(), canViewHUD(), canViewNotes(), canViewStopwatch(), and canViewSunDial(), each returning true when the current user may see that application.
hasPermission(permission)
Section titled “hasPermission(permission)”Check whether the current user has a specific permission.
const canChange = CALENDARIA.permissions.hasPermission('changeDateTime');| Parameter | Type | Description |
|---|---|---|
permission | string | Permission key |
Permission Keys: viewBigCal, viewChronicle, viewHUD, viewMiniCal, viewNotes, viewStopwatch, viewSunDial, viewTimeKeeper, addNotes, deleteNotes, changeDateTime, changeWeather, viewWeatherForecast, changeActiveCalendar, editCalendars
Returns: boolean
canViewBigCal()
Section titled “canViewBigCal()”Check whether the current user can view the BigCal.
const canView = CALENDARIA.permissions.canViewBigCal();Returns: boolean
canViewMiniCal()
Section titled “canViewMiniCal()”Check whether the current user can view the MiniCal.
const canView = CALENDARIA.permissions.canViewMiniCal();Returns: boolean
canViewTimeKeeper()
Section titled “canViewTimeKeeper()”Check whether the current user can view the TimeKeeper.
const canView = CALENDARIA.permissions.canViewTimeKeeper();Returns: boolean
canAddNotes()
Section titled “canAddNotes()”Check whether the current user can create notes.
const canAdd = CALENDARIA.permissions.canAddNotes();Returns: boolean
canDeleteNotes()
Section titled “canDeleteNotes()”Check whether the current user can delete notes.
const canDelete = CALENDARIA.permissions.canDeleteNotes();Returns: boolean
canChangeDateTime()
Section titled “canChangeDateTime()”Check whether the current user can modify date/time.
const canChange = CALENDARIA.permissions.canChangeDateTime();Returns: boolean
canChangeWeather()
Section titled “canChangeWeather()”Check whether the current user can change weather.
const canChange = CALENDARIA.permissions.canChangeWeather();Returns: boolean
canViewWeatherForecast()
Section titled “canViewWeatherForecast()”Check whether the current user can view weather forecasts.
const canView = CALENDARIA.permissions.canViewWeatherForecast();Returns: boolean
canChangeActiveCalendar()
Section titled “canChangeActiveCalendar()”Check whether the current user can switch the active calendar.
const canChange = CALENDARIA.permissions.canChangeActiveCalendar();Returns: boolean
canEditCalendars()
Section titled “canEditCalendars()”Check whether the current user can access the Calendar Editor.
const canEdit = CALENDARIA.permissions.canEditCalendars();Returns: boolean
canViewMoons()
Section titled “canViewMoons()”Check whether moons should be shown to the current user. This one reads the Hide Moons From Players setting rather than the permission table, and GMs always get true.
const canView = CALENDARIA.permissions.canViewMoons();Returns: boolean
getUsersWithPermission(permission) / getBlockedActiveUsers(permission)
Section titled “getUsersWithPermission(permission) / getBlockedActiveUsers(permission)”Resolve which users hold a permission, and which currently-connected users do not.
const allowed = CALENDARIA.permissions.getUsersWithPermission('viewBigCal');const blocked = CALENDARIA.permissions.getBlockedActiveUsers('viewBigCal');Returns: User[]
Widgets
Section titled “Widgets”For external module integration. See Widgets for full documentation.
widgetPoints
Section titled “widgetPoints”Available widget insertion points.
const points = CALENDARIA.api.widgetPoints;// { HUD_BUTTONS_LEFT, HUD_BUTTONS_RIGHT, HUD_INDICATORS, HUD_TRAY, MINICAL_SIDEBAR, BIGCAL_ACTIONS }replaceableElements
Section titled “replaceableElements”Built-in indicator elements that can be replaced by widgets.
const elements = CALENDARIA.api.replaceableElements;// { WEATHER_INDICATOR, SEASON_INDICATOR, ERA_INDICATOR, CYCLE_INDICATOR }registerWidget(moduleId, config)
Section titled “registerWidget(moduleId, config)”Register a custom widget.
CALENDARIA.api.registerWidget('my-module', { id: 'my-button', type: 'button', insertAt: 'hud.buttons.right', icon: 'fas fa-star', label: 'My Button', onClick: () => console.log('Clicked!')});| Parameter | Type | Description |
|---|---|---|
moduleId | string | Your module’s ID |
config | object | Widget configuration |
See Widgets for config options.
getRegisteredWidgets(insertPoint)
Section titled “getRegisteredWidgets(insertPoint)”Get widgets registered at a specific point.
const widgets = CALENDARIA.api.getRegisteredWidgets('hud.buttons.right');| Parameter | Type | Description |
|---|---|---|
insertPoint | string | Widget point ID |
Returns: array - Registered widget configs.
getWidgetByReplacement(elementId)
Section titled “getWidgetByReplacement(elementId)”Get widget that replaces a built-in element.
const widget = CALENDARIA.api.getWidgetByReplacement('weather-indicator');| Parameter | Type | Description |
|---|---|---|
elementId | string | Replaceable element ID |
Returns: object|null - Widget config or null.
refreshWidgets()
Section titled “refreshWidgets()”Force all widgets to re-render.
CALENDARIA.api.refreshWidgets();Enum getters
Section titled “Enum getters”Read-only enum constants.
conditionFields
Section titled “conditionFields”Get the condition fields createCondition() recognizes.
const fields = CALENDARIA.api.conditionFields;// { MONTH: 'month', WEEKDAY: 'weekday', SEASON: 'season', MOON_PHASE: 'moonPhase', ... }Returns: object - CONDITION_FIELDS enum (43 fields).
conditionOperators
Section titled “conditionOperators”Get the available condition operators.
const ops = CALENDARIA.api.conditionOperators;// { EQUAL: '==', NOT_EQUAL: '!=', GREATER: '>', LESS: '<', MODULO: '%', DAYS_AGO: 'daysAgo', ... }Returns: object - CONDITION_OPERATORS enum (11 operators).
conditionGroupModes
Section titled “conditionGroupModes”Get the available condition group modes.
const modes = CALENDARIA.api.conditionGroupModes;// { AND: 'and', OR: 'or', NAND: 'nand', XOR: 'xor', COUNT: 'count' }Returns: object - CONDITION_GROUP_MODES enum.
displayStyles
Section titled “displayStyles”Get the available note display styles.
const styles = CALENDARIA.api.displayStyles;// { ICON: 'icon', PIP: 'pip', BANNER: 'banner' }Returns: object - DISPLAY_STYLES enum.
noteVisibility
Section titled “noteVisibility”Get the available note visibility levels.
const levels = CALENDARIA.api.noteVisibility;// { VISIBLE: 'visible', HIDDEN: 'hidden', SECRET: 'secret' }Returns: object - NOTE_VISIBILITY enum.
Get all available Calendaria hook name constants. See Hooks for full documentation, parameters, and examples.
const hooks = CALENDARIA.api.hooks;// Use: Hooks.on(hooks.DAY_CHANGE, (data) => { ... });Returns: object - Hook name constants (e.g., DAY_CHANGE, WEATHER_CHANGE, CLOCK_START_STOP).
CONDITION_EVALUATED hook
Section titled “CONDITION_EVALUATED hook”Fires after note condition evaluation via the evaluateNote() API method (unless silent is true).
Hooks.on(CALENDARIA.api.hooks.CONDITION_EVALUATED, (pageId, date, result) => { console.log(`Note ${pageId} on ${date.year}-${date.month}-${date.day}: ${result}`);});| Parameter | Type | Description |
|---|---|---|
pageId | string | Journal entry page ID |
date | object | Date that was evaluated |
result | boolean | Whether the note matched the date |