Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
161 changes: 161 additions & 0 deletions docs/assets/js/partials/snippets.js
Original file line number Diff line number Diff line change
Expand Up @@ -657,6 +657,167 @@ export default () => {
}
// js-docs-end calendar-disabled-dates3

// js-docs-start calendar-customize-cells
const myCalendarCustomizeCells = document.getElementById('myCalendarCustomizeCells')
if (myCalendarCustomizeCells) {
// Pricing data caches
const pricingData = {} // For day prices
const monthRangeData = {} // For month min/max ranges
const yearRangeData = {} // For year min/max ranges

// Fetch pricing data for a specific date range and view
const fetchPricingData = async (startDate, endDate, view = 'days', limit = 400) => {
const startDateStr = startDate.toISOString().split('T')[0]
const endDateStr = endDate.toISOString().split('T')[0]

try {
const response = await fetch(`https://apitest.coreui.io/demos/daily-rates.php?start_date=${startDateStr}&end_date=${endDateStr}&view=${view}&limit=${limit}`)
const data = await response.json()

// API now returns object with date keys, merge directly into appropriate cache
switch (view) {
case 'days': {
Object.assign(pricingData, data)
break
}

case 'months': {
Object.assign(monthRangeData, data)
break
}

case 'years': {
Object.assign(yearRangeData, data)
break
}

default: {
break
}
}
} catch (error) {
// eslint-disable-next-line no-console
console.error('Error fetching pricing data:', error)
}
}

// Get min/max prices for a specific month from cached API data
const getMonthPriceRange = (year, month) => {
// Format: YYYY-MM-01
const monthKey = `${year}-${String(month + 1).padStart(2, '0')}-01`
return monthRangeData[monthKey] || null
}

// Get min/max prices for a specific year from cached API data
const getYearPriceRange = year => {
// Format: YYYY-01-01
const yearKey = `${year}-01-01`
return yearRangeData[yearKey] || null
}

// Helper to get date range based on view
const getDateRangeForView = (date, view) => {
switch (view) {
case 'days': {
return {
startDate: new Date(date.getFullYear(), date.getMonth(), 1),
endDate: new Date(date.getFullYear(), date.getMonth() + 2, 0)
}
}

case 'months': {
return {
startDate: new Date(date.getFullYear(), 0, 1),
endDate: new Date(date.getFullYear(), 11, 31)
}
}

case 'years': {
const startYear = Math.floor(date.getFullYear() / 12) * 12
return {
startDate: new Date(startYear, 0, 1),
endDate: new Date(startYear + 11, 11, 31)
}
}

default: {
return null
}
}
}

const myDefaultAllowList = coreui.Calendar.Default.allowList
myDefaultAllowList.div.push('style')

// Initialize calendar with data
const initCalendar = async () => {
const initialDate = new Date(2025, 0, 1)
const dateRange = getDateRangeForView(initialDate, 'days')

// Fetch initial data
await fetchPricingData(dateRange.startDate, dateRange.endDate, 'days')

const calendar = new coreui.Calendar(myCalendarCustomizeCells, {
calendars: 2,
calendarDate: initialDate,
locale: 'en-US',
minDate: new Date(2022, 0, 1),
maxDate: new Date(2025, 11, 31),
range: true,
renderDayCell(date, meta) {
const dateKey = date.toISOString().split('T')[0]
const price = pricingData[dateKey]

return `<div class="py-1">
<div>${date.toLocaleDateString('en-US', { day: '2-digit' })}</div>
<div class="${meta.isSelected ? 'text-reset' : `text-body-tertiary${meta.isInCurrentMonth ? '' : ' opacity-75'}`}" style="font-size: 0.75rem;">${price ? `$${price}` : '-'}</div>
</div>`
},
renderMonthCell(date, meta) {
const priceRange = getMonthPriceRange(date.getFullYear(), date.getMonth())

return `<div class="py-1">
<div>${date.toLocaleDateString('en-US', { month: 'short' })}</div>
<div class="${meta.isSelected ? 'text-reset' : 'text-body-tertiary'}" style="font-size: 0.75rem;">${priceRange ? `$${priceRange.min}-$${priceRange.max}` : '-'}</div>
</div>`
},
renderYearCell(date, meta) {
const priceRange = getYearPriceRange(date.getFullYear())

return `<div class="py-1">
<div>${date.getFullYear()}</div>
<div class="${meta.isSelected ? 'text-reset' : 'text-body-tertiary'}" style="font-size: 0.75rem;">${priceRange ? `$${priceRange.min}-$${priceRange.max}` : '-'}</div>
</div>`
}
})

// Fetch data when date or view changes
const handleDataUpdate = (date, view) => {
const dateRange = getDateRangeForView(date, view)
if (dateRange) {
fetchPricingData(dateRange.startDate, dateRange.endDate, view).then(() => {
calendar.refresh()
})
}
}

// Listen for calendar date changes
myCalendarCustomizeCells.addEventListener('calendarDateChange.coreui.calendar', event => {
handleDataUpdate(event.date, event.view || 'days')
})

// Listen for calendar view changes
myCalendarCustomizeCells.addEventListener('calendarViewChange.coreui.calendar', event => {
if (event.source !== 'cellClick') {
handleDataUpdate(calendar._calendarDate || initialDate, event.view)
}
})
}

initCalendar()
}
// js-docs-end calendar-customize-cells

