@ionic/core
Version:
Base components for Ionic
1,089 lines (1,088 loc) • 117 kB
JavaScript
/*!
* (C) Ionic http://ionicframework.com - MIT License
*/
import { Host, h, writeTask } from "@stencil/core";
import { startFocusVisible } from "../../utils/focus-visible";
import { getElementRoot, raf, renderHiddenInput } from "../../utils/helpers";
import { printIonError, printIonWarning } from "../../utils/logging/index";
import { isRTL } from "../../utils/rtl/index";
import { createColorClasses } from "../../utils/theme";
import { caretDownSharp, caretUpSharp, chevronBack, chevronDown, chevronForward } from "ionicons/icons";
import { getIonMode } from "../../global/ionic-global";
import { isSameDay, warnIfValueOutOfBounds, isBefore, isAfter } from "./utils/comparison";
import { generateMonths, getDaysOfMonth, getDaysOfWeek, getToday, getMonthColumnData, getDayColumnData, getYearColumnData, getTimeColumnsData, getCombinedDateColumnData, } from "./utils/data";
import { formatValue, getLocalizedDateTime, getLocalizedTime, getMonthAndYear } from "./utils/format";
import { isLocaleDayPeriodRTL, isMonthFirstLocale, getNumDaysInMonth, getHourCycle } from "./utils/helpers";
import { calculateHourFromAMPM, convertDataToISO, getClosestValidDate, getEndOfWeek, getNextDay, getNextMonth, getNextWeek, getNextYear, getPreviousDay, getPreviousMonth, getPreviousWeek, getPreviousYear, getStartOfWeek, validateParts, } from "./utils/manipulation";
import { clampDate, convertToArrayOfNumbers, getPartsFromCalendarDay, parseAmPm, parseDate, parseMaxParts, parseMinParts, } from "./utils/parse";
import { getCalendarDayState, getHighlightStyles, isDayDisabled, isMonthDisabled, isNextMonthDisabled, isPrevMonthDisabled, } from "./utils/state";
import { checkForPresentationFormatMismatch, warnIfTimeZoneProvided } from "./utils/validate";
/**
* @virtualProp {"ios" | "md"} mode - The mode determines which platform styles to use.
*
* @slot title - The title of the datetime.
* @slot buttons - The buttons in the datetime.
* @slot time-label - The label for the time selector in the datetime.
*
* @part wheel-item - The individual items when using a wheel style layout, or in the
* month/year picker when using a grid style layout.
* @part wheel-item active - The currently selected wheel-item.
*
* @part time-button - The button that opens the time picker when using a grid style
* layout with `presentation="date-time"` or `"time-date"`.
* @part time-button active - The time picker button when the picker is open.
*
* @part month-year-button - The button that opens the month/year picker when
* using a grid style layout.
*
* @part calendar-day - The individual buttons that display a day inside of the datetime
* calendar.
* @part calendar-day active - The currently selected calendar day.
* @part calendar-day today - The calendar day that contains the current day.
* @part calendar-day disabled - The calendar day that is disabled.
*/
export class Datetime {
constructor() {
this.inputId = `ion-dt-${datetimeIds++}`;
this.prevPresentation = null;
this.warnIfIncorrectValueUsage = () => {
const { multiple, value } = this;
if (!multiple && Array.isArray(value)) {
/**
* We do some processing on the `value` array so
* that it looks more like an array when logged to
* the console.
* Example given ['a', 'b']
* Default toString() behavior: a,b
* Custom behavior: ['a', 'b']
*/
printIonWarning(`ion-datetime was passed an array of values, but multiple="false". This is incorrect usage and may result in unexpected behaviors. To dismiss this warning, pass a string to the "value" property when multiple="false".
Value Passed: [${value.map((v) => `'${v}'`).join(', ')}]
`, this.el);
}
};
this.setValue = (value) => {
this.value = value;
this.ionChange.emit({ value });
};
/**
* Returns the DatetimePart interface
* to use when rendering an initial set of
* data. This should be used when rendering an
* interface in an environment where the `value`
* may not be set. This function works
* by returning the first selected date and then
* falling back to defaultParts if no active date
* is selected.
*/
this.getActivePartsWithFallback = () => {
var _a;
const { defaultParts } = this;
return (_a = this.getActivePart()) !== null && _a !== void 0 ? _a : defaultParts;
};
this.getActivePart = () => {
const { activeParts } = this;
return Array.isArray(activeParts) ? activeParts[0] : activeParts;
};
this.closeParentOverlay = (role) => {
const popoverOrModal = this.el.closest('ion-modal, ion-popover');
if (popoverOrModal) {
popoverOrModal.dismiss(undefined, role);
}
};
this.setWorkingParts = (parts) => {
this.workingParts = Object.assign({}, parts);
};
this.setActiveParts = (parts, removeDate = false) => {
/** if the datetime component is in readonly mode,
* allow browsing of the calendar without changing
* the set value
*/
if (this.readonly) {
return;
}
const { multiple, minParts, maxParts, activeParts } = this;
/**
* When setting the active parts, it is possible
* to set invalid data. For example,
* when updating January 31 to February,
* February 31 does not exist. As a result
* we need to validate the active parts and
* ensure that we are only setting valid dates.
* Additionally, we need to update the working parts
* too in the event that the validated parts are different.
*/
const validatedParts = validateParts(parts, minParts, maxParts);
this.setWorkingParts(validatedParts);
if (multiple) {
const activePartsArray = Array.isArray(activeParts) ? activeParts : [activeParts];
if (removeDate) {
this.activeParts = activePartsArray.filter((p) => !isSameDay(p, validatedParts));
}
else {
this.activeParts = [...activePartsArray, validatedParts];
}
}
else {
this.activeParts = Object.assign({}, validatedParts);
}
const hasSlottedButtons = this.el.querySelector('[slot="buttons"]') !== null;
if (hasSlottedButtons || this.showDefaultButtons) {
return;
}
this.confirm();
};
this.initializeKeyboardListeners = () => {
const calendarBodyRef = this.calendarBodyRef;
if (!calendarBodyRef) {
return;
}
const root = this.el.shadowRoot;
/**
* Get a reference to the month
* element we are currently viewing.
*/
const currentMonth = calendarBodyRef.querySelector('.calendar-month:nth-of-type(2)');
/**
* When focusing the calendar body, we want to pass focus
* to the working day, but other days should
* only be accessible using the arrow keys. Pressing
* Tab should jump between bodies of selectable content.
*/
const checkCalendarBodyFocus = (ev) => {
var _a;
const record = ev[0];
/**
* If calendar body was already focused
* when this fired or if the calendar body
* if not currently focused, we should not re-focus
* the inner day.
*/
if (((_a = record.oldValue) === null || _a === void 0 ? void 0 : _a.includes('ion-focused')) || !calendarBodyRef.classList.contains('ion-focused')) {
return;
}
this.focusWorkingDay(currentMonth);
};
const mo = new MutationObserver(checkCalendarBodyFocus);
mo.observe(calendarBodyRef, { attributeFilter: ['class'], attributeOldValue: true });
this.destroyKeyboardMO = () => {
mo === null || mo === void 0 ? void 0 : mo.disconnect();
};
/**
* We must use keydown not keyup as we want
* to prevent scrolling when using the arrow keys.
*/
calendarBodyRef.addEventListener('keydown', (ev) => {
const activeElement = root.activeElement;
if (!activeElement || !activeElement.classList.contains('calendar-day')) {
return;
}
const parts = getPartsFromCalendarDay(activeElement);
let partsToFocus;
switch (ev.key) {
case 'ArrowDown':
ev.preventDefault();
partsToFocus = getNextWeek(parts);
break;
case 'ArrowUp':
ev.preventDefault();
partsToFocus = getPreviousWeek(parts);
break;
case 'ArrowRight':
ev.preventDefault();
partsToFocus = getNextDay(parts);
break;
case 'ArrowLeft':
ev.preventDefault();
partsToFocus = getPreviousDay(parts);
break;
case 'Home':
ev.preventDefault();
partsToFocus = getStartOfWeek(parts);
break;
case 'End':
ev.preventDefault();
partsToFocus = getEndOfWeek(parts);
break;
case 'PageUp':
ev.preventDefault();
partsToFocus = ev.shiftKey ? getPreviousYear(parts) : getPreviousMonth(parts);
break;
case 'PageDown':
ev.preventDefault();
partsToFocus = ev.shiftKey ? getNextYear(parts) : getNextMonth(parts);
break;
/**
* Do not preventDefault here
* as we do not want to override other
* browser defaults such as pressing Enter/Space
* to select a day.
*/
default:
return;
}
/**
* If the day we want to move focus to is
* disabled, do not do anything.
*/
if (isDayDisabled(partsToFocus, this.minParts, this.maxParts)) {
return;
}
this.setWorkingParts(Object.assign(Object.assign({}, this.workingParts), partsToFocus));
/**
* Give view a chance to re-render
* then move focus to the new working day
*/
requestAnimationFrame(() => this.focusWorkingDay(currentMonth));
});
};
this.focusWorkingDay = (currentMonth) => {
/**
* Get the number of padding days so
* we know how much to offset our next selector by
* to grab the correct calendar-day element.
*/
const padding = currentMonth.querySelectorAll('.calendar-day-padding');
const { day } = this.workingParts;
if (day === null) {
return;
}
/**
* Get the calendar day element
* and focus it.
*/
const dayEl = currentMonth.querySelector(`.calendar-day-wrapper:nth-of-type(${padding.length + day}) .calendar-day`);
if (dayEl) {
dayEl.focus();
}
};
this.processMinParts = () => {
const { min, defaultParts } = this;
if (min === undefined) {
this.minParts = undefined;
return;
}
this.minParts = parseMinParts(min, defaultParts);
};
this.processMaxParts = () => {
const { max, defaultParts } = this;
if (max === undefined) {
this.maxParts = undefined;
return;
}
this.maxParts = parseMaxParts(max, defaultParts);
};
this.initializeCalendarListener = () => {
const calendarBodyRef = this.calendarBodyRef;
if (!calendarBodyRef) {
return;
}
/**
* For performance reasons, we only render 3
* months at a time: The current month, the previous
* month, and the next month. We have a scroll listener
* on the calendar body to append/prepend new months.
*
* We can do this because Stencil is smart enough to not
* re-create the .calendar-month containers, but rather
* update the content within those containers.
*
* As an added bonus, WebKit has some troubles with
* scroll-snap-stop: always, so not rendering all of
* the months in a row allows us to mostly sidestep
* that issue.
*/
const months = calendarBodyRef.querySelectorAll('.calendar-month');
const startMonth = months[0];
const workingMonth = months[1];
const endMonth = months[2];
const mode = getIonMode(this);
const needsiOSRubberBandFix = mode === 'ios' && typeof navigator !== 'undefined' && navigator.maxTouchPoints > 1;
/**
* Before setting up the scroll listener,
* scroll the middle month into view.
* scrollIntoView() will scroll entire page
* if element is not in viewport. Use scrollLeft instead.
*/
writeTask(() => {
calendarBodyRef.scrollLeft = startMonth.clientWidth * (isRTL(this.el) ? -1 : 1);
const getChangedMonth = (parts) => {
const box = calendarBodyRef.getBoundingClientRect();
/**
* If the current scroll position is all the way to the left
* then we have scrolled to the previous month.
* Otherwise, assume that we have scrolled to the next
* month. We have a tolerance of 2px to account for
* sub pixel rendering.
*
* Check below the next line ensures that we did not
* swipe and abort (i.e. we swiped but we are still on the current month).
*/
const condition = isRTL(this.el) ? calendarBodyRef.scrollLeft >= -2 : calendarBodyRef.scrollLeft <= 2;
const month = condition ? startMonth : endMonth;
/**
* The edge of the month must be lined up with
* the edge of the calendar body in order for
* the component to update. Otherwise, it
* may be the case that the user has paused their
* swipe or the browser has not finished snapping yet.
* Rather than check if the x values are equal,
* we give it a tolerance of 2px to account for
* sub pixel rendering.
*/
const monthBox = month.getBoundingClientRect();
if (Math.abs(monthBox.x - box.x) > 2)
return;
/**
* If we're force-rendering a month, assume we've
* scrolled to that and return it.
*
* If forceRenderDate is ever used in a context where the
* forced month is not immediately auto-scrolled to, this
* should be updated to also check whether `month` has the
* same month and year as the forced date.
*/
const { forceRenderDate } = this;
if (forceRenderDate !== undefined) {
return { month: forceRenderDate.month, year: forceRenderDate.year, day: forceRenderDate.day };
}
/**
* From here, we can determine if the start
* month or the end month was scrolled into view.
* If no month was changed, then we can return from
* the scroll callback early.
*/
if (month === startMonth) {
return getPreviousMonth(parts);
}
else if (month === endMonth) {
return getNextMonth(parts);
}
else {
return;
}
};
const updateActiveMonth = () => {
if (needsiOSRubberBandFix) {
calendarBodyRef.style.removeProperty('pointer-events');
appliediOSRubberBandFix = false;
}
/**
* If the month did not change
* then we can return early.
*/
const newDate = getChangedMonth(this.workingParts);
if (!newDate)
return;
const { month, day, year } = newDate;
if (isMonthDisabled({ month, year, day: null }, {
minParts: Object.assign(Object.assign({}, this.minParts), { day: null }),
maxParts: Object.assign(Object.assign({}, this.maxParts), { day: null }),
})) {
return;
}
/**
* Prevent scrolling for other browsers
* to give the DOM time to update and the container
* time to properly snap.
*/
calendarBodyRef.style.setProperty('overflow', 'hidden');
/**
* Use a writeTask here to ensure
* that the state is updated and the
* correct month is scrolled into view
* in the same frame. This is not
* typically a problem on newer devices
* but older/slower device may have a flicker
* if we did not do this.
*/
writeTask(() => {
this.setWorkingParts(Object.assign(Object.assign({}, this.workingParts), { month, day: day, year }));
calendarBodyRef.scrollLeft = workingMonth.clientWidth * (isRTL(this.el) ? -1 : 1);
calendarBodyRef.style.removeProperty('overflow');
if (this.resolveForceDateScrolling) {
this.resolveForceDateScrolling();
}
});
};
/**
* When the container finishes scrolling we
* need to update the DOM with the selected month.
*/
let scrollTimeout;
/**
* We do not want to attempt to set pointer-events
* multiple times within a single swipe gesture as
* that adds unnecessary work to the main thread.
*/
let appliediOSRubberBandFix = false;
const scrollCallback = () => {
if (scrollTimeout) {
clearTimeout(scrollTimeout);
}
/**
* On iOS it is possible to quickly rubber band
* the scroll area before the scroll timeout has fired.
* This results in users reaching the end of the scrollable
* container before the DOM has updated.
* By setting `pointer-events: none` we can ensure that
* subsequent swipes do not happen while the container
* is snapping.
*/
if (!appliediOSRubberBandFix && needsiOSRubberBandFix) {
calendarBodyRef.style.setProperty('pointer-events', 'none');
appliediOSRubberBandFix = true;
}
// Wait ~3 frames
scrollTimeout = setTimeout(updateActiveMonth, 50);
};
calendarBodyRef.addEventListener('scroll', scrollCallback);
this.destroyCalendarListener = () => {
calendarBodyRef.removeEventListener('scroll', scrollCallback);
};
});
};
/**
* Clean up all listeners except for the overlay
* listener. This is so that we can re-create the listeners
* if the datetime has been hidden/presented by a modal or popover.
*/
this.destroyInteractionListeners = () => {
const { destroyCalendarListener, destroyKeyboardMO } = this;
if (destroyCalendarListener !== undefined) {
destroyCalendarListener();
}
if (destroyKeyboardMO !== undefined) {
destroyKeyboardMO();
}
};
this.processValue = (value) => {
const hasValue = value !== null && value !== undefined && value !== '' && (!Array.isArray(value) || value.length > 0);
const valueToProcess = hasValue ? parseDate(value) : this.defaultParts;
const { minParts, maxParts, workingParts, el } = this;
this.warnIfIncorrectValueUsage();
/**
* Return early if the value wasn't parsed correctly, such as
* if an improperly formatted date string was provided.
*/
if (!valueToProcess) {
return;
}
/**
* Datetime should only warn of out of bounds values
* if set by the user. If the `value` is undefined,
* we will default to today's date which may be out
* of bounds. In this case, the warning makes it look
* like the developer did something wrong which is
* not true.
*/
if (hasValue) {
warnIfValueOutOfBounds(valueToProcess, minParts, maxParts);
}
/**
* If there are multiple values, pick an arbitrary one to clamp to. This way,
* if the values are across months, we always show at least one of them. Note
* that the values don't necessarily have to be in order.
*/
const singleValue = Array.isArray(valueToProcess) ? valueToProcess[0] : valueToProcess;
const targetValue = clampDate(singleValue, minParts, maxParts);
const { month, day, year, hour, minute } = targetValue;
const ampm = parseAmPm(hour);
/**
* Since `activeParts` indicates a value that
* been explicitly selected either by the
* user or the app, only update `activeParts`
* if the `value` property is set.
*/
if (hasValue) {
if (Array.isArray(valueToProcess)) {
this.activeParts = [...valueToProcess];
}
else {
this.activeParts = {
month,
day,
year,
hour,
minute,
ampm,
};
}
}
else {
/**
* Reset the active parts if the value is not set.
* This will clear the selected calendar day when
* performing a clear action or using the reset() method.
*/
this.activeParts = [];
}
/**
* Only animate if:
* 1. We're using grid style (wheel style pickers should just jump to new value)
* 2. The month and/or year actually changed, and both are defined (otherwise there's nothing to animate to)
* 3. The calendar body is visible (prevents animation when in collapsed datetime-button, for example)
* 4. The month/year picker is not open (since you wouldn't see the animation anyway)
*/
const didChangeMonth = (month !== undefined && month !== workingParts.month) || (year !== undefined && year !== workingParts.year);
const bodyIsVisible = el.classList.contains('datetime-ready');
const { isGridStyle, showMonthAndYear } = this;
let areAllSelectedDatesInSameMonth = true;
if (Array.isArray(valueToProcess)) {
const firstMonth = valueToProcess[0].month;
for (const date of valueToProcess) {
if (date.month !== firstMonth) {
areAllSelectedDatesInSameMonth = false;
break;
}
}
}
/**
* If there is more than one date selected
* and the dates aren't all in the same month,
* then we should neither animate to the date
* nor update the working parts because we do
* not know which date the user wants to view.
*/
if (areAllSelectedDatesInSameMonth) {
if (isGridStyle && didChangeMonth && bodyIsVisible && !showMonthAndYear) {
this.animateToDate(targetValue);
}
else {
/**
* We only need to do this if we didn't just animate to a new month,
* since that calls prevMonth/nextMonth which calls setWorkingParts for us.
*/
this.setWorkingParts({
month,
day,
year,
hour,
minute,
ampm,
});
}
}
};
this.animateToDate = async (targetValue) => {
const { workingParts } = this;
/**
* Tell other render functions that we need to force the
* target month to appear in place of the actual next/prev month.
* Because this is a State variable, a rerender will be triggered
* automatically, updating the rendered months.
*/
this.forceRenderDate = targetValue;
/**
* Flag that we've started scrolling to the forced date.
* The resolve function will be called by the datetime's
* scroll listener when it's done updating everything.
* This is a replacement for making prev/nextMonth async,
* since the logic we're waiting on is in a listener.
*/
const forceDateScrollingPromise = new Promise((resolve) => {
this.resolveForceDateScrolling = resolve;
});
/**
* Animate smoothly to the forced month. This will also update
* workingParts and correct the surrounding months for us.
*/
const targetMonthIsBefore = isBefore(targetValue, workingParts);
targetMonthIsBefore ? this.prevMonth() : this.nextMonth();
await forceDateScrollingPromise;
this.resolveForceDateScrolling = undefined;
this.forceRenderDate = undefined;
};
this.onFocus = () => {
this.ionFocus.emit();
};
this.onBlur = () => {
this.ionBlur.emit();
};
this.hasValue = () => {
return this.value != null;
};
this.nextMonth = () => {
const calendarBodyRef = this.calendarBodyRef;
if (!calendarBodyRef) {
return;
}
const nextMonth = calendarBodyRef.querySelector('.calendar-month:last-of-type');
if (!nextMonth) {
return;
}
const left = nextMonth.offsetWidth * 2;
calendarBodyRef.scrollTo({
top: 0,
left: left * (isRTL(this.el) ? -1 : 1),
behavior: 'smooth',
});
};
this.prevMonth = () => {
const calendarBodyRef = this.calendarBodyRef;
if (!calendarBodyRef) {
return;
}
const prevMonth = calendarBodyRef.querySelector('.calendar-month:first-of-type');
if (!prevMonth) {
return;
}
calendarBodyRef.scrollTo({
top: 0,
left: 0,
behavior: 'smooth',
});
};
this.toggleMonthAndYearView = () => {
this.showMonthAndYear = !this.showMonthAndYear;
};
this.showMonthAndYear = false;
this.activeParts = [];
this.workingParts = {
month: 5,
day: 28,
year: 2021,
hour: 13,
minute: 52,
ampm: 'pm',
};
this.isTimePopoverOpen = false;
this.forceRenderDate = undefined;
this.color = 'primary';
this.name = this.inputId;
this.disabled = false;
this.formatOptions = undefined;
this.readonly = false;
this.isDateEnabled = undefined;
this.min = undefined;
this.max = undefined;
this.presentation = 'date-time';
this.cancelText = 'Cancel';
this.doneText = 'Done';
this.clearText = 'Clear';
this.yearValues = undefined;
this.monthValues = undefined;
this.dayValues = undefined;
this.hourValues = undefined;
this.minuteValues = undefined;
this.locale = 'default';
this.firstDayOfWeek = 0;
this.titleSelectedDatesFormatter = undefined;
this.multiple = false;
this.highlightedDates = undefined;
this.value = undefined;
this.showDefaultTitle = false;
this.showDefaultButtons = false;
this.showClearButton = false;
this.showDefaultTimeLabel = true;
this.hourCycle = undefined;
this.size = 'fixed';
this.preferWheel = false;
}
formatOptionsChanged() {
const { el, formatOptions, presentation } = this;
checkForPresentationFormatMismatch(el, presentation, formatOptions);
warnIfTimeZoneProvided(el, formatOptions);
}
disabledChanged() {
this.emitStyle();
}
minChanged() {
this.processMinParts();
}
maxChanged() {
this.processMaxParts();
}
presentationChanged() {
const { el, formatOptions, presentation } = this;
checkForPresentationFormatMismatch(el, presentation, formatOptions);
}
get isGridStyle() {
const { presentation, preferWheel } = this;
const hasDatePresentation = presentation === 'date' || presentation === 'date-time' || presentation === 'time-date';
return hasDatePresentation && !preferWheel;
}
yearValuesChanged() {
this.parsedYearValues = convertToArrayOfNumbers(this.yearValues);
}
monthValuesChanged() {
this.parsedMonthValues = convertToArrayOfNumbers(this.monthValues);
}
dayValuesChanged() {
this.parsedDayValues = convertToArrayOfNumbers(this.dayValues);
}
hourValuesChanged() {
this.parsedHourValues = convertToArrayOfNumbers(this.hourValues);
}
minuteValuesChanged() {
this.parsedMinuteValues = convertToArrayOfNumbers(this.minuteValues);
}
/**
* Update the datetime value when the value changes
*/
async valueChanged() {
const { value } = this;
if (this.hasValue()) {
this.processValue(value);
}
this.emitStyle();
this.ionValueChange.emit({ value });
}
/**
* Confirms the selected datetime value, updates the
* `value` property, and optionally closes the popover
* or modal that the datetime was presented in.
*/
async confirm(closeOverlay = false) {
const { isCalendarPicker, activeParts, preferWheel, workingParts } = this;
/**
* We only update the value if the presentation is not a calendar picker.
*/
if (activeParts !== undefined || !isCalendarPicker) {
const activePartsIsArray = Array.isArray(activeParts);
if (activePartsIsArray && activeParts.length === 0) {
if (preferWheel) {
/**
* If the datetime is using a wheel picker, but the
* active parts are empty, then the user has confirmed the
* initial value (working parts) presented to them.
*/
this.setValue(convertDataToISO(workingParts));
}
else {
this.setValue(undefined);
}
}
else {
this.setValue(convertDataToISO(activeParts));
}
}
if (closeOverlay) {
this.closeParentOverlay(CONFIRM_ROLE);
}
}
/**
* Resets the internal state of the datetime but does not update the value.
* Passing a valid ISO-8601 string will reset the state of the component to the provided date.
* If no value is provided, the internal state will be reset to the clamped value of the min, max and today.
*/
async reset(startDate) {
this.processValue(startDate);
}
/**
* Emits the ionCancel event and
* optionally closes the popover
* or modal that the datetime was
* presented in.
*/
async cancel(closeOverlay = false) {
this.ionCancel.emit();
if (closeOverlay) {
this.closeParentOverlay(CANCEL_ROLE);
}
}
get isCalendarPicker() {
const { presentation } = this;
return presentation === 'date' || presentation === 'date-time' || presentation === 'time-date';
}
connectedCallback() {
this.clearFocusVisible = startFocusVisible(this.el).destroy;
}
disconnectedCallback() {
if (this.clearFocusVisible) {
this.clearFocusVisible();
this.clearFocusVisible = undefined;
}
}
initializeListeners() {
this.initializeCalendarListener();
this.initializeKeyboardListeners();
}
componentDidLoad() {
const { el, intersectionTrackerRef } = this;
/**
* If a scrollable element is hidden using `display: none`,
* it will not have a scroll height meaning we cannot scroll elements
* into view. As a result, we will need to wait for the datetime to become
* visible if used inside of a modal or a popover otherwise the scrollable
* areas will not have the correct values snapped into place.
*/
const visibleCallback = (entries) => {
const ev = entries[0];
if (!ev.isIntersecting) {
return;
}
this.initializeListeners();
/**
* TODO FW-2793: Datetime needs a frame to ensure that it
* can properly scroll contents into view. As a result
* we hide the scrollable content until after that frame
* so users do not see the content quickly shifting. The downside
* is that the content will pop into view a frame after. Maybe there
* is a better way to handle this?
*/
writeTask(() => {
this.el.classList.add('datetime-ready');
});
};
const visibleIO = new IntersectionObserver(visibleCallback, { threshold: 0.01, root: el });
/**
* Use raf to avoid a race condition between the component loading and
* its display animation starting (such as when shown in a modal). This
* could cause the datetime to start at a visibility of 0, erroneously
* triggering the `hiddenIO` observer below.
*/
raf(() => visibleIO === null || visibleIO === void 0 ? void 0 : visibleIO.observe(intersectionTrackerRef));
/**
* We need to clean up listeners when the datetime is hidden
* in a popover/modal so that we can properly scroll containers
* back into view if they are re-presented. When the datetime is hidden
* the scroll areas have scroll widths/heights of 0px, so any snapping
* we did originally has been lost.
*/
const hiddenCallback = (entries) => {
const ev = entries[0];
if (ev.isIntersecting) {
return;
}
this.destroyInteractionListeners();
/**
* When datetime is hidden, we need to make sure that
* the month/year picker is closed. Otherwise,
* it will be open when the datetime re-appears
* and the scroll area of the calendar grid will be 0.
* As a result, the wrong month will be shown.
*/
this.showMonthAndYear = false;
writeTask(() => {
this.el.classList.remove('datetime-ready');
});
};
const hiddenIO = new IntersectionObserver(hiddenCallback, { threshold: 0, root: el });
raf(() => hiddenIO === null || hiddenIO === void 0 ? void 0 : hiddenIO.observe(intersectionTrackerRef));
/**
* Datetime uses Ionic components that emit
* ionFocus and ionBlur. These events are
* composed meaning they will cross
* the shadow dom boundary. We need to
* stop propagation on these events otherwise
* developers will see 2 ionFocus or 2 ionBlur
* events at a time.
*/
const root = getElementRoot(this.el);
root.addEventListener('ionFocus', (ev) => ev.stopPropagation());
root.addEventListener('ionBlur', (ev) => ev.stopPropagation());
}
/**
* When the presentation is changed, all calendar content is recreated,
* so we need to re-init behavior with the new elements.
*/
componentDidRender() {
const { presentation, prevPresentation, calendarBodyRef, minParts, preferWheel, forceRenderDate } = this;
/**
* TODO(FW-2165)
* Remove this when https://bugs.webkit.org/show_bug.cgi?id=235960 is fixed.
* When using `min`, we add `scroll-snap-align: none`
* to the disabled month so that users cannot scroll to it.
* This triggers a bug in WebKit where the scroll position is reset.
* Since the month change logic is handled by a scroll listener,
* this causes the month to change leading to `scroll-snap-align`
* changing again, thus changing the scroll position again and causing
* an infinite loop.
* This issue only applies to the calendar grid, so we can disable
* it if the calendar grid is not being used.
*/
const hasCalendarGrid = !preferWheel && ['date-time', 'time-date', 'date'].includes(presentation);
if (minParts !== undefined && hasCalendarGrid && calendarBodyRef) {
const workingMonth = calendarBodyRef.querySelector('.calendar-month:nth-of-type(1)');
/**
* We need to make sure the datetime is not in the process
* of scrolling to a new datetime value if the value
* is updated programmatically.
* Otherwise, the datetime will appear to not scroll at all because
* we are resetting the scroll position to the center of the view.
* Prior to the datetime's value being updated programmatically,
* the calendarBodyRef is scrolled such that the middle month is centered
* in the view. The below code updates the scroll position so the middle
* month is also centered in the view. Since the scroll position did not change,
* the scroll callback in this file does not fire,
* and the resolveForceDateScrolling promise never resolves.
*/
if (workingMonth && forceRenderDate === undefined) {
calendarBodyRef.scrollLeft = workingMonth.clientWidth * (isRTL(this.el) ? -1 : 1);
}
}
if (prevPresentation === null) {
this.prevPresentation = presentation;
return;
}
if (presentation === prevPresentation) {
return;
}
this.prevPresentation = presentation;
this.destroyInteractionListeners();
this.initializeListeners();
/**
* The month/year picker from the date interface
* should be closed as it is not available in non-date
* interfaces.
*/
this.showMonthAndYear = false;
raf(() => {
this.ionRender.emit();
});
}
componentWillLoad() {
const { el, formatOptions, highlightedDates, multiple, presentation, preferWheel } = this;
if (multiple) {
if (presentation !== 'date') {
printIonWarning('Multiple date selection is only supported for presentation="date".', el);
}
if (preferWheel) {
printIonWarning('Multiple date selection is not supported with preferWheel="true".', el);
}
}
if (highlightedDates !== undefined) {
if (presentation !== 'date' && presentation !== 'date-time' && presentation !== 'time-date') {
printIonWarning('The highlightedDates property is only supported with the date, date-time, and time-date presentations.', el);
}
if (preferWheel) {
printIonWarning('The highlightedDates property is not supported with preferWheel="true".', el);
}
}
if (formatOptions) {
checkForPresentationFormatMismatch(el, presentation, formatOptions);
warnIfTimeZoneProvided(el, formatOptions);
}
const hourValues = (this.parsedHourValues = convertToArrayOfNumbers(this.hourValues));
const minuteValues = (this.parsedMinuteValues = convertToArrayOfNumbers(this.minuteValues));
const monthValues = (this.parsedMonthValues = convertToArrayOfNumbers(this.monthValues));
const yearValues = (this.parsedYearValues = convertToArrayOfNumbers(this.yearValues));
const dayValues = (this.parsedDayValues = convertToArrayOfNumbers(this.dayValues));
const todayParts = (this.todayParts = parseDate(getToday()));
this.processMinParts();
this.processMaxParts();
this.defaultParts = getClosestValidDate({
refParts: todayParts,
monthValues,
dayValues,
yearValues,
hourValues,
minuteValues,
minParts: this.minParts,
maxParts: this.maxParts,
});
this.processValue(this.value);
this.emitStyle();
}
emitStyle() {
this.ionStyle.emit({
interactive: true,
datetime: true,
'interactive-disabled': this.disabled,
});
}
/**
* Universal render methods
* These are pieces of datetime that
* are rendered independently of presentation.
*/
renderFooter() {
const { disabled, readonly, showDefaultButtons, showClearButton } = this;
/**
* The cancel, clear, and confirm buttons
* should not be interactive if the datetime
* is disabled or readonly.
*/
const isButtonDisabled = disabled || readonly;
const hasSlottedButtons = this.el.querySelector('[slot="buttons"]') !== null;
if (!hasSlottedButtons && !showDefaultButtons && !showClearButton) {
return;
}
const clearButtonClick = () => {
this.reset();
this.setValue(undefined);
};
/**
* By default we render two buttons:
* Cancel - Dismisses the datetime and
* does not update the `value` prop.
* OK - Dismisses the datetime and
* updates the `value` prop.
*/
return (h("div", { class: "datetime-footer" }, h("div", { class: "datetime-buttons" }, h("div", { class: {
['datetime-action-buttons']: true,
['has-clear-button']: this.showClearButton,
} }, h("slot", { name: "buttons" }, h("ion-buttons", null, showDefaultButtons && (h("ion-button", { id: "cancel-button", color: this.color, onClick: () => this.cancel(true), disabled: isButtonDisabled }, this.cancelText)), h("div", { class: "datetime-action-buttons-container" }, showClearButton && (h("ion-button", { id: "clear-button", color: this.color, onClick: () => clearButtonClick(), disabled: isButtonDisabled }, this.clearText)), showDefaultButtons && (h("ion-button", { id: "confirm-button", color: this.color, onClick: () => this.confirm(true), disabled: isButtonDisabled }, this.doneText)))))))));
}
/**
* Wheel picker render methods
*/
renderWheelPicker(forcePresentation = this.presentation) {
/**
* If presentation="time-date" we switch the
* order of the render array here instead of
* manually reordering each date/time picker
* column with CSS. This allows for additional
* flexibility if we need to render subsets
* of the date/time data or do additional ordering
* within the child render functions.
*/
const renderArray = forcePresentation === 'time-date'
? [this.renderTimePickerColumns(forcePresentation), this.renderDatePickerColumns(forcePresentation)]
: [this.renderDatePickerColumns(forcePresentation), this.renderTimePickerColumns(forcePresentation)];
return h("ion-picker", null, renderArray);
}
renderDatePickerColumns(forcePresentation) {
return forcePresentation === 'date-time' || forcePresentation === 'time-date'
? this.renderCombinedDatePickerColumn()
: this.renderIndividualDatePickerColumns(forcePresentation);
}
renderCombinedDatePickerColumn() {
const { defaultParts, disabled, workingParts, locale, minParts, maxParts, todayParts, isDateEnabled } = this;
const activePart = this.getActivePartsWithFallback();
/**
* By default, generate a range of 3 months:
* Previous month, current month, and next month
*/
const monthsToRender = generateMonths(workingParts);
const lastMonth = monthsToRender[monthsToRender.length - 1];
/**
* Ensure that users can select the entire window of dates.
*/
monthsToRender[0].day = 1;
lastMonth.day = getNumDaysInMonth(lastMonth.month, lastMonth.year);
/**
* Narrow the dates rendered based on min/max dates (if any).
* The `min` date is used if the min is after the generated min month.
* The `max` date is used if the max is before the generated max month.
* This ensures that the sliding window always stays at 3 months
* but still allows future dates to be lazily rendered based on any min/max
* constraints.
*/
const min = minParts !== undefined && isAfter(minParts, monthsToRender[0]) ? minParts : monthsToRender[0];
const max = maxParts !== undefined && isBefore(maxParts, lastMonth) ? maxParts : lastMonth;
const result = getCombinedDateColumnData(locale, todayParts, min, max, this.parsedDayValues, this.parsedMonthValues);
let items = result.items;
const parts = result.parts;
if (isDateEnabled) {
items = items.map((itemObject, index) => {
const referenceParts = parts[index];
let disabled;
try {
/**
* The `isDateEnabled` implementation is try-catch wrapped
* to prevent exceptions in the user's function from
* interrupting the calendar rendering.
*/
disabled = !isDateEnabled(convertDataToISO(referenceParts));
}
catch (e) {
printIonError('Exception thrown from provided `isDateEnabled` function. Please check your function and try again.', e);
}
return Object.assign(Object.assign({}, itemObject), { disabled });
});
}
/**
* If we have selected a day already, then default the column
* to that value. Otherwise, set it to the default dat