logo dile-components dile-components

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):

<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:

<dile-calendar visibleMonths="2" selection="range"></dile-calendar>
<dile-calendar hideOutsideDays></dile-calendar>

With several months:

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

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

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

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>