// -------------------------------
// Date Pickers
// -------------------------------
Expand Down
111 changes: 101 additions & 10 deletions docs/content/components/calendar.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,22 @@ Set the `data-coreui-selection-type` to `month` to enable selection of entire mo
</div>
{{< /example >}}

### Quarters

Set the `data-coreui-selection-type` property to `quarter` to enable quarters range selection.

{{< example stackblitz_pro="true" >}}
<div class="d-flex justify-content-center">
<div
class="border rounded"
data-coreui-locale="en-US"
data-coreui-selection-type="quarter"
data-coreui-start-date="2024Q1"
data-coreui-toggle="calendar"
></div>
</div>
{{< /example >}}

### Years

Set the `data-coreui-selection-type` to `year` to enable years range selection.
Expand Down Expand Up @@ -231,6 +247,66 @@ Example of the Bootstrap Calendar component with Persian locale settings.
</div>
{{< /example >}}

## Custom cell rendering

The Calendar component provides powerful customization options through render functions that allow you to completely control how calendar cells are displayed. These render functions are particularly useful when you need to add custom content, styling, or data to calendar cells.

### Render functions

The component supports four render functions, one for each view type:

- `renderDayCell(date, meta)` - Customize day cells in the days view
- `renderMonthCell(date, meta)` - Customize month cells in the months view
- `renderQuarterCell(date, meta)` - Customize quarter cells in the quarters view
- `renderYearCell(date, meta)` - Customize year cells in the years view

Each render function receives two parameters:

1. `date` - A JavaScript Date object representing the cell's date
2. `meta` - An object containing cell state information:
- `isDisabled` - Whether the cell is disabled
- `isInRange` - Whether the cell is within a selected range (range selection only)
- `isSelected` - Whether the cell is selected
- For `renderDayCell` only:
- `isInCurrentMonth` - Whether the day belongs to the current month
- `isToday` - Whether the day is today

The render functions should return an HTML string that will be displayed inside the cell. The returned HTML is automatically sanitized to prevent XSS attacks.

### Format options

In addition to custom rendering, you can control the display format of calendar elements using format options:

- `dayFormat` - Controls how day numbers are displayed (`'numeric'` or `'2-digit'`)
- `monthFormat` - Controls how month names are displayed (`'long'`, `'narrow'`, `'short'`, `'numeric'`, or `'2-digit'`)
- `yearFormat` - Controls how year numbers are displayed (`'numeric'` or `'2-digit'`)
- `weekdayFormat` - Controls how weekday names are displayed (number for character length, or `'long'`, `'narrow'`, `'short'`)

These format options use the JavaScript `Intl.DateTimeFormat` API and respect the `locale` setting.

### Security considerations

