dile-calendar
Web Component that shows a month calendar to select a date or a range of dates. It is the calendar used inside dile-datepicker, dile-datetimepicker and dile-date-range-picker, and it can also be used on its own, for example inline in a page or in a custom picker.
The names of the months and days and the texts for assistive technologies come from the Intl API of the browser, so the calendar has no external dependencies.
Installation
npm i @dile/utils
Usage
Import the component.
import '@dile/utils/components/datepicker/calendar.js';
Use the component.
<dile-calendar></dile-calendar>
Listen to the selection of the user:
calendar.addEventListener('user-selected-date-changed', (e) => {
console.log(e.detail.selectedDate); // Date
});
Range selection
With selection="range" the calendar selects a range of dates (for a form field with a popup calendar and quick ranges, use dile-date-range-picker):
- The first click (or Enter / Space) sets the start of the range and the second one sets the end. If the second day is before the first one, the dates are swapped. A third click starts a new range.
- While the end is being chosen, the days between the start and the day under the pointer (or the focused day) are shown as a preview.
- The start and the end have their own shape (rounded on their outer side) and bold text, so the range doesn't depend only on color. The days get the
range-start,range-end,in-rangeandrange-previewattributes. - Each day of the selected range says for assistive technologies whether it is the start, the end or inside the range, and a live region announces the selection, for example "Selected range: 3–10 March 2024".
- The days disabled by
disableDatescan be inside a range, but they can't be its start or end.
<dile-calendar selection="range"></dile-calendar>
calendar.addEventListener('user-selected-range-changed', (e) => {
const { start, end } = e.detail; // end is null until the second day is chosen
});
Several months and outside days
By default the calendar shows one month, including the last days of the previous month and the first ones of the next month (the outside days) to fill the weeks. Two options change that:
hideOutsideDaysleaves those cells empty, so the grid only shows the days of its month. The empty cells are hidden from assistive technologies, and the focus never lands on them: moving with the keyboard to a day of another month shows that month.visibleMonthsshows several consecutive months side by side, each one with its title. The outside days are always hidden with more than one month, so no day is shown twice.
<dile-calendar visibleMonths="2" selection="range"></dile-calendar>
<dile-calendar hideOutsideDays></dile-calendar>
With several months:
- Only one day of all the grids is in the tab order. The arrow keys, Page Up / Page Down and Home / End move from one month to the next one, and the visible months only change when the focused day leaves them.
- The previous / next month buttons move the months one by one (the year buttons, twelve months), and they are disabled when the next month would be completely out of
minDate/maxDate. The header shows the first visible month, and the month and year columns change it. goToDate(date)shows the month of the date as the first one. The calendar doesn't show months completely aftermaxDateor beforeminDatewhen it can avoid it: withmaxDatein March and two months, it shows February and March.- The range selection, its preview and its announcements work across the months.
- The calendar doesn't decide the number of months by the screen width: give it room, or let dile-date-range-picker do it.
Localization
The calendar uses its locale property, or the lang attribute of the <html> element, or en-GB when there is none. The built-in texts (navigation buttons, unavailable days, range announcements) are available in English, Spanish, Catalan, French, German, Italian, Dutch, Polish, Romanian, Bulgarian, Czech, Hungarian, Russian, Slovak, Turkish, Ukrainian and Chinese. Change any of them with the messages property:
calendar.messages = {
defaultDisabledDate: 'We are closed that day.',
rangeSelected: 'Your stay: {range}.',
};
The keys are nextMonth, previousMonth, nextFullYear, previousFullYear, defaultDisabledDate, beforeDisabledDate, afterDisabledDate ({date} is the limit date), rangeStart, rangeEnd, inRange, rangeStartSelected ({date}) and rangeSelected ({range}).
Properties
| Property | Type | Default | Description |
|---|---|---|---|
selection |
String |
"single" |
"single" to select one date, "range" to select a range of dates. |
selectedDate |
Date |
undefined |
Selected date in single mode. Only settable from JavaScript. |
rangeStart |
Date |
null |
Start of the range in range mode. Only settable from JavaScript. |
rangeEnd |
Date |
null |
End of the range in range mode (null while it is being chosen). Only settable from JavaScript. |
centralDate |
Date |
today | Day that has the focus and whose month is shown. Without one of its own, the calendar starts on the selected date. It is always moved to an enabled date when the limits change. |
minDate |
Date |
January 1 of year 1 | First selectable date. Empty or invalid values go back to the default. |
maxDate |
Date |
no limit | Last selectable date. |
disableDates |
Function |
() => false |
(date) => boolean, returns true for the days that can't be selected. |
firstDayOfWeek |
Number |
0 |
First day of the week: 0 is Sunday, 1 is Monday... |
weekdayHeaderNotation |
String |
"short" |
Weekday names in the header: "long", "short" or "narrow". |
locale |
String |
<html lang> or en-GB |
Language of the calendar, for example "es-ES". |
minYear |
Number |
current year - 100 | First year of the year column of the month and year selection. |
maxYear |
Number |
current year + 100 | Last year of the year column. |
monthYearAcceptLabel |
String |
"OK" |
Accessible label of the check button that closes the month and year columns. |
messages |
Object |
{} |
Texts that replace the built-in ones (see Localization). |
visibleMonths |
Number |
1 |
Number of consecutive months shown side by side (1 to 12). With more than one, the outside days are hidden. |
hideOutsideDays |
Boolean |
false |
Leaves empty the cells of the days of the previous and next months. |
Methods
- goToNextMonth(), goToPreviousMonth(), goToNextYear(), goToPreviousYear(): show another month, keeping the day when possible and never going out of
minDate/maxDate. - goToDate(date): shows the month of the date (today by default), or of the nearest enabled date. With several visible months, that month is the first one.
- focusDate(date): shows the date and moves the focus to it.
- focusCentralDate(): moves the focus to the
centralDate. - focusSelectedDate(): moves the focus to the selected date (the start of the range in range mode).
- initCentralDate(): goes back to the selected date, or to the initial date, and focuses it.
- isEnabledDate(date): returns
truewhen the day can be selected. - findNearestEnabledDate(date), findNextEnabledDate(date), findPreviousEnabledDate(date): search an enabled date up to 750 days around the date. When there is none, they return the date moved inside
minDate/maxDate. - openMonthYearPicker(column): shows the month and year columns and focuses
'month'or'year'(default). - closeMonthYearPicker(): goes back to the days.
The getters monthYearPickerOpened, focusedDate (the focused day, or null) and visibleMonthDates (the first day of each visible month) are read-only.
Customizing the days
Subclasses can override renderDayContent(day) to add marks to the days (holidays, events...), or renderDay(day) to change the whole cell. day has the date, dayNumber and the flags today, selected, disabled, currentMonth, previousMonth, nextMonth (relative to the month of its grid), hidden (an outside day that is not shown), rangeStart, rangeEnd, inRange and rangePreview. createDay(date, monthDate) receives the month of the grid, and renderMonthGrid(monthDate, index, withTitle) renders the grid of each month.
import { html } from 'lit';
import { DileCalendar } from '@dile/utils/components/datepicker/index.js';
class HolidayCalendar extends DileCalendar {
renderDayContent(day) {
return html`${super.renderDayContent(day)}${isHoliday(day.date) ? html`<span class="holiday">•</span>` : ''}`;
}
}
Events
- user-selected-date-changed: single mode. Dispatched when the user selects a day (not when
selectedDateis set from code).detail:{ selectedDate }. - user-selected-range-changed: range mode. Dispatched when the user selects the start or the end of the range.
detail:{ start, end }, whereendisnullafter the first day.
CSS Custom Properties
The calendar has the --dile-calendar-* custom properties listed in dile-datepicker. In addition, for the range mode:
| Custom property | Description | Default |
|---|---|---|
| --dile-calendar-range-background-color | Background of the days inside the range | --dile-primary-color at 18% or #2563eb at 18% |
| --dile-calendar-range-edge-background-color | Background of the start and end days | --dile-primary-color or #2563eb |
| --dile-calendar-range-edge-text-color | Text color of the start and end days | --dile-on-primary-color or #fff |
| --dile-calendar-range-edge-border-radius | Radius of the outer side of the start and end days | 50% |
| --dile-calendar-range-preview-background-color | Background of the days of the preview | --dile-primary-color at 10% or #2563eb at 10% |
| --dile-calendar-months-gap | Space between the months when several are visible | 1rem |
| --dile-calendar-month-title-font-size | Font size of the title of each month when several are visible | 0.95em |
Accessibility
- The days are a
role="grid"with a single focusable day (tabindex="0"). The arrow keys move by day and week, Page Up / Page Down change the month (with Alt or Shift, the year), Home / End go to the first and last day of the week, and Enter / Space select the day. The focus never goes out ofminDate/maxDate. - Each day has a hidden text with the full date and, when it can't be selected, the reason.
- The selected day, and the days of the selected range, have
aria-pressed="true"; today hasaria-current="date". - In the month and year columns, Enter or Escape go back to the days. Escape only closes the columns (its event doesn't propagate), so a datepicker that contains the calendar stays open.
dile-calendar demos
Single date
Selected: none
<script type="module">
import '@dile/utils/components/datepicker/calendar.js';
const calendar = document.getElementById('singleCalendar');
calendar.addEventListener('user-selected-date-changed', (e) => {
document.getElementById('singleCalendarResult').textContent = e.detail.selectedDate.toDateString();
});
</script>
<dile-calendar id="singleCalendar" firstDayOfWeek="1" style="max-width: 340px;"></dile-calendar>
<p>Selected: <span id="singleCalendarResult">none</span></p>
Range of dates
From today, with Sundays disabled.
Range: none
<script type="module">
const calendar = document.getElementById('rangeCalendar');
calendar.minDate = new Date();
calendar.disableDates = (date) => date.getDay() === 0;
calendar.addEventListener('user-selected-range-changed', (e) => {
const { start, end } = e.detail;
document.getElementById('rangeCalendarResult').textContent = end
? `${start.toDateString()} - ${end.toDateString()}`
: `${start.toDateString()} - choose the end date`;
});
</script>
<dile-calendar id="rangeCalendar" selection="range" firstDayOfWeek="1" style="max-width: 340px;"></dile-calendar>
<p>Range: <span id="rangeCalendarResult">none</span></p>
Two months
<dile-calendar selection="range" visibleMonths="2" firstDayOfWeek="1" style="max-width: 640px;"></dile-calendar>
Without outside days
<dile-calendar hideOutsideDays firstDayOfWeek="1" style="max-width: 340px;"></dile-calendar>
Styled range in another language
<style>
.styled-range {
max-width: 340px;
--dile-calendar-range-edge-background-color: #6d3d6c;
--dile-calendar-range-background-color: #ead7e9;
--dile-calendar-range-edge-border-radius: 8px;
}
</style>
<dile-calendar class="styled-range" selection="range" locale="es-ES" firstDayOfWeek="1" weekdayHeaderNotation="narrow"></dile-calendar>
dile-components