For security reasons, all HTML returned by render functions is automatically sanitized using the built-in sanitizer. You can:

- Disable sanitization by setting `sanitize: false` (not recommended)
- Customize allowed HTML tags and attributes using the `allowList` option
- Provide your own sanitization function using the `sanitizeFn` option

Note that `sanitize`, `sanitizeFn`, and `allowList` options cannot be supplied via data attributes for security reasons.

### Pricing calendar with custom cells

This example demonstrates advanced usage of custom cell rendering to display pricing data across different calendar views. It uses `renderDayCell` to show daily prices, `renderMonthCell` to display monthly price ranges, and `renderYearCell` to show annual price ranges. The data is fetched from an external API and cached for performance.

{{< example stackblitz_pro="true" stackblitz_add_js="true">}}
<div class="d-flex justify-content-center">
<div id="myCalendarCustomizeCells" class="border rounded"></div>
</div>
{{< /example >}}

{{< js-docs name="calendar-customize-cells" file="docs/assets/js/partials/snippets.js" >}}


## Usage

{{< bootstrap-compatibility >}}
Expand Down Expand Up @@ -264,29 +340,43 @@ const calendarList = calendarElementList.map(calendarEl => {
{{< partial "js-data-attributes.md" >}}
{{< /markdown >}}

{{< callout warning >}}
Note that for security reasons the `sanitize`, `sanitizeFn`, and `allowList` options cannot be supplied using data attributes.
{{< /callout >}}

{{< bs-table >}}
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `allowList` | object | [Default value]({{< docsref "/getting-started/javascript#sanitizer" >}}) | Object which contains allowed attributes and tags. |
| `ariaNavNextMonthLabel` | string | `'Next month'` | A string that provides an accessible label for the button that navigates to the next month in the calendar. This label is read by screen readers to describe the action associated with the button. |
| `ariaNavNextYearLabel` | string | `'Next year'` | A string that provides an accessible label for the button that navigates to the next year in the calendar. This label is intended for screen readers to help users understand the button's functionality. |
| `ariaNavPrevMonthLabel` | string | `'Previous month'` | A string that provides an accessible label for the button that navigates to the previous month in the calendar. Screen readers will use this label to explain the purpose of the button. |
| `ariaNavPrevYearLabel` | string | `'Previous year'` | A string that provides an accessible label for the button that navigates to the previous year in the calendar. This label helps screen reader users understand the button's function. |
| `calendarDate` | date, number, string, null | `null` | Default date of the component. |
| `calendars` | number | `2` | The number of calendars that render on desktop devices. |
| `dayFormat` | `'numeric'`, `'2-digit'` | `'numeric'` | Sets the format for days. Accepts a built-in format (`'numeric'` or `'2-digit'`) |
| `disabledDates` | array, function, null | `null` | Specify the list of dates that cannot be selected. |
| `endDate` | date, number, string, null | `null` | Initial selected to date (range). |
| `firstDayOfWeek` | number | `1` | <p>Sets the day of start week.</p> <ul><li>`0` - Sunday</li><li>`1` - Monday</li><li>`2` - Tuesday</li><li>`3` - Wednesday</li><li>`4` - Thursday</li><li>`5` - Friday</li><li>`6` - Saturday</li></ul> |
| `locale` | string | `'default'` | Sets the default locale for components. If not set, it is inherited from the navigator.language. |
| `maxDate` | date, number, string, null | `null` | Max selectable date. |
| `minDate` | date, number, string, null | `null` | Min selectable date. |
| `monthFormat` | `'long'`, `'narrow'`, `'short'`, `'numeric'`, `'2-digit'` | `'short'` | Sets the format for month names. Accepts built-in formats (`'long'`, `'narrow'`, `'short'`, `'numeric'`, `'2-digit'`). |
| `range` | boolean | `false` | Allow range selection |
| `renderDayCell` | function, null | `null` | Custom function to render day cells. Receives `date` and `meta` object (with `isDisabled`, `isInCurrentMonth`, `isInRange`, `isSelected`, `isToday`) as parameters and should return HTML string. |
| `renderMonthCell` | function, null | `null` | Custom function to render month cells. Receives `date` and `meta` object (with `isDisabled`, `isInRange`, `isSelected`) as parameters and should return HTML string. |
| `renderQuarterCell` | function, null | `null` | Custom function to render quarter cells. Receives `date` and `meta` object (with `isDisabled`, `isInRange`, `isSelected`) as parameters and should return HTML string. |
| `renderYearCell` | function, null | `null` | Custom function to render year cells. Receives `date` and `meta` object (with `isDisabled`, `isInRange`, `isSelected`) as parameters and should return HTML string. |
| `sanitize` | boolean | `true` | Enable or disable the sanitization. If activated `renderDayCell`, `renderMonthCell`, `renderQuarterCell`, and `renderYearCell` options will be sanitized. |
| `sanitizeFn` | null, function | `null` | Here you can supply your own sanitize function. This can be useful if you prefer to use a dedicated library to perform sanitization. |
| `selectAdjacementDays` | boolean | `false` | Set whether days in adjacent months shown before or after the current month are selectable. This only applies if the `showAdjacementDays` option is set to true. |
| `selectionType` | `'day'`, `'week'`, `'month'`, `'year'` | `day` | Specify the type of date selection as day, week, month, or year. |
| `selectionType` | `'day'`, `'week'`, `'month'`, `'quarter'`, `'year'` | `day` | Specify the type of date selection as day, week, month, quarter, or year. |
| `showAdjacementDays` | boolean | `true` | Set whether to display dates in adjacent months (non-selectable) at the start and end of the current month. |
| `showWeekNumber` | boolean | `false` | Set whether to display week numbers in the calendar. |
| `startDate` | date, number, string, null | `null` | Initial selected date. |
| `weekdayFormat` | number, 'long', 'narrow', 'short' | `2` | Set length or format of day name. |
| `weekdayFormat` | number, `'long'`, `'narrow'`, `'short'` | `2` | Set length or format of day name. |
| `weekNumbersLabel` | string | `null` | Label displayed over week numbers in the calendar. |
| `yearFormat` | `'numeric'`, `'2-digit'` | `'numeric'` | Sets the format for years. Accepts built-in formats (`'numeric'` or `'2-digit'`) |
{{< /bs-table >}}

### Methods
Expand All @@ -303,14 +393,15 @@ const calendarList = calendarElementList.map(calendarEl => {
### Events

{{< bs-table >}}
| Method | Description |
| --- | --- |
| `calendarDateChange.coreui.calendar` | Callback fired when the calendar date changed. |
| `calendarMouseleave.coreui.calendar` | Callback fired when the cursor leave the calendar. |
| `cellHover.coreui.calendar` | Callback fired when the user hovers over the calendar cell. |
| `endDateChange.coreui.calendar` | Callback fired when the end date changed. |
| `selectEndChange.coreui.calendar` | Callback fired when the selection type changed. |
| `startDateChange.coreui.calendar` | Callback fired when the start date changed. |
| Method | Description | Event detail |
| --- | --- | --- |
| `calendarDateChange.coreui.calendar` | Fired when the calendar date changes. | `{ date: Date, view: 'days' \| 'months' \| 'quarters' \| 'years' }` |
| `calendarViewChange.coreui.calendar` | Fired when the calendar view changes. | `{ view: 'days' \| 'months' \| 'quarters' \| 'years', source: 'cellClick' \| 'navigation' }` |
| `calendarMouseleave.coreui.calendar` | Fired when the cursor leaves the calendar. | — |
| `cellHover.coreui.calendar` | Fired when the user hovers over a calendar cell. | `{ date: Date \| null }` |
| `endDateChange.coreui.calendar` | Fired when the end date changes. | `{ date: Date \| null }` |
| `selectEndChange.coreui.calendar` | Fired when the selection mode changes. | `{ value: boolean }` |
| `startDateChange.coreui.calendar` | Fired when the start date changes. | `{ date: Date \| null }` |
{{< /bs-table >}}

```js
Expand Down
Loading
Loading