Socket
Socket
Sign inDemoInstall

@react-stately/datepicker

Package Overview
Dependencies
Maintainers
2
Versions
541
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@react-stately/datepicker - npm Package Compare versions

Comparing version 3.0.0-nightly.3113 to 3.0.0-nightly.3114

dist/ar-AE.main.js

763

dist/main.js

@@ -1,756 +0,31 @@

var $h2qOe$internationalizeddate = require("@internationalized/date");
var $h2qOe$reactstatelyutils = require("@react-stately/utils");
var $h2qOe$react = require("react");
var $aaab7a647e17e1fd$exports = require("./useDatePickerState.main.js");
var $596a1f0f523d6752$exports = require("./useDateFieldState.main.js");
var $7072d26f58deb33b$exports = require("./useDateRangePickerState.main.js");
var $2654e87be0231a69$exports = require("./useTimeFieldState.main.js");
function $parcel$exportWildcard(dest, source) {
Object.keys(source).forEach(function(key) {
if (key === 'default' || key === '__esModule' || dest.hasOwnProperty(key)) {
return;
}
Object.defineProperty(dest, key, {
enumerable: true,
get: function get() {
return source[key];
}
});
});
return dest;
}
function $parcel$export(e, n, v, s) {
Object.defineProperty(e, n, {get: v, set: s, enumerable: true, configurable: true});
}
var $aaab7a647e17e1fd$exports = {};
$parcel$export($aaab7a647e17e1fd$exports, "useDatePickerState", () => $aaab7a647e17e1fd$export$87194bb378cc3ac2);
$parcel$export(module.exports, "useDatePickerState", () => $aaab7a647e17e1fd$exports.useDatePickerState);
$parcel$export(module.exports, "useDateFieldState", () => $596a1f0f523d6752$exports.useDateFieldState);
$parcel$export(module.exports, "useDateRangePickerState", () => $7072d26f58deb33b$exports.useDateRangePickerState);
$parcel$export(module.exports, "useTimeFieldState", () => $2654e87be0231a69$exports.useTimeFieldState);
/*
* Copyright 2020 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
function $50d5d6a623389320$export$eac50920cf2fd59a(value, minValue, maxValue) {
return value != null && (minValue != null && value.compare(minValue) < 0 || maxValue != null && value.compare(maxValue) > 0);
}
const $50d5d6a623389320$var$DEFAULT_FIELD_OPTIONS = {
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: '2-digit',
second: '2-digit'
};
function $50d5d6a623389320$export$7e319ea407e63bc0(fieldOptions, options) {
fieldOptions = {
...$50d5d6a623389320$var$DEFAULT_FIELD_OPTIONS,
...fieldOptions
};
let granularity = options.granularity || 'minute';
let keys = Object.keys(fieldOptions);
var _maxGranularity;
let startIdx = keys.indexOf((_maxGranularity = options.maxGranularity) !== null && _maxGranularity !== void 0 ? _maxGranularity : 'year');
if (startIdx < 0) startIdx = 0;
let endIdx = keys.indexOf(granularity);
if (endIdx < 0) endIdx = 2;
if (startIdx > endIdx) throw new Error('maxGranularity must be greater than granularity');
let opts1 = keys.slice(startIdx, endIdx + 1).reduce((opts, key)=>{
opts[key] = fieldOptions[key];
return opts;
}, {
});
if (options.hourCycle != null) opts1.hour12 = options.hourCycle === 12;
opts1.timeZone = options.timeZone || 'UTC';
let hasTime = granularity === 'hour' || granularity === 'minute' || granularity === 'second';
if (hasTime && options.timeZone && !options.hideTimeZone) opts1.timeZoneName = 'short';
return opts1;
}
function $50d5d6a623389320$export$c5221a78ef73c5e9(placeholderValue) {
if (placeholderValue && 'hour' in placeholderValue) return placeholderValue;
return new $h2qOe$internationalizeddate.Time();
}
function $50d5d6a623389320$export$61a490a80c552550(value, calendar) {
if (value === null) return null;
if (!value) return undefined;
return $h2qOe$internationalizeddate.toCalendar(value, calendar);
}
function $50d5d6a623389320$export$66aa2b09de4b1ea5(placeholderValue, granularity, calendar, timeZone) {
if (placeholderValue) return $50d5d6a623389320$export$61a490a80c552550(placeholderValue, calendar);
let date = $h2qOe$internationalizeddate.toCalendar($h2qOe$internationalizeddate.now(timeZone).set({
hour: 0,
minute: 0,
second: 0,
millisecond: 0
}), calendar);
if (granularity === 'year' || granularity === 'month' || granularity === 'day') return $h2qOe$internationalizeddate.toCalendarDate(date);
if (!timeZone) return $h2qOe$internationalizeddate.toCalendarDateTime(date);
return date;
}
function $50d5d6a623389320$export$2440da353cedad43(v, granularity) {
// Compute default granularity and time zone from the value. If the value becomes null, keep the last values.
let lastValue = $h2qOe$react.useRef(v);
if (v) lastValue.current = v;
v = lastValue.current;
let defaultTimeZone = v && 'timeZone' in v ? v.timeZone : undefined;
granularity = granularity || (v && 'minute' in v ? 'minute' : 'day');
// props.granularity must actually exist in the value if one is provided.
if (v && !(granularity in v)) throw new Error('Invalid granularity ' + granularity + ' for value ' + v.toString());
return [
granularity,
defaultTimeZone
];
}
function $aaab7a647e17e1fd$export$87194bb378cc3ac2(props) {
let [isOpen1, setOpen] = $h2qOe$react.useState(false);
let [value, setValue] = $h2qOe$reactstatelyutils.useControlledState(props.value, props.defaultValue || null, props.onChange);
let v = value || props.placeholderValue;
let [granularity, defaultTimeZone] = $50d5d6a623389320$export$2440da353cedad43(v, props.granularity);
let dateValue = value != null ? value.toDate(defaultTimeZone !== null && defaultTimeZone !== void 0 ? defaultTimeZone : 'UTC') : null;
let hasTime = granularity === 'hour' || granularity === 'minute' || granularity === 'second' || granularity === 'millisecond';
let [selectedDate, setSelectedDate] = $h2qOe$react.useState(null);
let [selectedTime, setSelectedTime] = $h2qOe$react.useState(null);
if (value) {
selectedDate = value;
if ('hour' in value) selectedTime = value;
}
// props.granularity must actually exist in the value if one is provided.
if (v && !(granularity in v)) throw new Error('Invalid granularity ' + granularity + ' for value ' + v.toString());
let commitValue = (date, time)=>{
setValue('timeZone' in time ? time.set($h2qOe$internationalizeddate.toDateFields(date)) : $h2qOe$internationalizeddate.toCalendarDateTime(date, time));
};
// Intercept setValue to make sure the Time section is not changed by date selection in Calendar
let selectDate = (newValue)=>{
if (hasTime) {
if (selectedTime) commitValue(newValue, selectedTime);
else setSelectedDate(newValue);
} else setValue(newValue);
if (!hasTime) setOpen(false);
};
let selectTime = (newValue)=>{
if (selectedDate) commitValue(selectedDate, newValue);
else setSelectedTime(newValue);
};
let validationState = props.validationState || ($50d5d6a623389320$export$eac50920cf2fd59a(value, props.minValue, props.maxValue) ? 'invalid' : null);
return {
value: value,
setValue: setValue,
dateValue: selectedDate,
timeValue: selectedTime,
setDateValue: selectDate,
setTimeValue: selectTime,
granularity: granularity,
isOpen: isOpen1,
setOpen (isOpen) {
// Commit the selected date when the calendar is closed. Use a placeholder time if one wasn't set.
// If only the time was set and not the date, don't commit. The state will be preserved until
// the user opens the popover again.
if (!isOpen && !value && selectedDate && hasTime) commitValue(selectedDate, selectedTime || $50d5d6a623389320$export$c5221a78ef73c5e9(props.placeholderValue));
setOpen(isOpen);
},
validationState: validationState,
formatValue (locale, fieldOptions) {
if (!dateValue) return '';
let formatOptions = $50d5d6a623389320$export$7e319ea407e63bc0(fieldOptions, {
granularity: granularity,
timeZone: defaultTimeZone,
hideTimeZone: props.hideTimeZone,
hourCycle: props.hourCycle
});
let formatter = new $h2qOe$internationalizeddate.DateFormatter(locale, formatOptions);
return formatter.format(dateValue);
}
};
}
var $6d4e641deb83cb9e$exports = {};
$parcel$export($6d4e641deb83cb9e$exports, "useDatePickerFieldState", () => $6d4e641deb83cb9e$export$714a241b39a650d6);
const $6d4e641deb83cb9e$var$EDITABLE_SEGMENTS = {
year: true,
month: true,
day: true,
hour: true,
minute: true,
second: true,
dayPeriod: true,
era: true
};
const $6d4e641deb83cb9e$var$PAGE_STEP = {
year: 5,
month: 2,
day: 7,
hour: 2,
minute: 15,
second: 15
};
// Node seems to convert everything to lowercase...
const $6d4e641deb83cb9e$var$TYPE_MAPPING = {
dayperiod: 'dayPeriod'
};
function $6d4e641deb83cb9e$export$714a241b39a650d6(props) {
let { locale: locale , createCalendar: createCalendar , hideTimeZone: hideTimeZone } = props;
let v1 = props.value || props.defaultValue || props.placeholderValue;
let [granularity, defaultTimeZone] = $50d5d6a623389320$export$2440da353cedad43(v1, props.granularity);
let timeZone = defaultTimeZone || 'UTC';
// props.granularity must actually exist in the value if one is provided.
if (v1 && !(granularity in v1)) throw new Error('Invalid granularity ' + granularity + ' for value ' + v1.toString());
var _maxGranularity;
let formatOpts = $h2qOe$react.useMemo(()=>({
granularity: granularity,
maxGranularity: (_maxGranularity = props.maxGranularity) !== null && _maxGranularity !== void 0 ? _maxGranularity : 'year',
timeZone: defaultTimeZone,
hideTimeZone: hideTimeZone,
hourCycle: props.hourCycle
})
, [
props.maxGranularity,
granularity,
props.hourCycle,
defaultTimeZone,
hideTimeZone
]);
let opts = $h2qOe$react.useMemo(()=>$50d5d6a623389320$export$7e319ea407e63bc0({
}, formatOpts)
, [
formatOpts
]);
let dateFormatter = $h2qOe$react.useMemo(()=>new $h2qOe$internationalizeddate.DateFormatter(locale, opts)
, [
locale,
opts
]);
let resolvedOptions = $h2qOe$react.useMemo(()=>dateFormatter.resolvedOptions()
, [
dateFormatter
]);
let calendar = $h2qOe$react.useMemo(()=>createCalendar(resolvedOptions.calendar)
, [
createCalendar,
resolvedOptions.calendar
]);
// Determine how many editable segments there are for validation purposes.
// The result is cached for performance.
let allSegments = $h2qOe$react.useMemo(()=>dateFormatter.formatToParts(new Date()).filter((seg)=>$6d4e641deb83cb9e$var$EDITABLE_SEGMENTS[seg.type]
).reduce((p, seg)=>(p[seg.type] = true, p)
, {
})
, [
dateFormatter
]);
let [validSegments, setValidSegments] = $h2qOe$react.useState(()=>props.value || props.defaultValue ? {
...allSegments
} : {
}
);
// We keep track of the placeholder date separately in state so that onChange is not called
// until all segments are set. If the value === null (not undefined), then assume the component
// is controlled, so use the placeholder as the value until all segments are entered so it doesn't
// change from uncontrolled to controlled and emit a warning.
let [placeholderDate, setPlaceholderDate] = $h2qOe$react.useState(()=>$50d5d6a623389320$export$66aa2b09de4b1ea5(props.placeholderValue, granularity, calendar, defaultTimeZone)
);
// Reset placeholder when calendar changes
let lastCalendarIdentifier = $h2qOe$react.useRef(calendar.identifier);
$h2qOe$react.useEffect(()=>{
if (calendar.identifier !== lastCalendarIdentifier.current) {
lastCalendarIdentifier.current = calendar.identifier;
setPlaceholderDate((placeholder)=>Object.keys(validSegments).length > 0 ? $h2qOe$internationalizeddate.toCalendar(placeholder, calendar) : $50d5d6a623389320$export$66aa2b09de4b1ea5(props.placeholderValue, granularity, calendar, defaultTimeZone)
);
}
}, [
calendar,
granularity,
validSegments,
defaultTimeZone,
props.placeholderValue
]);
let [value1, setDate] = $h2qOe$reactstatelyutils.useControlledState(props.value, props.defaultValue, props.onChange);
let calendarValue = $h2qOe$react.useMemo(()=>$50d5d6a623389320$export$61a490a80c552550(value1, calendar)
, [
value1,
calendar
]);
// If there is a value prop, and some segments were previously placeholders, mark them all as valid.
if (value1 && Object.keys(validSegments).length < Object.keys(allSegments).length) {
validSegments = {
...allSegments
};
setValidSegments(validSegments);
}
// If the value is set to null and all segments are valid, reset the placeholder.
if (value1 == null && Object.keys(validSegments).length === Object.keys(allSegments).length) {
validSegments = {
};
setValidSegments(validSegments);
setPlaceholderDate($50d5d6a623389320$export$66aa2b09de4b1ea5(props.placeholderValue, granularity, calendar, defaultTimeZone));
}
// If all segments are valid, use the date from state, otherwise use the placeholder date.
let displayValue = calendarValue && Object.keys(validSegments).length >= Object.keys(allSegments).length ? calendarValue : placeholderDate;
let setValue = (newValue)=>{
if (props.isDisabled || props.isReadOnly) return;
if (Object.keys(validSegments).length >= Object.keys(allSegments).length) {
// The display calendar should not have any effect on the emitted value.
// Emit dates in the same calendar as the original value, if any, otherwise gregorian.
newValue = $h2qOe$internationalizeddate.toCalendar(newValue, (v1 === null || v1 === void 0 ? void 0 : v1.calendar) || new $h2qOe$internationalizeddate.GregorianCalendar());
setDate(newValue);
} else setPlaceholderDate(newValue);
};
let dateValue = $h2qOe$react.useMemo(()=>displayValue.toDate(timeZone)
, [
displayValue,
timeZone
]);
let segments = $h2qOe$react.useMemo(()=>dateFormatter.formatToParts(dateValue).map((segment)=>{
let isEditable = $6d4e641deb83cb9e$var$EDITABLE_SEGMENTS[segment.type];
if (segment.type === 'era' && calendar.getEras().length === 1) isEditable = false;
return {
type: $6d4e641deb83cb9e$var$TYPE_MAPPING[segment.type] || segment.type,
text: segment.value,
...$6d4e641deb83cb9e$var$getSegmentLimits(displayValue, segment.type, resolvedOptions),
isPlaceholder: $6d4e641deb83cb9e$var$EDITABLE_SEGMENTS[segment.type] && !validSegments[segment.type],
isEditable: isEditable
};
})
, [
dateValue,
validSegments,
dateFormatter,
resolvedOptions,
displayValue,
calendar
]);
let hasEra = $h2qOe$react.useMemo(()=>segments.some((s)=>s.type === 'era'
)
, [
segments
]);
let markValid = (part)=>{
validSegments[part] = true;
if (part === 'year' && hasEra) validSegments.era = true;
setValidSegments({
...validSegments
});
};
let adjustSegment = (type, amount)=>{
markValid(type);
setValue($6d4e641deb83cb9e$var$addSegment(displayValue, type, amount, resolvedOptions));
};
let validationState = props.validationState || ($50d5d6a623389320$export$eac50920cf2fd59a(calendarValue, props.minValue, props.maxValue) ? 'invalid' : null);
return {
value: calendarValue,
dateValue: dateValue,
setValue: setValue,
segments: segments,
dateFormatter: dateFormatter,
validationState: validationState,
granularity: granularity,
increment (part) {
adjustSegment(part, 1);
},
decrement (part) {
adjustSegment(part, -1);
},
incrementPage (part) {
adjustSegment(part, $6d4e641deb83cb9e$var$PAGE_STEP[part] || 1);
},
decrementPage (part) {
adjustSegment(part, -($6d4e641deb83cb9e$var$PAGE_STEP[part] || 1));
},
setSegment (part, v) {
markValid(part);
setValue($6d4e641deb83cb9e$var$setSegment(displayValue, part, v, resolvedOptions));
},
confirmPlaceholder (part) {
if (props.isDisabled || props.isReadOnly) return;
if (!part) {
// Confirm the rest of the placeholder if any of the segments are valid.
let numValid = Object.keys(validSegments).length;
if (numValid > 0 && numValid < Object.keys(allSegments).length) {
validSegments = {
...allSegments
};
setValidSegments(validSegments);
setValue(displayValue.copy());
}
} else if (!validSegments[part]) {
markValid(part);
setValue(displayValue.copy());
}
},
clearSegment (part) {
delete validSegments[part];
setValidSegments({
...validSegments
});
let placeholder = $50d5d6a623389320$export$66aa2b09de4b1ea5(props.placeholderValue, granularity, calendar, defaultTimeZone);
let value = displayValue;
// Reset day period to default without changing the hour.
if (part === 'dayPeriod' && 'hour' in displayValue && 'hour' in placeholder) {
let isPM = displayValue.hour >= 12;
let shouldBePM = placeholder.hour >= 12;
if (isPM && !shouldBePM) value = displayValue.set({
hour: displayValue.hour - 12
});
else if (!isPM && shouldBePM) value = displayValue.set({
hour: displayValue.hour + 12
});
} else if (part in displayValue) value = displayValue.set({
[part]: placeholder[part]
});
setDate(null);
setValue(value);
},
getFormatOptions (fieldOptions) {
return $50d5d6a623389320$export$7e319ea407e63bc0(fieldOptions, formatOpts);
}
};
}
function $6d4e641deb83cb9e$var$getSegmentLimits(date, type, options) {
switch(type){
case 'era':
{
let eras = date.calendar.getEras();
return {
value: eras.indexOf(date.era),
minValue: 0,
maxValue: eras.length - 1
};
}
case 'year':
return {
value: date.year,
minValue: 1,
maxValue: date.calendar.getYearsInEra(date)
};
case 'month':
return {
value: date.month,
minValue: $h2qOe$internationalizeddate.getMinimumMonthInYear(date),
maxValue: date.calendar.getMonthsInYear(date)
};
case 'day':
return {
value: date.day,
minValue: $h2qOe$internationalizeddate.getMinimumDayInMonth(date),
maxValue: date.calendar.getDaysInMonth(date)
};
}
if ('hour' in date) switch(type){
case 'dayPeriod':
return {
value: date.hour >= 12 ? 12 : 0,
minValue: 0,
maxValue: 12
};
case 'hour':
if (options.hour12) {
let isPM = date.hour >= 12;
return {
value: date.hour,
minValue: isPM ? 12 : 0,
maxValue: isPM ? 23 : 11
};
}
return {
value: date.hour,
minValue: 0,
maxValue: 23
};
case 'minute':
return {
value: date.minute,
minValue: 0,
maxValue: 59
};
case 'second':
return {
value: date.second,
minValue: 0,
maxValue: 59
};
}
return {
};
}
function $6d4e641deb83cb9e$var$addSegment(value, part, amount, options) {
switch(part){
case 'era':
case 'year':
case 'month':
case 'day':
return value.cycle(part, amount, {
round: part === 'year'
});
}
if ('hour' in value) switch(part){
case 'dayPeriod':
{
let hours = value.hour;
let isPM = hours >= 12;
return value.set({
hour: isPM ? hours - 12 : hours + 12
});
}
case 'hour':
case 'minute':
case 'second':
return value.cycle(part, amount, {
round: part !== 'hour',
hourCycle: options.hour12 ? 12 : 24
});
}
}
function $6d4e641deb83cb9e$var$setSegment(value, part, segmentValue, options) {
switch(part){
case 'day':
case 'month':
case 'year':
return value.set({
[part]: segmentValue
});
}
if ('hour' in value) switch(part){
case 'dayPeriod':
{
let hours = value.hour;
let wasPM = hours >= 12;
let isPM = segmentValue >= 12;
if (isPM === wasPM) return value;
return value.set({
hour: wasPM ? hours - 12 : hours + 12
});
}
case 'hour':
// In 12 hour time, ensure that AM/PM does not change
if (options.hour12) {
let hours = value.hour;
let wasPM = hours >= 12;
if (!wasPM && segmentValue === 12) segmentValue = 0;
if (wasPM && segmentValue < 12) segmentValue += 12;
}
// fallthrough
case 'minute':
case 'second':
return value.set({
[part]: segmentValue
});
}
}
var $7072d26f58deb33b$exports = {};
$parcel$export($7072d26f58deb33b$exports, "useDateRangePickerState", () => $7072d26f58deb33b$export$e50a61c1de9f574);
function $7072d26f58deb33b$export$e50a61c1de9f574(props) {
let [isOpen1, setOpen] = $h2qOe$react.useState(false);
let [controlledValue, setControlledValue] = $h2qOe$reactstatelyutils.useControlledState(props.value, props.defaultValue || null, props.onChange);
let [placeholderValue, setPlaceholderValue] = $h2qOe$react.useState(()=>controlledValue || {
start: null,
end: null
}
);
// Reset the placeholder if the value prop is set to null.
if (controlledValue == null && placeholderValue.start && placeholderValue.end) {
placeholderValue = {
start: null,
end: null
};
setPlaceholderValue(placeholderValue);
}
let value1 = controlledValue || placeholderValue;
let valueRef = $h2qOe$react.useRef(value1);
valueRef.current = value1;
let setValue = (value)=>{
valueRef.current = value;
setPlaceholderValue(value);
if ((value === null || value === void 0 ? void 0 : value.start) && value.end) setControlledValue(value);
else setControlledValue(null);
};
let v = (value1 === null || value1 === void 0 ? void 0 : value1.start) || (value1 === null || value1 === void 0 ? void 0 : value1.end) || props.placeholderValue;
let [granularity, defaultTimeZone] = $50d5d6a623389320$export$2440da353cedad43(v, props.granularity);
let hasTime = granularity === 'hour' || granularity === 'minute' || granularity === 'second' || granularity === 'millisecond';
let [dateRange1, setSelectedDateRange] = $h2qOe$react.useState(null);
let [timeRange1, setSelectedTimeRange] = $h2qOe$react.useState(null);
if (value1 && value1.start && value1.end) {
dateRange1 = value1;
if ('hour' in value1.start) timeRange1 = value1;
}
let commitValue = (dateRange, timeRange)=>{
setValue({
start: 'timeZone' in timeRange.start ? timeRange.start.set($h2qOe$internationalizeddate.toDateFields(dateRange.start)) : $h2qOe$internationalizeddate.toCalendarDateTime(dateRange.start, timeRange.start),
end: 'timeZone' in timeRange.end ? timeRange.end.set($h2qOe$internationalizeddate.toDateFields(dateRange.end)) : $h2qOe$internationalizeddate.toCalendarDateTime(dateRange.end, timeRange.end)
});
};
// Intercept setValue to make sure the Time section is not changed by date selection in Calendar
let setDateRange = (range)=>{
if (hasTime) {
if (range.start && range.end && (timeRange1 === null || timeRange1 === void 0 ? void 0 : timeRange1.start) && (timeRange1 === null || timeRange1 === void 0 ? void 0 : timeRange1.end)) commitValue(range, timeRange1);
else setSelectedDateRange(range);
} else if (range.start && range.end) setValue(range);
else setSelectedDateRange(range);
if (!hasTime) setOpen(false);
};
let setTimeRange = (range)=>{
if ((dateRange1 === null || dateRange1 === void 0 ? void 0 : dateRange1.start) && (dateRange1 === null || dateRange1 === void 0 ? void 0 : dateRange1.end) && range.start && range.end) commitValue(dateRange1, range);
else setSelectedTimeRange(range);
};
let validationState = props.validationState || (value1 != null && ($50d5d6a623389320$export$eac50920cf2fd59a(value1.start, props.minValue, props.maxValue) || $50d5d6a623389320$export$eac50920cf2fd59a(value1.end, props.minValue, props.maxValue) || value1.end != null && value1.start != null && value1.end.compare(value1.start) < 0) ? 'invalid' : null);
return {
value: value1,
setValue: setValue,
dateRange: dateRange1,
timeRange: timeRange1,
granularity: granularity,
setDate (part, date) {
setDateRange({
...dateRange1,
[part]: date
});
},
setTime (part, time) {
setTimeRange({
...timeRange1,
[part]: time
});
},
setDateTime (part, dateTime) {
setValue({
...value1,
[part]: dateTime
});
},
setDateRange: setDateRange,
setTimeRange: setTimeRange,
isOpen: isOpen1,
setOpen (isOpen) {
// Commit the selected date range when the calendar is closed. Use a placeholder time if one wasn't set.
// If only the time range was set and not the date range, don't commit. The state will be preserved until
// the user opens the popover again.
if (!isOpen && !((value1 === null || value1 === void 0 ? void 0 : value1.start) && (value1 === null || value1 === void 0 ? void 0 : value1.end)) && (dateRange1 === null || dateRange1 === void 0 ? void 0 : dateRange1.start) && (dateRange1 === null || dateRange1 === void 0 ? void 0 : dateRange1.end) && hasTime) commitValue(dateRange1, {
start: (timeRange1 === null || timeRange1 === void 0 ? void 0 : timeRange1.start) || $50d5d6a623389320$export$c5221a78ef73c5e9(props.placeholderValue),
end: (timeRange1 === null || timeRange1 === void 0 ? void 0 : timeRange1.end) || $50d5d6a623389320$export$c5221a78ef73c5e9(props.placeholderValue)
});
setOpen(isOpen);
},
validationState: validationState,
formatValue (locale, fieldOptions) {
if (!value1 || !value1.start || !value1.end) return '';
let startTimeZone = 'timeZone' in value1.start ? value1.start.timeZone : undefined;
let startGranularity = props.granularity || (value1.start && 'minute' in value1.start ? 'minute' : 'day');
let endTimeZone = 'timeZone' in value1.end ? value1.end.timeZone : undefined;
let endGranularity = props.granularity || (value1.end && 'minute' in value1.end ? 'minute' : 'day');
let startOptions = $50d5d6a623389320$export$7e319ea407e63bc0(fieldOptions, {
granularity: startGranularity,
timeZone: startTimeZone,
hideTimeZone: props.hideTimeZone,
hourCycle: props.hourCycle
});
let startFormatter = new $h2qOe$internationalizeddate.DateFormatter(locale, startOptions);
let endFormatter;
if (startTimeZone === endTimeZone && startGranularity === endGranularity) {
// Use formatRange, as it results in shorter output when some of the fields
// are shared between the start and end dates (e.g. the same month).
// Formatting will fail if the end date is before the start date. Fall back below when that happens.
try {
return startFormatter.formatRange(value1.start.toDate(startTimeZone), value1.end.toDate(endTimeZone));
} catch (e) {
// ignore
}
endFormatter = startFormatter;
} else {
let endOptions = $50d5d6a623389320$export$7e319ea407e63bc0(fieldOptions, {
granularity: endGranularity,
timeZone: endTimeZone,
hideTimeZone: props.hideTimeZone,
hourCycle: props.hourCycle
});
endFormatter = new $h2qOe$internationalizeddate.DateFormatter(locale, endOptions);
}
return `${startFormatter.format(value1.start.toDate(startTimeZone))} – ${endFormatter.format(value1.end.toDate(endTimeZone))}`;
},
confirmPlaceholder () {
// Need to use ref value here because the value can be set in the same tick as
// a blur, which means the component won't have re-rendered yet.
let value = valueRef.current;
if (value && Boolean(value.start) !== Boolean(value.end)) {
let calendar = (value.start || value.end).calendar;
let placeholder = $50d5d6a623389320$export$66aa2b09de4b1ea5(props.placeholderValue, granularity, calendar, defaultTimeZone);
setValue({
start: value.start || placeholder,
end: value.end || placeholder
});
}
}
};
}
var $2654e87be0231a69$exports = {};
$parcel$export($2654e87be0231a69$exports, "useTimeFieldState", () => $2654e87be0231a69$export$fd53cef0cc796101);
function $2654e87be0231a69$export$fd53cef0cc796101(props) {
let { placeholderValue: placeholderValue = new $h2qOe$internationalizeddate.Time() , minValue: minValue , maxValue: maxValue , granularity: granularity } = props;
let [value, setValue] = $h2qOe$reactstatelyutils.useControlledState(props.value, props.defaultValue, props.onChange);
let v = value || placeholderValue;
let day = v && 'day' in v ? v : undefined;
let placeholderDate = $h2qOe$react.useMemo(()=>$2654e87be0231a69$var$convertValue(placeholderValue)
, [
placeholderValue
]);
let minDate = $h2qOe$react.useMemo(()=>$2654e87be0231a69$var$convertValue(minValue, day)
, [
minValue,
day
]);
let maxDate = $h2qOe$react.useMemo(()=>$2654e87be0231a69$var$convertValue(maxValue, day)
, [
maxValue,
day
]);
let dateTime = $h2qOe$react.useMemo(()=>value == null ? null : $2654e87be0231a69$var$convertValue(value)
, [
value
]);
let onChange = (newValue)=>{
setValue(v && 'day' in v ? newValue : newValue && $h2qOe$internationalizeddate.toTime(newValue));
};
return $6d4e641deb83cb9e$export$714a241b39a650d6({
...props,
value: dateTime,
defaultValue: undefined,
minValue: minDate,
maxValue: maxDate,
onChange: onChange,
granularity: granularity || 'minute',
maxGranularity: 'hour',
placeholderValue: placeholderDate
});
}
function $2654e87be0231a69$var$convertValue(value, date = $h2qOe$internationalizeddate.today($h2qOe$internationalizeddate.getLocalTimeZone())) {
if (!value) return null;
if ('day' in value) return value;
return $h2qOe$internationalizeddate.toCalendarDateTime(date, value);
}
$parcel$exportWildcard(module.exports, $aaab7a647e17e1fd$exports);
$parcel$exportWildcard(module.exports, $6d4e641deb83cb9e$exports);
$parcel$exportWildcard(module.exports, $7072d26f58deb33b$exports);
$parcel$exportWildcard(module.exports, $2654e87be0231a69$exports);
//# sourceMappingURL=main.js.map

@@ -1,737 +0,23 @@

import {toDateFields as $7UzoM$toDateFields, toCalendarDateTime as $7UzoM$toCalendarDateTime, DateFormatter as $7UzoM$DateFormatter, Time as $7UzoM$Time, toCalendar as $7UzoM$toCalendar, now as $7UzoM$now, toCalendarDate as $7UzoM$toCalendarDate, GregorianCalendar as $7UzoM$GregorianCalendar, getMinimumMonthInYear as $7UzoM$getMinimumMonthInYear, getMinimumDayInMonth as $7UzoM$getMinimumDayInMonth, toTime as $7UzoM$toTime, today as $7UzoM$today, getLocalTimeZone as $7UzoM$getLocalTimeZone} from "@internationalized/date";
import {useControlledState as $7UzoM$useControlledState} from "@react-stately/utils";
import {useState as $7UzoM$useState, useRef as $7UzoM$useRef, useMemo as $7UzoM$useMemo, useEffect as $7UzoM$useEffect} from "react";
import {useDatePickerState as $ab5bf3f618090389$export$87194bb378cc3ac2} from "./useDatePickerState.module.js";
import {useDateFieldState as $3c0fc76039f1c516$export$60e84778edff6d26} from "./useDateFieldState.module.js";
import {useDateRangePickerState as $93c38a5e28be6249$export$e50a61c1de9f574} from "./useDateRangePickerState.module.js";
import {useTimeFieldState as $eff5d8ee529ac4bb$export$fd53cef0cc796101} from "./useTimeFieldState.module.js";
function $parcel$export(e, n, v, s) {
Object.defineProperty(e, n, {get: v, set: s, enumerable: true, configurable: true});
}
var $ab5bf3f618090389$exports = {};
/*
* Copyright 2020 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
$parcel$export($ab5bf3f618090389$exports, "useDatePickerState", () => $ab5bf3f618090389$export$87194bb378cc3ac2);
function $35a22f14a1f04b11$export$eac50920cf2fd59a(value, minValue, maxValue) {
return value != null && (minValue != null && value.compare(minValue) < 0 || maxValue != null && value.compare(maxValue) > 0);
}
const $35a22f14a1f04b11$var$DEFAULT_FIELD_OPTIONS = {
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: '2-digit',
second: '2-digit'
};
function $35a22f14a1f04b11$export$7e319ea407e63bc0(fieldOptions, options) {
fieldOptions = {
...$35a22f14a1f04b11$var$DEFAULT_FIELD_OPTIONS,
...fieldOptions
};
let granularity = options.granularity || 'minute';
let keys = Object.keys(fieldOptions);
var _maxGranularity;
let startIdx = keys.indexOf((_maxGranularity = options.maxGranularity) !== null && _maxGranularity !== void 0 ? _maxGranularity : 'year');
if (startIdx < 0) startIdx = 0;
let endIdx = keys.indexOf(granularity);
if (endIdx < 0) endIdx = 2;
if (startIdx > endIdx) throw new Error('maxGranularity must be greater than granularity');
let opts1 = keys.slice(startIdx, endIdx + 1).reduce((opts, key)=>{
opts[key] = fieldOptions[key];
return opts;
}, {
});
if (options.hourCycle != null) opts1.hour12 = options.hourCycle === 12;
opts1.timeZone = options.timeZone || 'UTC';
let hasTime = granularity === 'hour' || granularity === 'minute' || granularity === 'second';
if (hasTime && options.timeZone && !options.hideTimeZone) opts1.timeZoneName = 'short';
return opts1;
}
function $35a22f14a1f04b11$export$c5221a78ef73c5e9(placeholderValue) {
if (placeholderValue && 'hour' in placeholderValue) return placeholderValue;
return new $7UzoM$Time();
}
function $35a22f14a1f04b11$export$61a490a80c552550(value, calendar) {
if (value === null) return null;
if (!value) return undefined;
return $7UzoM$toCalendar(value, calendar);
}
function $35a22f14a1f04b11$export$66aa2b09de4b1ea5(placeholderValue, granularity, calendar, timeZone) {
if (placeholderValue) return $35a22f14a1f04b11$export$61a490a80c552550(placeholderValue, calendar);
let date = $7UzoM$toCalendar($7UzoM$now(timeZone).set({
hour: 0,
minute: 0,
second: 0,
millisecond: 0
}), calendar);
if (granularity === 'year' || granularity === 'month' || granularity === 'day') return $7UzoM$toCalendarDate(date);
if (!timeZone) return $7UzoM$toCalendarDateTime(date);
return date;
}
function $35a22f14a1f04b11$export$2440da353cedad43(v, granularity) {
// Compute default granularity and time zone from the value. If the value becomes null, keep the last values.
let lastValue = $7UzoM$useRef(v);
if (v) lastValue.current = v;
v = lastValue.current;
let defaultTimeZone = v && 'timeZone' in v ? v.timeZone : undefined;
granularity = granularity || (v && 'minute' in v ? 'minute' : 'day');
// props.granularity must actually exist in the value if one is provided.
if (v && !(granularity in v)) throw new Error('Invalid granularity ' + granularity + ' for value ' + v.toString());
return [
granularity,
defaultTimeZone
];
}
function $ab5bf3f618090389$export$87194bb378cc3ac2(props) {
let [isOpen1, setOpen] = $7UzoM$useState(false);
let [value, setValue] = $7UzoM$useControlledState(props.value, props.defaultValue || null, props.onChange);
let v = value || props.placeholderValue;
let [granularity, defaultTimeZone] = $35a22f14a1f04b11$export$2440da353cedad43(v, props.granularity);
let dateValue = value != null ? value.toDate(defaultTimeZone !== null && defaultTimeZone !== void 0 ? defaultTimeZone : 'UTC') : null;
let hasTime = granularity === 'hour' || granularity === 'minute' || granularity === 'second' || granularity === 'millisecond';
let [selectedDate, setSelectedDate] = $7UzoM$useState(null);
let [selectedTime, setSelectedTime] = $7UzoM$useState(null);
if (value) {
selectedDate = value;
if ('hour' in value) selectedTime = value;
}
// props.granularity must actually exist in the value if one is provided.
if (v && !(granularity in v)) throw new Error('Invalid granularity ' + granularity + ' for value ' + v.toString());
let commitValue = (date, time)=>{
setValue('timeZone' in time ? time.set($7UzoM$toDateFields(date)) : $7UzoM$toCalendarDateTime(date, time));
};
// Intercept setValue to make sure the Time section is not changed by date selection in Calendar
let selectDate = (newValue)=>{
if (hasTime) {
if (selectedTime) commitValue(newValue, selectedTime);
else setSelectedDate(newValue);
} else setValue(newValue);
if (!hasTime) setOpen(false);
};
let selectTime = (newValue)=>{
if (selectedDate) commitValue(selectedDate, newValue);
else setSelectedTime(newValue);
};
let validationState = props.validationState || ($35a22f14a1f04b11$export$eac50920cf2fd59a(value, props.minValue, props.maxValue) ? 'invalid' : null);
return {
value: value,
setValue: setValue,
dateValue: selectedDate,
timeValue: selectedTime,
setDateValue: selectDate,
setTimeValue: selectTime,
granularity: granularity,
isOpen: isOpen1,
setOpen (isOpen) {
// Commit the selected date when the calendar is closed. Use a placeholder time if one wasn't set.
// If only the time was set and not the date, don't commit. The state will be preserved until
// the user opens the popover again.
if (!isOpen && !value && selectedDate && hasTime) commitValue(selectedDate, selectedTime || $35a22f14a1f04b11$export$c5221a78ef73c5e9(props.placeholderValue));
setOpen(isOpen);
},
validationState: validationState,
formatValue (locale, fieldOptions) {
if (!dateValue) return '';
let formatOptions = $35a22f14a1f04b11$export$7e319ea407e63bc0(fieldOptions, {
granularity: granularity,
timeZone: defaultTimeZone,
hideTimeZone: props.hideTimeZone,
hourCycle: props.hourCycle
});
let formatter = new $7UzoM$DateFormatter(locale, formatOptions);
return formatter.format(dateValue);
}
};
}
var $09e80d602234613d$exports = {};
$parcel$export($09e80d602234613d$exports, "useDatePickerFieldState", () => $09e80d602234613d$export$714a241b39a650d6);
const $09e80d602234613d$var$EDITABLE_SEGMENTS = {
year: true,
month: true,
day: true,
hour: true,
minute: true,
second: true,
dayPeriod: true,
era: true
};
const $09e80d602234613d$var$PAGE_STEP = {
year: 5,
month: 2,
day: 7,
hour: 2,
minute: 15,
second: 15
};
// Node seems to convert everything to lowercase...
const $09e80d602234613d$var$TYPE_MAPPING = {
dayperiod: 'dayPeriod'
};
function $09e80d602234613d$export$714a241b39a650d6(props) {
let { locale: locale , createCalendar: createCalendar , hideTimeZone: hideTimeZone } = props;
let v1 = props.value || props.defaultValue || props.placeholderValue;
let [granularity, defaultTimeZone] = $35a22f14a1f04b11$export$2440da353cedad43(v1, props.granularity);
let timeZone = defaultTimeZone || 'UTC';
// props.granularity must actually exist in the value if one is provided.
if (v1 && !(granularity in v1)) throw new Error('Invalid granularity ' + granularity + ' for value ' + v1.toString());
var _maxGranularity;
let formatOpts = $7UzoM$useMemo(()=>({
granularity: granularity,
maxGranularity: (_maxGranularity = props.maxGranularity) !== null && _maxGranularity !== void 0 ? _maxGranularity : 'year',
timeZone: defaultTimeZone,
hideTimeZone: hideTimeZone,
hourCycle: props.hourCycle
})
, [
props.maxGranularity,
granularity,
props.hourCycle,
defaultTimeZone,
hideTimeZone
]);
let opts = $7UzoM$useMemo(()=>$35a22f14a1f04b11$export$7e319ea407e63bc0({
}, formatOpts)
, [
formatOpts
]);
let dateFormatter = $7UzoM$useMemo(()=>new $7UzoM$DateFormatter(locale, opts)
, [
locale,
opts
]);
let resolvedOptions = $7UzoM$useMemo(()=>dateFormatter.resolvedOptions()
, [
dateFormatter
]);
let calendar = $7UzoM$useMemo(()=>createCalendar(resolvedOptions.calendar)
, [
createCalendar,
resolvedOptions.calendar
]);
// Determine how many editable segments there are for validation purposes.
// The result is cached for performance.
let allSegments = $7UzoM$useMemo(()=>dateFormatter.formatToParts(new Date()).filter((seg)=>$09e80d602234613d$var$EDITABLE_SEGMENTS[seg.type]
).reduce((p, seg)=>(p[seg.type] = true, p)
, {
})
, [
dateFormatter
]);
let [validSegments, setValidSegments] = $7UzoM$useState(()=>props.value || props.defaultValue ? {
...allSegments
} : {
}
);
// We keep track of the placeholder date separately in state so that onChange is not called
// until all segments are set. If the value === null (not undefined), then assume the component
// is controlled, so use the placeholder as the value until all segments are entered so it doesn't
// change from uncontrolled to controlled and emit a warning.
let [placeholderDate, setPlaceholderDate] = $7UzoM$useState(()=>$35a22f14a1f04b11$export$66aa2b09de4b1ea5(props.placeholderValue, granularity, calendar, defaultTimeZone)
);
// Reset placeholder when calendar changes
let lastCalendarIdentifier = $7UzoM$useRef(calendar.identifier);
$7UzoM$useEffect(()=>{
if (calendar.identifier !== lastCalendarIdentifier.current) {
lastCalendarIdentifier.current = calendar.identifier;
setPlaceholderDate((placeholder)=>Object.keys(validSegments).length > 0 ? $7UzoM$toCalendar(placeholder, calendar) : $35a22f14a1f04b11$export$66aa2b09de4b1ea5(props.placeholderValue, granularity, calendar, defaultTimeZone)
);
}
}, [
calendar,
granularity,
validSegments,
defaultTimeZone,
props.placeholderValue
]);
let [value1, setDate] = $7UzoM$useControlledState(props.value, props.defaultValue, props.onChange);
let calendarValue = $7UzoM$useMemo(()=>$35a22f14a1f04b11$export$61a490a80c552550(value1, calendar)
, [
value1,
calendar
]);
// If there is a value prop, and some segments were previously placeholders, mark them all as valid.
if (value1 && Object.keys(validSegments).length < Object.keys(allSegments).length) {
validSegments = {
...allSegments
};
setValidSegments(validSegments);
}
// If the value is set to null and all segments are valid, reset the placeholder.
if (value1 == null && Object.keys(validSegments).length === Object.keys(allSegments).length) {
validSegments = {
};
setValidSegments(validSegments);
setPlaceholderDate($35a22f14a1f04b11$export$66aa2b09de4b1ea5(props.placeholderValue, granularity, calendar, defaultTimeZone));
}
// If all segments are valid, use the date from state, otherwise use the placeholder date.
let displayValue = calendarValue && Object.keys(validSegments).length >= Object.keys(allSegments).length ? calendarValue : placeholderDate;
let setValue = (newValue)=>{
if (props.isDisabled || props.isReadOnly) return;
if (Object.keys(validSegments).length >= Object.keys(allSegments).length) {
// The display calendar should not have any effect on the emitted value.
// Emit dates in the same calendar as the original value, if any, otherwise gregorian.
newValue = $7UzoM$toCalendar(newValue, (v1 === null || v1 === void 0 ? void 0 : v1.calendar) || new $7UzoM$GregorianCalendar());
setDate(newValue);
} else setPlaceholderDate(newValue);
};
let dateValue = $7UzoM$useMemo(()=>displayValue.toDate(timeZone)
, [
displayValue,
timeZone
]);
let segments = $7UzoM$useMemo(()=>dateFormatter.formatToParts(dateValue).map((segment)=>{
let isEditable = $09e80d602234613d$var$EDITABLE_SEGMENTS[segment.type];
if (segment.type === 'era' && calendar.getEras().length === 1) isEditable = false;
return {
type: $09e80d602234613d$var$TYPE_MAPPING[segment.type] || segment.type,
text: segment.value,
...$09e80d602234613d$var$getSegmentLimits(displayValue, segment.type, resolvedOptions),
isPlaceholder: $09e80d602234613d$var$EDITABLE_SEGMENTS[segment.type] && !validSegments[segment.type],
isEditable: isEditable
};
})
, [
dateValue,
validSegments,
dateFormatter,
resolvedOptions,
displayValue,
calendar
]);
let hasEra = $7UzoM$useMemo(()=>segments.some((s)=>s.type === 'era'
)
, [
segments
]);
let markValid = (part)=>{
validSegments[part] = true;
if (part === 'year' && hasEra) validSegments.era = true;
setValidSegments({
...validSegments
});
};
let adjustSegment = (type, amount)=>{
markValid(type);
setValue($09e80d602234613d$var$addSegment(displayValue, type, amount, resolvedOptions));
};
let validationState = props.validationState || ($35a22f14a1f04b11$export$eac50920cf2fd59a(calendarValue, props.minValue, props.maxValue) ? 'invalid' : null);
return {
value: calendarValue,
dateValue: dateValue,
setValue: setValue,
segments: segments,
dateFormatter: dateFormatter,
validationState: validationState,
granularity: granularity,
increment (part) {
adjustSegment(part, 1);
},
decrement (part) {
adjustSegment(part, -1);
},
incrementPage (part) {
adjustSegment(part, $09e80d602234613d$var$PAGE_STEP[part] || 1);
},
decrementPage (part) {
adjustSegment(part, -($09e80d602234613d$var$PAGE_STEP[part] || 1));
},
setSegment (part, v) {
markValid(part);
setValue($09e80d602234613d$var$setSegment(displayValue, part, v, resolvedOptions));
},
confirmPlaceholder (part) {
if (props.isDisabled || props.isReadOnly) return;
if (!part) {
// Confirm the rest of the placeholder if any of the segments are valid.
let numValid = Object.keys(validSegments).length;
if (numValid > 0 && numValid < Object.keys(allSegments).length) {
validSegments = {
...allSegments
};
setValidSegments(validSegments);
setValue(displayValue.copy());
}
} else if (!validSegments[part]) {
markValid(part);
setValue(displayValue.copy());
}
},
clearSegment (part) {
delete validSegments[part];
setValidSegments({
...validSegments
});
let placeholder = $35a22f14a1f04b11$export$66aa2b09de4b1ea5(props.placeholderValue, granularity, calendar, defaultTimeZone);
let value = displayValue;
// Reset day period to default without changing the hour.
if (part === 'dayPeriod' && 'hour' in displayValue && 'hour' in placeholder) {
let isPM = displayValue.hour >= 12;
let shouldBePM = placeholder.hour >= 12;
if (isPM && !shouldBePM) value = displayValue.set({
hour: displayValue.hour - 12
});
else if (!isPM && shouldBePM) value = displayValue.set({
hour: displayValue.hour + 12
});
} else if (part in displayValue) value = displayValue.set({
[part]: placeholder[part]
});
setDate(null);
setValue(value);
},
getFormatOptions (fieldOptions) {
return $35a22f14a1f04b11$export$7e319ea407e63bc0(fieldOptions, formatOpts);
}
};
}
function $09e80d602234613d$var$getSegmentLimits(date, type, options) {
switch(type){
case 'era':
{
let eras = date.calendar.getEras();
return {
value: eras.indexOf(date.era),
minValue: 0,
maxValue: eras.length - 1
};
}
case 'year':
return {
value: date.year,
minValue: 1,
maxValue: date.calendar.getYearsInEra(date)
};
case 'month':
return {
value: date.month,
minValue: $7UzoM$getMinimumMonthInYear(date),
maxValue: date.calendar.getMonthsInYear(date)
};
case 'day':
return {
value: date.day,
minValue: $7UzoM$getMinimumDayInMonth(date),
maxValue: date.calendar.getDaysInMonth(date)
};
}
if ('hour' in date) switch(type){
case 'dayPeriod':
return {
value: date.hour >= 12 ? 12 : 0,
minValue: 0,
maxValue: 12
};
case 'hour':
if (options.hour12) {
let isPM = date.hour >= 12;
return {
value: date.hour,
minValue: isPM ? 12 : 0,
maxValue: isPM ? 23 : 11
};
}
return {
value: date.hour,
minValue: 0,
maxValue: 23
};
case 'minute':
return {
value: date.minute,
minValue: 0,
maxValue: 59
};
case 'second':
return {
value: date.second,
minValue: 0,
maxValue: 59
};
}
return {
};
}
function $09e80d602234613d$var$addSegment(value, part, amount, options) {
switch(part){
case 'era':
case 'year':
case 'month':
case 'day':
return value.cycle(part, amount, {
round: part === 'year'
});
}
if ('hour' in value) switch(part){
case 'dayPeriod':
{
let hours = value.hour;
let isPM = hours >= 12;
return value.set({
hour: isPM ? hours - 12 : hours + 12
});
}
case 'hour':
case 'minute':
case 'second':
return value.cycle(part, amount, {
round: part !== 'hour',
hourCycle: options.hour12 ? 12 : 24
});
}
}
function $09e80d602234613d$var$setSegment(value, part, segmentValue, options) {
switch(part){
case 'day':
case 'month':
case 'year':
return value.set({
[part]: segmentValue
});
}
if ('hour' in value) switch(part){
case 'dayPeriod':
{
let hours = value.hour;
let wasPM = hours >= 12;
let isPM = segmentValue >= 12;
if (isPM === wasPM) return value;
return value.set({
hour: wasPM ? hours - 12 : hours + 12
});
}
case 'hour':
// In 12 hour time, ensure that AM/PM does not change
if (options.hour12) {
let hours = value.hour;
let wasPM = hours >= 12;
if (!wasPM && segmentValue === 12) segmentValue = 0;
if (wasPM && segmentValue < 12) segmentValue += 12;
}
// fallthrough
case 'minute':
case 'second':
return value.set({
[part]: segmentValue
});
}
}
var $93c38a5e28be6249$exports = {};
$parcel$export($93c38a5e28be6249$exports, "useDateRangePickerState", () => $93c38a5e28be6249$export$e50a61c1de9f574);
function $93c38a5e28be6249$export$e50a61c1de9f574(props) {
let [isOpen1, setOpen] = $7UzoM$useState(false);
let [controlledValue, setControlledValue] = $7UzoM$useControlledState(props.value, props.defaultValue || null, props.onChange);
let [placeholderValue, setPlaceholderValue] = $7UzoM$useState(()=>controlledValue || {
start: null,
end: null
}
);
// Reset the placeholder if the value prop is set to null.
if (controlledValue == null && placeholderValue.start && placeholderValue.end) {
placeholderValue = {
start: null,
end: null
};
setPlaceholderValue(placeholderValue);
}
let value1 = controlledValue || placeholderValue;
let valueRef = $7UzoM$useRef(value1);
valueRef.current = value1;
let setValue = (value)=>{
valueRef.current = value;
setPlaceholderValue(value);
if ((value === null || value === void 0 ? void 0 : value.start) && value.end) setControlledValue(value);
else setControlledValue(null);
};
let v = (value1 === null || value1 === void 0 ? void 0 : value1.start) || (value1 === null || value1 === void 0 ? void 0 : value1.end) || props.placeholderValue;
let [granularity, defaultTimeZone] = $35a22f14a1f04b11$export$2440da353cedad43(v, props.granularity);
let hasTime = granularity === 'hour' || granularity === 'minute' || granularity === 'second' || granularity === 'millisecond';
let [dateRange1, setSelectedDateRange] = $7UzoM$useState(null);
let [timeRange1, setSelectedTimeRange] = $7UzoM$useState(null);
if (value1 && value1.start && value1.end) {
dateRange1 = value1;
if ('hour' in value1.start) timeRange1 = value1;
}
let commitValue = (dateRange, timeRange)=>{
setValue({
start: 'timeZone' in timeRange.start ? timeRange.start.set($7UzoM$toDateFields(dateRange.start)) : $7UzoM$toCalendarDateTime(dateRange.start, timeRange.start),
end: 'timeZone' in timeRange.end ? timeRange.end.set($7UzoM$toDateFields(dateRange.end)) : $7UzoM$toCalendarDateTime(dateRange.end, timeRange.end)
});
};
// Intercept setValue to make sure the Time section is not changed by date selection in Calendar
let setDateRange = (range)=>{
if (hasTime) {
if (range.start && range.end && (timeRange1 === null || timeRange1 === void 0 ? void 0 : timeRange1.start) && (timeRange1 === null || timeRange1 === void 0 ? void 0 : timeRange1.end)) commitValue(range, timeRange1);
else setSelectedDateRange(range);
} else if (range.start && range.end) setValue(range);
else setSelectedDateRange(range);
if (!hasTime) setOpen(false);
};
let setTimeRange = (range)=>{
if ((dateRange1 === null || dateRange1 === void 0 ? void 0 : dateRange1.start) && (dateRange1 === null || dateRange1 === void 0 ? void 0 : dateRange1.end) && range.start && range.end) commitValue(dateRange1, range);
else setSelectedTimeRange(range);
};
let validationState = props.validationState || (value1 != null && ($35a22f14a1f04b11$export$eac50920cf2fd59a(value1.start, props.minValue, props.maxValue) || $35a22f14a1f04b11$export$eac50920cf2fd59a(value1.end, props.minValue, props.maxValue) || value1.end != null && value1.start != null && value1.end.compare(value1.start) < 0) ? 'invalid' : null);
return {
value: value1,
setValue: setValue,
dateRange: dateRange1,
timeRange: timeRange1,
granularity: granularity,
setDate (part, date) {
setDateRange({
...dateRange1,
[part]: date
});
},
setTime (part, time) {
setTimeRange({
...timeRange1,
[part]: time
});
},
setDateTime (part, dateTime) {
setValue({
...value1,
[part]: dateTime
});
},
setDateRange: setDateRange,
setTimeRange: setTimeRange,
isOpen: isOpen1,
setOpen (isOpen) {
// Commit the selected date range when the calendar is closed. Use a placeholder time if one wasn't set.
// If only the time range was set and not the date range, don't commit. The state will be preserved until
// the user opens the popover again.
if (!isOpen && !((value1 === null || value1 === void 0 ? void 0 : value1.start) && (value1 === null || value1 === void 0 ? void 0 : value1.end)) && (dateRange1 === null || dateRange1 === void 0 ? void 0 : dateRange1.start) && (dateRange1 === null || dateRange1 === void 0 ? void 0 : dateRange1.end) && hasTime) commitValue(dateRange1, {
start: (timeRange1 === null || timeRange1 === void 0 ? void 0 : timeRange1.start) || $35a22f14a1f04b11$export$c5221a78ef73c5e9(props.placeholderValue),
end: (timeRange1 === null || timeRange1 === void 0 ? void 0 : timeRange1.end) || $35a22f14a1f04b11$export$c5221a78ef73c5e9(props.placeholderValue)
});
setOpen(isOpen);
},
validationState: validationState,
formatValue (locale, fieldOptions) {
if (!value1 || !value1.start || !value1.end) return '';
let startTimeZone = 'timeZone' in value1.start ? value1.start.timeZone : undefined;
let startGranularity = props.granularity || (value1.start && 'minute' in value1.start ? 'minute' : 'day');
let endTimeZone = 'timeZone' in value1.end ? value1.end.timeZone : undefined;
let endGranularity = props.granularity || (value1.end && 'minute' in value1.end ? 'minute' : 'day');
let startOptions = $35a22f14a1f04b11$export$7e319ea407e63bc0(fieldOptions, {
granularity: startGranularity,
timeZone: startTimeZone,
hideTimeZone: props.hideTimeZone,
hourCycle: props.hourCycle
});
let startFormatter = new $7UzoM$DateFormatter(locale, startOptions);
let endFormatter;
if (startTimeZone === endTimeZone && startGranularity === endGranularity) {
// Use formatRange, as it results in shorter output when some of the fields
// are shared between the start and end dates (e.g. the same month).
// Formatting will fail if the end date is before the start date. Fall back below when that happens.
try {
return startFormatter.formatRange(value1.start.toDate(startTimeZone), value1.end.toDate(endTimeZone));
} catch (e) {
// ignore
}
endFormatter = startFormatter;
} else {
let endOptions = $35a22f14a1f04b11$export$7e319ea407e63bc0(fieldOptions, {
granularity: endGranularity,
timeZone: endTimeZone,
hideTimeZone: props.hideTimeZone,
hourCycle: props.hourCycle
});
endFormatter = new $7UzoM$DateFormatter(locale, endOptions);
}
return `${startFormatter.format(value1.start.toDate(startTimeZone))} – ${endFormatter.format(value1.end.toDate(endTimeZone))}`;
},
confirmPlaceholder () {
// Need to use ref value here because the value can be set in the same tick as
// a blur, which means the component won't have re-rendered yet.
let value = valueRef.current;
if (value && Boolean(value.start) !== Boolean(value.end)) {
let calendar = (value.start || value.end).calendar;
let placeholder = $35a22f14a1f04b11$export$66aa2b09de4b1ea5(props.placeholderValue, granularity, calendar, defaultTimeZone);
setValue({
start: value.start || placeholder,
end: value.end || placeholder
});
}
}
};
}
var $eff5d8ee529ac4bb$exports = {};
$parcel$export($eff5d8ee529ac4bb$exports, "useTimeFieldState", () => $eff5d8ee529ac4bb$export$fd53cef0cc796101);
function $eff5d8ee529ac4bb$export$fd53cef0cc796101(props) {
let { placeholderValue: placeholderValue = new $7UzoM$Time() , minValue: minValue , maxValue: maxValue , granularity: granularity } = props;
let [value, setValue] = $7UzoM$useControlledState(props.value, props.defaultValue, props.onChange);
let v = value || placeholderValue;
let day = v && 'day' in v ? v : undefined;
let placeholderDate = $7UzoM$useMemo(()=>$eff5d8ee529ac4bb$var$convertValue(placeholderValue)
, [
placeholderValue
]);
let minDate = $7UzoM$useMemo(()=>$eff5d8ee529ac4bb$var$convertValue(minValue, day)
, [
minValue,
day
]);
let maxDate = $7UzoM$useMemo(()=>$eff5d8ee529ac4bb$var$convertValue(maxValue, day)
, [
maxValue,
day
]);
let dateTime = $7UzoM$useMemo(()=>value == null ? null : $eff5d8ee529ac4bb$var$convertValue(value)
, [
value
]);
let onChange = (newValue)=>{
setValue(v && 'day' in v ? newValue : newValue && $7UzoM$toTime(newValue));
};
return $09e80d602234613d$export$714a241b39a650d6({
...props,
value: dateTime,
defaultValue: undefined,
minValue: minDate,
maxValue: maxDate,
onChange: onChange,
granularity: granularity || 'minute',
maxGranularity: 'hour',
placeholderValue: placeholderDate
});
}
function $eff5d8ee529ac4bb$var$convertValue(value, date = $7UzoM$today($7UzoM$getLocalTimeZone())) {
if (!value) return null;
if ('day' in value) return value;
return $7UzoM$toCalendarDateTime(date, value);
}
export {$ab5bf3f618090389$export$87194bb378cc3ac2 as useDatePickerState, $09e80d602234613d$export$714a241b39a650d6 as useDatePickerFieldState, $93c38a5e28be6249$export$e50a61c1de9f574 as useDateRangePickerState, $eff5d8ee529ac4bb$export$fd53cef0cc796101 as useTimeFieldState};
export {$ab5bf3f618090389$export$87194bb378cc3ac2 as useDatePickerState, $3c0fc76039f1c516$export$60e84778edff6d26 as useDateFieldState, $93c38a5e28be6249$export$e50a61c1de9f574 as useDateRangePickerState, $eff5d8ee529ac4bb$export$fd53cef0cc796101 as useTimeFieldState};
//# sourceMappingURL=module.js.map

@@ -1,76 +0,243 @@

import { CalendarDate, Calendar, CalendarDateTime, DateFormatter } from "@internationalized/date";
import { DatePickerProps, DateValue, Granularity, TimeValue, DateRange, DateRangePickerProps, TimePickerProps } from "@react-types/datepicker";
import { CalendarDate, DateFormatter, Calendar, Time } from "@internationalized/date";
import { FormValidationState } from "@react-stately/form";
import { OverlayTriggerState } from "@react-stately/overlays";
import { ValidationState, RangeValue } from "@react-types/shared";
type FieldOptions = Pick<Intl.DateTimeFormatOptions, 'year' | 'month' | 'day' | 'hour' | 'minute' | 'second'>;
export interface DatePickerState {
value: DateValue;
setValue: (value: DateValue) => void;
interface FormatterOptions {
timeZone?: string;
hideTimeZone?: boolean;
granularity?: DatePickerProps<any>['granularity'];
maxGranularity?: 'year' | 'month' | DatePickerProps<any>['granularity'];
hourCycle?: 12 | 24;
showEra?: boolean;
shouldForceLeadingZeros?: boolean;
}
export interface DatePickerStateOptions<T extends DateValue> extends DatePickerProps<T> {
/**
* Determines whether the date picker popover should close automatically when a date is selected.
* @default true
*/
shouldCloseOnSelect?: boolean | (() => boolean);
}
export interface DatePickerState extends OverlayTriggerState, FormValidationState {
/** The currently selected date. */
value: DateValue | null;
/** Sets the selected date. */
setValue(value: DateValue | null): void;
/**
* The date portion of the value. This may be set prior to `value` if the user has
* selected a date but has not yet selected a time.
*/
dateValue: DateValue;
setDateValue: (value: CalendarDate) => void;
/** Sets the date portion of the value. */
setDateValue(value: CalendarDate): void;
/**
* The time portion of the value. This may be set prior to `value` if the user has
* selected a time but has not yet selected a date.
*/
timeValue: TimeValue;
setTimeValue: (value: TimeValue) => void;
/** Sets the time portion of the value. */
setTimeValue(value: TimeValue): void;
/** The granularity for the field, based on the `granularity` prop and current value. */
granularity: Granularity;
/** Whether the date picker supports selecting a time, according to the `granularity` prop and current value. */
hasTime: boolean;
/** Whether the calendar popover is currently open. */
isOpen: boolean;
setOpen: (isOpen: boolean) => void;
/** Sets whether the calendar popover is open. */
setOpen(isOpen: boolean): void;
/**
* The current validation state of the date picker, based on the `validationState`, `minValue`, and `maxValue` props.
* @deprecated Use `isInvalid` instead.
*/
validationState: ValidationState;
/** Whether the date picker is invalid, based on the `isInvalid`, `minValue`, and `maxValue` props. */
isInvalid: boolean;
/** Formats the selected value using the given options. */
formatValue(locale: string, fieldOptions: FieldOptions): string;
granularity: Granularity;
/** Gets a formatter based on state's props. */
getDateFormatter(locale: string, formatOptions: FormatterOptions): DateFormatter;
}
export function useDatePickerState<T extends DateValue>(props: DatePickerProps<T>): DatePickerState;
/**
* Provides state management for a date picker component.
* A date picker combines a DateField and a Calendar popover to allow users to enter or select a date and time value.
*/
export function useDatePickerState<T extends DateValue = DateValue>(props: DatePickerStateOptions<T>): DatePickerState;
export type SegmentType = 'era' | 'year' | 'month' | 'day' | 'hour' | 'minute' | 'second' | 'dayPeriod' | 'literal' | 'timeZoneName';
export interface DateSegment {
type: Intl.DateTimeFormatPartTypes;
/** The type of segment. */
type: SegmentType;
/** The formatted text for the segment. */
text: string;
/** The numeric value for the segment, if applicable. */
value?: number;
/** The minimum numeric value for the segment, if applicable. */
minValue?: number;
/** The maximum numeric value for the segment, if applicable. */
maxValue?: number;
/** Whether the value is a placeholder. */
isPlaceholder: boolean;
/** A placeholder string for the segment. */
placeholder: string;
/** Whether the segment is editable. */
isEditable: boolean;
}
export interface DatePickerFieldState {
export interface DateFieldState extends FormValidationState {
/** The current field value. */
value: DateValue;
/** The current value, converted to a native JavaScript `Date` object. */
dateValue: Date;
setValue: (value: CalendarDateTime) => void;
/** The calendar system currently in use. */
calendar: Calendar;
/** Sets the field's value. */
setValue(value: DateValue): void;
/** A list of segments for the current value. */
segments: DateSegment[];
/** A date formatter configured for the current locale and format. */
dateFormatter: DateFormatter;
/**
* The current validation state of the date field, based on the `validationState`, `minValue`, and `maxValue` props.
* @deprecated Use `isInvalid` instead.
*/
validationState: ValidationState;
/** Whether the date field is invalid, based on the `isInvalid`, `minValue`, and `maxValue` props. */
isInvalid: boolean;
/** The granularity for the field, based on the `granularity` prop and current value. */
granularity: Granularity;
increment: (type: Intl.DateTimeFormatPartTypes) => void;
decrement: (type: Intl.DateTimeFormatPartTypes) => void;
incrementPage: (type: Intl.DateTimeFormatPartTypes) => void;
decrementPage: (type: Intl.DateTimeFormatPartTypes) => void;
setSegment: (type: Intl.DateTimeFormatPartTypes, value: number) => void;
confirmPlaceholder: (type?: Intl.DateTimeFormatPartTypes) => void;
clearSegment: (type?: Intl.DateTimeFormatPartTypes) => void;
getFormatOptions(fieldOptions: FieldOptions): Intl.DateTimeFormatOptions;
/** The maximum date or time unit that is displayed in the field. */
maxGranularity: 'year' | 'month' | Granularity;
/** Whether the field is disabled. */
isDisabled: boolean;
/** Whether the field is read only. */
isReadOnly: boolean;
/** Whether the field is required. */
isRequired: boolean;
/** Increments the given segment. Upon reaching the minimum or maximum value, the value wraps around to the opposite limit. */
increment(type: SegmentType): void;
/** Decrements the given segment. Upon reaching the minimum or maximum value, the value wraps around to the opposite limit. */
decrement(type: SegmentType): void;
/**
* Increments the given segment by a larger amount, rounding it to the nearest increment.
* The amount to increment by depends on the field, for example 15 minutes, 7 days, and 5 years.
* Upon reaching the minimum or maximum value, the value wraps around to the opposite limit.
*/
incrementPage(type: SegmentType): void;
/**
* Decrements the given segment by a larger amount, rounding it to the nearest increment.
* The amount to decrement by depends on the field, for example 15 minutes, 7 days, and 5 years.
* Upon reaching the minimum or maximum value, the value wraps around to the opposite limit.
*/
decrementPage(type: SegmentType): void;
/** Sets the value of the given segment. */
setSegment(type: 'era', value: string): void;
setSegment(type: SegmentType, value: number): void;
/** Updates the remaining unfilled segments with the placeholder value. */
confirmPlaceholder(): void;
/** Clears the value of the given segment, reverting it to the placeholder. */
clearSegment(type: SegmentType): void;
/** Formats the current date value using the given options. */
formatValue(fieldOptions: FieldOptions): string;
/** Gets a formatter based on state's props. */
getDateFormatter(locale: string, formatOptions: FormatterOptions): DateFormatter;
}
interface DatePickerFieldProps<T extends DateValue> extends DatePickerProps<T> {
maxGranularity?: 'year' | 'month' | DatePickerProps<T>['granularity'];
export interface DateFieldStateOptions<T extends DateValue = DateValue> extends DatePickerProps<T> {
/**
* The maximum unit to display in the date field.
* @default 'year'
*/
maxGranularity?: 'year' | 'month' | Granularity;
/** The locale to display and edit the value according to. */
locale: string;
/**
* A function that creates a [Calendar](../internationalized/date/Calendar.html)
* object for a given calendar identifier. Such a function may be imported from the
* `@internationalized/date` package, or manually implemented to include support for
* only certain calendars.
*/
createCalendar: (name: string) => Calendar;
}
export function useDatePickerFieldState<T extends DateValue>(props: DatePickerFieldProps<T>): DatePickerFieldState;
/**
* Provides state management for a date field component.
* A date field allows users to enter and edit date and time values using a keyboard.
* Each part of a date value is displayed in an individually editable segment.
*/
export function useDateFieldState<T extends DateValue = DateValue>(props: DateFieldStateOptions<T>): DateFieldState;
export interface DateRangePickerStateOptions<T extends DateValue = DateValue> extends DateRangePickerProps<T> {
/**
* Determines whether the date picker popover should close automatically when a date is selected.
* @default true
*/
shouldCloseOnSelect?: boolean | (() => boolean);
}
type TimeRange = RangeValue<TimeValue>;
export interface DateRangePickerState {
value: DateRange;
setValue: (value: DateRange) => void;
setDate: (part: keyof DateRange, value: DateValue) => void;
setTime: (part: keyof TimeRange, value: TimeValue) => void;
setDateTime: (part: keyof DateRange, value: DateValue) => void;
dateRange: DateRange;
setDateRange: (value: DateRange) => void;
timeRange: TimeRange;
setTimeRange: (value: TimeRange) => void;
export interface DateRangePickerState extends OverlayTriggerState, FormValidationState {
/** The currently selected date range. */
value: DateRange | null;
/** Sets the selected date range. */
setValue(value: DateRange | null): void;
/**
* The date portion of the selected range. This may be set prior to `value` if the user has
* selected a date range but has not yet selected a time range.
*/
dateRange: DateRange | null;
/** Sets the date portion of the selected range. */
setDateRange(value: DateRange): void;
/**
* The time portion of the selected range. This may be set prior to `value` if the user has
* selected a time range but has not yet selected a date range.
*/
timeRange: TimeRange | null;
/** Sets the time portion of the selected range. */
setTimeRange(value: TimeRange): void;
/** Sets the date portion of either the start or end of the selected range. */
setDate(part: 'start' | 'end', value: DateValue): void;
/** Sets the time portion of either the start or end of the selected range. */
setTime(part: 'start' | 'end', value: TimeValue): void;
/** Sets the date and time of either the start or end of the selected range. */
setDateTime(part: 'start' | 'end', value: DateValue): void;
/** The granularity for the field, based on the `granularity` prop and current value. */
granularity: Granularity;
/** Whether the date range picker supports selecting times, according to the `granularity` prop and current value. */
hasTime: boolean;
/** Whether the calendar popover is currently open. */
isOpen: boolean;
setOpen: (isOpen: boolean) => void;
/** Sets whether the calendar popover is open. */
setOpen(isOpen: boolean): void;
/**
* The current validation state of the date range picker, based on the `validationState`, `minValue`, and `maxValue` props.
* @deprecated Use `isInvalid` instead.
*/
validationState: ValidationState;
formatValue(locale: string, fieldOptions: FieldOptions): string;
confirmPlaceholder(): void;
granularity: Granularity;
/** Whether the date range picker is invalid, based on the `isInvalid`, `minValue`, and `maxValue` props. */
isInvalid: boolean;
/** Formats the selected range using the given options. */
formatValue(locale: string, fieldOptions: FieldOptions): {
start: string;
end: string;
};
/** Gets a formatter based on state's props. */
getDateFormatter(locale: string, formatOptions: FormatterOptions): DateFormatter;
}
export function useDateRangePickerState<T extends DateValue>(props: DateRangePickerProps<T>): DateRangePickerState;
interface TimeFieldProps<T extends TimeValue> extends TimePickerProps<T> {
/**
* Provides state management for a date range picker component.
* A date range picker combines two DateFields and a RangeCalendar popover to allow
* users to enter or select a date and time range.
*/
export function useDateRangePickerState<T extends DateValue = DateValue>(props: DateRangePickerStateOptions<T>): DateRangePickerState;
export interface TimeFieldStateOptions<T extends TimeValue = TimeValue> extends TimePickerProps<T> {
/** The locale to display and edit the value according to. */
locale: string;
createCalendar: (name: string) => Calendar;
}
export function useTimeFieldState<T extends TimeValue>(props: TimeFieldProps<T>): import("useDatePickerFieldState").DatePickerFieldState;
export interface TimeFieldState extends DateFieldState {
/** The current time value. */
timeValue: Time;
}
/**
* Provides state management for a time field component.
* A time field allows users to enter and edit time values using a keyboard.
* Each part of a time value is displayed in an individually editable segment.
*/
export function useTimeFieldState<T extends TimeValue = TimeValue>(props: TimeFieldStateOptions<T>): TimeFieldState;
//# sourceMappingURL=types.d.ts.map
{
"name": "@react-stately/datepicker",
"version": "3.0.0-nightly.3113+404d41859",
"version": "3.0.0-nightly.3114+68403fe55",
"description": "Spectrum UI components in React",

@@ -8,2 +8,7 @@ "license": "Apache-2.0",

"module": "dist/module.js",
"exports": {
"types": "./dist/types.d.ts",
"import": "./dist/import.mjs",
"require": "./dist/main.js"
},
"types": "dist/types.d.ts",

@@ -21,11 +26,13 @@ "source": "src/index.ts",

"dependencies": {
"@babel/runtime": "^7.6.2",
"@internationalized/date": "3.0.0-nightly.3113+404d41859",
"@react-stately/utils": "3.0.0-nightly.1417+404d41859",
"@react-types/datepicker": "3.0.0-nightly.3113+404d41859",
"@react-types/shared": "3.0.0-nightly.1417+404d41859",
"date-fns": "^1.30.1"
"@internationalized/date": "3.5.6-nightly.5042+68403fe55",
"@internationalized/string": "3.2.4-nightly.5042+68403fe55",
"@react-stately/form": "3.0.6-nightly.5042+68403fe55",
"@react-stately/overlays": "3.6.11-nightly.5042+68403fe55",
"@react-stately/utils": "3.0.0-nightly.3114+68403fe55",
"@react-types/datepicker": "3.0.0-nightly.3114+68403fe55",
"@react-types/shared": "3.0.0-nightly.3114+68403fe55",
"@swc/helpers": "^0.5.0"
},
"peerDependencies": {
"react": "^16.8.0 || ^17.0.0-rc.1"
"react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0"
},

@@ -35,3 +42,3 @@ "publishConfig": {

},
"gitHead": "404d41859b7d6f56201d7fc01bd9f22ae3512937"
"gitHead": "68403fe55489dce3de1b3094c957d598ad719861"
}

@@ -13,5 +13,10 @@ /*

export * from './useDatePickerState';
export * from './useDatePickerFieldState';
export * from './useDateRangePickerState';
export * from './useTimeFieldState';
export {useDatePickerState} from './useDatePickerState';
export {useDateFieldState} from './useDateFieldState';
export {useDateRangePickerState} from './useDateRangePickerState';
export {useTimeFieldState} from './useTimeFieldState';
export type {DateFieldStateOptions, DateFieldState, DateSegment, SegmentType} from './useDateFieldState';
export type {DatePickerStateOptions, DatePickerState} from './useDatePickerState';
export type {DateRangePickerStateOptions, DateRangePickerState} from './useDateRangePickerState';
export type {TimeFieldStateOptions, TimeFieldState} from './useTimeFieldState';

@@ -13,26 +13,65 @@ /*

import {CalendarDate, DateFormatter, toCalendarDateTime, toDateFields} from '@internationalized/date';
import {CalendarDate, DateFormatter, toCalendarDate, toCalendarDateTime} from '@internationalized/date';
import {DatePickerProps, DateValue, Granularity, TimeValue} from '@react-types/datepicker';
import {FieldOptions, getFormatOptions, getPlaceholderTime, useDefaultProps} from './utils';
import {isInvalid} from './utils';
import {FieldOptions, FormatterOptions, getFormatOptions, getPlaceholderTime, getValidationResult, useDefaultProps} from './utils';
import {FormValidationState, useFormValidationState} from '@react-stately/form';
import {OverlayTriggerState, useOverlayTriggerState} from '@react-stately/overlays';
import {useControlledState} from '@react-stately/utils';
import {useState} from 'react';
import {useMemo, useState} from 'react';
import {ValidationState} from '@react-types/shared';
export interface DatePickerState {
value: DateValue,
setValue: (value: DateValue) => void,
export interface DatePickerStateOptions<T extends DateValue> extends DatePickerProps<T> {
/**
* Determines whether the date picker popover should close automatically when a date is selected.
* @default true
*/
shouldCloseOnSelect?: boolean | (() => boolean)
}
export interface DatePickerState extends OverlayTriggerState, FormValidationState {
/** The currently selected date. */
value: DateValue | null,
/** Sets the selected date. */
setValue(value: DateValue | null): void,
/**
* The date portion of the value. This may be set prior to `value` if the user has
* selected a date but has not yet selected a time.
*/
dateValue: DateValue,
setDateValue: (value: CalendarDate) => void,
/** Sets the date portion of the value. */
setDateValue(value: CalendarDate): void,
/**
* The time portion of the value. This may be set prior to `value` if the user has
* selected a time but has not yet selected a date.
*/
timeValue: TimeValue,
setTimeValue: (value: TimeValue) => void,
/** Sets the time portion of the value. */
setTimeValue(value: TimeValue): void,
/** The granularity for the field, based on the `granularity` prop and current value. */
granularity: Granularity,
/** Whether the date picker supports selecting a time, according to the `granularity` prop and current value. */
hasTime: boolean,
/** Whether the calendar popover is currently open. */
isOpen: boolean,
setOpen: (isOpen: boolean) => void,
/** Sets whether the calendar popover is open. */
setOpen(isOpen: boolean): void,
/**
* The current validation state of the date picker, based on the `validationState`, `minValue`, and `maxValue` props.
* @deprecated Use `isInvalid` instead.
*/
validationState: ValidationState,
/** Whether the date picker is invalid, based on the `isInvalid`, `minValue`, and `maxValue` props. */
isInvalid: boolean,
/** Formats the selected value using the given options. */
formatValue(locale: string, fieldOptions: FieldOptions): string,
granularity: Granularity
/** Gets a formatter based on state's props. */
getDateFormatter(locale: string, formatOptions: FormatterOptions): DateFormatter
}
export function useDatePickerState<T extends DateValue>(props: DatePickerProps<T>): DatePickerState {
let [isOpen, setOpen] = useState(false);
/**
* Provides state management for a date picker component.
* A date picker combines a DateField and a Calendar popover to allow users to enter or select a date and time value.
*/
export function useDatePickerState<T extends DateValue = DateValue>(props: DatePickerStateOptions<T>): DatePickerState {
let overlayState = useOverlayTriggerState(props);
let [value, setValue] = useControlledState<DateValue>(props.value, props.defaultValue || null, props.onChange);

@@ -43,3 +82,4 @@

let dateValue = value != null ? value.toDate(defaultTimeZone ?? 'UTC') : null;
let hasTime = granularity === 'hour' || granularity === 'minute' || granularity === 'second' || granularity === 'millisecond';
let hasTime = granularity === 'hour' || granularity === 'minute' || granularity === 'second';
let shouldCloseOnSelect = props.shouldCloseOnSelect ?? true;

@@ -61,4 +101,35 @@ let [selectedDate, setSelectedDate] = useState<DateValue>(null);

let showEra = value?.calendar.identifier === 'gregory' && value.era === 'BC';
let formatOpts = useMemo(() => ({
granularity,
timeZone: defaultTimeZone,
hideTimeZone: props.hideTimeZone,
hourCycle: props.hourCycle,
shouldForceLeadingZeros: props.shouldForceLeadingZeros,
showEra
}), [granularity, props.hourCycle, props.shouldForceLeadingZeros, defaultTimeZone, props.hideTimeZone, showEra]);
let {minValue, maxValue, isDateUnavailable} = props;
let builtinValidation = useMemo(() => getValidationResult(
value,
minValue,
maxValue,
isDateUnavailable,
formatOpts
), [value, minValue, maxValue, isDateUnavailable, formatOpts]);
let validation = useFormValidationState({
...props,
value,
builtinValidation
});
let isValueInvalid = validation.displayValidation.isInvalid;
let validationState: ValidationState = props.validationState || (isValueInvalid ? 'invalid' : null);
let commitValue = (date: DateValue, time: TimeValue) => {
setValue('timeZone' in time ? time.set(toDateFields(date)) : toCalendarDateTime(date, time));
setValue('timeZone' in time ? time.set(toCalendarDate(date)) : toCalendarDateTime(date, time));
setSelectedDate(null);
setSelectedTime(null);
validation.commitValidation();
};

@@ -68,5 +139,6 @@

let selectDate = (newValue: CalendarDate) => {
let shouldClose = typeof shouldCloseOnSelect === 'function' ? shouldCloseOnSelect() : shouldCloseOnSelect;
if (hasTime) {
if (selectedTime) {
commitValue(newValue, selectedTime);
if (selectedTime || shouldClose) {
commitValue(newValue, selectedTime || getPlaceholderTime(props.placeholderValue));
} else {

@@ -77,6 +149,7 @@ setSelectedDate(newValue);

setValue(newValue);
validation.commitValidation();
}
if (!hasTime) {
setOpen(false);
if (shouldClose) {
overlayState.setOpen(false);
}

@@ -86,3 +159,3 @@ };

let selectTime = (newValue: TimeValue) => {
if (selectedDate) {
if (selectedDate && newValue) {
commitValue(selectedDate, newValue);

@@ -94,6 +167,4 @@ } else {

let validationState: ValidationState = props.validationState ||
(isInvalid(value, props.minValue, props.maxValue) ? 'invalid' : null);
return {
...validation,
value,

@@ -106,3 +177,4 @@ setValue,

granularity,
isOpen,
hasTime,
...overlayState,
setOpen(isOpen) {

@@ -116,5 +188,6 @@ // Commit the selected date when the calendar is closed. Use a placeholder time if one wasn't set.

setOpen(isOpen);
overlayState.setOpen(isOpen);
},
validationState,
isInvalid: isValueInvalid,
formatValue(locale, fieldOptions) {

@@ -125,13 +198,12 @@ if (!dateValue) {

let formatOptions = getFormatOptions(fieldOptions, {
granularity,
timeZone: defaultTimeZone,
hideTimeZone: props.hideTimeZone,
hourCycle: props.hourCycle
});
let formatOptions = getFormatOptions(fieldOptions, formatOpts);
let formatter = new DateFormatter(locale, formatOptions);
return formatter.format(dateValue);
},
getDateFormatter(locale, formatOptions: FormatterOptions) {
let newOptions = {...formatOpts, ...formatOptions};
let newFormatOptions = getFormatOptions({}, newOptions);
return new DateFormatter(locale, newFormatOptions);
}
};
}

@@ -13,30 +13,74 @@ /*

import {createPlaceholderDate, FieldOptions, getFormatOptions, getPlaceholderTime, isInvalid, useDefaultProps} from './utils';
import {DateFormatter, toCalendarDateTime, toDateFields} from '@internationalized/date';
import {DateFormatter, toCalendarDate, toCalendarDateTime} from '@internationalized/date';
import {DateRange, DateRangePickerProps, DateValue, Granularity, TimeValue} from '@react-types/datepicker';
import {FieldOptions, FormatterOptions, getFormatOptions, getPlaceholderTime, getRangeValidationResult, useDefaultProps} from './utils';
import {FormValidationState, useFormValidationState} from '@react-stately/form';
import {OverlayTriggerState, useOverlayTriggerState} from '@react-stately/overlays';
import {RangeValue, ValidationState} from '@react-types/shared';
import {useControlledState} from '@react-stately/utils';
import {useRef, useState} from 'react';
import {useMemo, useState} from 'react';
export interface DateRangePickerStateOptions<T extends DateValue = DateValue> extends DateRangePickerProps<T> {
/**
* Determines whether the date picker popover should close automatically when a date is selected.
* @default true
*/
shouldCloseOnSelect?: boolean | (() => boolean)
}
type TimeRange = RangeValue<TimeValue>;
export interface DateRangePickerState {
value: DateRange,
setValue: (value: DateRange) => void,
setDate: (part: keyof DateRange, value: DateValue) => void,
setTime: (part: keyof TimeRange, value: TimeValue) => void,
setDateTime: (part: keyof DateRange, value: DateValue) => void,
dateRange: DateRange,
setDateRange: (value: DateRange) => void,
timeRange: TimeRange,
setTimeRange: (value: TimeRange) => void,
export interface DateRangePickerState extends OverlayTriggerState, FormValidationState {
/** The currently selected date range. */
value: DateRange | null,
/** Sets the selected date range. */
setValue(value: DateRange | null): void,
/**
* The date portion of the selected range. This may be set prior to `value` if the user has
* selected a date range but has not yet selected a time range.
*/
dateRange: DateRange | null,
/** Sets the date portion of the selected range. */
setDateRange(value: DateRange): void,
/**
* The time portion of the selected range. This may be set prior to `value` if the user has
* selected a time range but has not yet selected a date range.
*/
timeRange: TimeRange | null,
/** Sets the time portion of the selected range. */
setTimeRange(value: TimeRange): void,
/** Sets the date portion of either the start or end of the selected range. */
setDate(part: 'start' | 'end', value: DateValue): void,
/** Sets the time portion of either the start or end of the selected range. */
setTime(part: 'start' | 'end', value: TimeValue): void,
/** Sets the date and time of either the start or end of the selected range. */
setDateTime(part: 'start' | 'end', value: DateValue): void,
/** The granularity for the field, based on the `granularity` prop and current value. */
granularity: Granularity,
/** Whether the date range picker supports selecting times, according to the `granularity` prop and current value. */
hasTime: boolean,
/** Whether the calendar popover is currently open. */
isOpen: boolean,
setOpen: (isOpen: boolean) => void,
/** Sets whether the calendar popover is open. */
setOpen(isOpen: boolean): void,
/**
* The current validation state of the date range picker, based on the `validationState`, `minValue`, and `maxValue` props.
* @deprecated Use `isInvalid` instead.
*/
validationState: ValidationState,
formatValue(locale: string, fieldOptions: FieldOptions): string,
confirmPlaceholder(): void,
granularity: Granularity
/** Whether the date range picker is invalid, based on the `isInvalid`, `minValue`, and `maxValue` props. */
isInvalid: boolean,
/** Formats the selected range using the given options. */
formatValue(locale: string, fieldOptions: FieldOptions): {start: string, end: string},
/** Gets a formatter based on state's props. */
getDateFormatter(locale: string, formatOptions: FormatterOptions): DateFormatter
}
export function useDateRangePickerState<T extends DateValue>(props: DateRangePickerProps<T>): DateRangePickerState {
let [isOpen, setOpen] = useState(false);
/**
* Provides state management for a date range picker component.
* A date range picker combines two DateFields and a RangeCalendar popover to allow
* users to enter or select a date and time range.
*/
export function useDateRangePickerState<T extends DateValue = DateValue>(props: DateRangePickerStateOptions<T>): DateRangePickerState {
let overlayState = useOverlayTriggerState(props);
let [controlledValue, setControlledValue] = useControlledState<DateRange>(props.value, props.defaultValue || null, props.onChange);

@@ -52,8 +96,5 @@ let [placeholderValue, setPlaceholderValue] = useState(() => controlledValue || {start: null, end: null});

let value = controlledValue || placeholderValue;
let valueRef = useRef(value);
valueRef.current = value;
let setValue = (value: DateRange) => {
valueRef.current = value;
setPlaceholderValue(value);
setPlaceholderValue(value || {start: null, end: null});
if (value?.start && value.end) {

@@ -68,3 +109,4 @@ setControlledValue(value);

let [granularity, defaultTimeZone] = useDefaultProps(v, props.granularity);
let hasTime = granularity === 'hour' || granularity === 'minute' || granularity === 'second' || granularity === 'millisecond';
let hasTime = granularity === 'hour' || granularity === 'minute' || granularity === 'second';
let shouldCloseOnSelect = props.shouldCloseOnSelect ?? true;

@@ -83,5 +125,8 @@ let [dateRange, setSelectedDateRange] = useState<DateRange>(null);

setValue({
start: 'timeZone' in timeRange.start ? timeRange.start.set(toDateFields(dateRange.start)) : toCalendarDateTime(dateRange.start, timeRange.start),
end: 'timeZone' in timeRange.end ? timeRange.end.set(toDateFields(dateRange.end)) : toCalendarDateTime(dateRange.end, timeRange.end)
start: 'timeZone' in timeRange.start ? timeRange.start.set(toCalendarDate(dateRange.start)) : toCalendarDateTime(dateRange.start, timeRange.start),
end: 'timeZone' in timeRange.end ? timeRange.end.set(toCalendarDate(dateRange.end)) : toCalendarDateTime(dateRange.end, timeRange.end)
});
setSelectedDateRange(null);
setSelectedTimeRange(null);
validation.commitValidation();
};

@@ -91,5 +136,9 @@

let setDateRange = (range: DateRange) => {
let shouldClose = typeof shouldCloseOnSelect === 'function' ? shouldCloseOnSelect() : shouldCloseOnSelect;
if (hasTime) {
if (range.start && range.end && timeRange?.start && timeRange?.end) {
commitValue(range, timeRange);
if (shouldClose || (range.start && range.end && timeRange?.start && timeRange?.end)) {
commitValue(range, {
start: timeRange?.start || getPlaceholderTime(props.placeholderValue),
end: timeRange?.end || getPlaceholderTime(props.placeholderValue)
});
} else {

@@ -100,2 +149,3 @@ setSelectedDateRange(range);

setValue(range);
validation.commitValidation();
} else {

@@ -105,4 +155,4 @@ setSelectedDateRange(range);

if (!hasTime) {
setOpen(false);
if (shouldClose) {
overlayState.setOpen(false);
}

@@ -119,10 +169,33 @@ };

let validationState: ValidationState = props.validationState
|| (value != null && (
isInvalid(value.start, props.minValue, props.maxValue) ||
isInvalid(value.end, props.minValue, props.maxValue) ||
(value.end != null && value.start != null && value.end.compare(value.start) < 0)
) ? 'invalid' : null);
let showEra = (value?.start?.calendar.identifier === 'gregory' && value.start.era === 'BC') || (value?.end?.calendar.identifier === 'gregory' && value.end.era === 'BC');
let formatOpts = useMemo(() => ({
granularity,
timeZone: defaultTimeZone,
hideTimeZone: props.hideTimeZone,
hourCycle: props.hourCycle,
shouldForceLeadingZeros: props.shouldForceLeadingZeros,
showEra
}), [granularity, props.hourCycle, props.shouldForceLeadingZeros, defaultTimeZone, props.hideTimeZone, showEra]);
let {minValue, maxValue, isDateUnavailable} = props;
let builtinValidation = useMemo(() => getRangeValidationResult(
value,
minValue,
maxValue,
isDateUnavailable,
formatOpts
), [value, minValue, maxValue, isDateUnavailable, formatOpts]);
let validation = useFormValidationState({
...props,
value: controlledValue,
name: useMemo(() => [props.startName, props.endName], [props.startName, props.endName]),
builtinValidation
});
let isValueInvalid = validation.displayValidation.isInvalid;
let validationState: ValidationState = props.validationState || (isValueInvalid ? 'invalid' : null);
return {
...validation,
value,

@@ -133,2 +206,3 @@ setValue,

granularity,
hasTime,
setDate(part, date) {

@@ -145,3 +219,3 @@ setDateRange({...dateRange, [part]: date});

setTimeRange,
isOpen,
...overlayState,
setOpen(isOpen) {

@@ -158,8 +232,9 @@ // Commit the selected date range when the calendar is closed. Use a placeholder time if one wasn't set.

setOpen(isOpen);
overlayState.setOpen(isOpen);
},
validationState,
isInvalid: isValueInvalid,
formatValue(locale, fieldOptions) {
if (!value || !value.start || !value.end) {
return '';
return null;
}

@@ -176,8 +251,13 @@

hideTimeZone: props.hideTimeZone,
hourCycle: props.hourCycle
hourCycle: props.hourCycle,
showEra: (value.start.calendar.identifier === 'gregory' && value.start.era === 'BC') ||
(value.end.calendar.identifier === 'gregory' && value.end.era === 'BC')
});
let startDate = value.start.toDate(startTimeZone || 'UTC');
let endDate = value.end.toDate(endTimeZone || 'UTC');
let startFormatter = new DateFormatter(locale, startOptions);
let endFormatter: Intl.DateTimeFormat;
if (startTimeZone === endTimeZone && startGranularity === endGranularity) {
if (startTimeZone === endTimeZone && startGranularity === endGranularity && value.start.compare(value.end) !== 0) {
// Use formatRange, as it results in shorter output when some of the fields

@@ -187,3 +267,28 @@ // are shared between the start and end dates (e.g. the same month).

try {
return startFormatter.formatRange(value.start.toDate(startTimeZone), value.end.toDate(endTimeZone));
let parts = startFormatter.formatRangeToParts(startDate, endDate);
// Find the separator between the start and end date. This is determined
// by finding the last shared literal before the end range.
let separatorIndex = -1;
for (let i = 0; i < parts.length; i++) {
let part = parts[i];
if (part.source === 'shared' && part.type === 'literal') {
separatorIndex = i;
} else if (part.source === 'endRange') {
break;
}
}
// Now we can combine the parts into start and end strings.
let start = '';
let end = '';
for (let i = 0; i < parts.length; i++) {
if (i < separatorIndex) {
start += parts[i].value;
} else if (i > separatorIndex) {
end += parts[i].value;
}
}
return {start, end};
} catch (e) {

@@ -205,18 +310,13 @@ // ignore

return `${startFormatter.format(value.start.toDate(startTimeZone))} – ${endFormatter.format(value.end.toDate(endTimeZone))}`;
return {
start: startFormatter.format(startDate),
end: endFormatter.format(endDate)
};
},
confirmPlaceholder() {
// Need to use ref value here because the value can be set in the same tick as
// a blur, which means the component won't have re-rendered yet.
let value = valueRef.current;
if (value && Boolean(value.start) !== Boolean(value.end)) {
let calendar = (value.start || value.end).calendar;
let placeholder = createPlaceholderDate(props.placeholderValue, granularity, calendar, defaultTimeZone);
setValue({
start: value.start || placeholder,
end: value.end || placeholder
});
}
getDateFormatter(locale, formatOptions: FormatterOptions) {
let newOptions = {...formatOpts, ...formatOptions};
let newFormatOptions = getFormatOptions({}, newOptions);
return new DateFormatter(locale, newFormatOptions);
}
};
}

@@ -13,14 +13,24 @@ /*

import {Calendar, getLocalTimeZone, Time, toCalendarDateTime, today, toTime} from '@internationalized/date';
import {DateFieldState, useDateFieldState} from '.';
import {DateValue, TimePickerProps, TimeValue} from '@react-types/datepicker';
import {getLocalTimeZone, GregorianCalendar, Time, toCalendarDateTime, today, toTime, toZoned} from '@internationalized/date';
import {useCallback, useMemo} from 'react';
import {useControlledState} from '@react-stately/utils';
import {useDatePickerFieldState} from '.';
import {useMemo} from 'react';
interface TimeFieldProps<T extends TimeValue> extends TimePickerProps<T> {
locale: string,
createCalendar: (name: string) => Calendar
export interface TimeFieldStateOptions<T extends TimeValue = TimeValue> extends TimePickerProps<T> {
/** The locale to display and edit the value according to. */
locale: string
}
export function useTimeFieldState<T extends TimeValue>(props: TimeFieldProps<T>) {
export interface TimeFieldState extends DateFieldState {
/** The current time value. */
timeValue: Time
}
/**
* Provides state management for a time field component.
* A time field allows users to enter and edit time values using a keyboard.
* Each part of a time value is displayed in an individually editable segment.
*/
export function useTimeFieldState<T extends TimeValue = TimeValue>(props: TimeFieldStateOptions<T>): TimeFieldState {
let {

@@ -30,3 +40,4 @@ placeholderValue = new Time(),

maxValue,
granularity
granularity,
validate
} = props;

@@ -42,12 +53,18 @@

let day = v && 'day' in v ? v : undefined;
let placeholderDate = useMemo(() => convertValue(placeholderValue), [placeholderValue]);
let defaultValueTimeZone = props.defaultValue && 'timeZone' in props.defaultValue ? props.defaultValue.timeZone : undefined;
let placeholderDate = useMemo(() => {
let valueTimeZone = v && 'timeZone' in v ? v.timeZone : undefined;
return (valueTimeZone || defaultValueTimeZone) && placeholderValue ? toZoned(convertValue(placeholderValue), valueTimeZone || defaultValueTimeZone) : convertValue(placeholderValue);
}, [placeholderValue, v, defaultValueTimeZone]);
let minDate = useMemo(() => convertValue(minValue, day), [minValue, day]);
let maxDate = useMemo(() => convertValue(maxValue, day), [maxValue, day]);
let timeValue = useMemo(() => value && 'day' in value ? toTime(value) : value as Time, [value]);
let dateTime = useMemo(() => value == null ? null : convertValue(value), [value]);
let onChange = newValue => {
setValue(v && 'day' in v ? newValue : newValue && toTime(newValue));
setValue(day || defaultValueTimeZone ? newValue : newValue && toTime(newValue));
};
return useDatePickerFieldState({
let state = useDateFieldState({
...props,

@@ -61,4 +78,12 @@ value: dateTime,

maxGranularity: 'hour',
placeholderValue: placeholderDate
placeholderValue: placeholderDate,
// Calendar should not matter for time fields.
createCalendar: () => new GregorianCalendar(),
validate: useCallback(() => validate?.(value as any), [validate, value])
});
return {
...state,
timeValue
};
}

@@ -65,0 +90,0 @@

@@ -13,15 +13,115 @@ /*

import {Calendar, now, Time, toCalendar, toCalendarDate, toCalendarDateTime} from '@internationalized/date';
import {Calendar, DateFormatter, now, Time, toCalendar, toCalendarDate, toCalendarDateTime} from '@internationalized/date';
import {DatePickerProps, DateValue, Granularity, TimeValue} from '@react-types/datepicker';
import {useRef} from 'react';
// @ts-ignore
import i18nMessages from '../intl/*.json';
import {LocalizedStringDictionary, LocalizedStringFormatter} from '@internationalized/string';
import {mergeValidation, VALID_VALIDITY_STATE} from '@react-stately/form';
import {RangeValue, ValidationResult} from '@react-types/shared';
import {useState} from 'react';
export function isInvalid(value: DateValue, minValue: DateValue, maxValue: DateValue) {
return value != null && (
(minValue != null && value.compare(minValue) < 0) ||
(maxValue != null && value.compare(maxValue) > 0)
const dictionary = new LocalizedStringDictionary(i18nMessages);
function getLocale() {
// Match browser language setting here, NOT react-aria's I18nProvider, so that we match other browser-provided
// validation messages, which to not respect our provider's language.
// @ts-ignore
return (typeof navigator !== 'undefined' && (navigator.language || navigator.userLanguage)) || 'en-US';
}
export function getValidationResult(
value: DateValue,
minValue: DateValue,
maxValue: DateValue,
isDateUnavailable: (v: DateValue) => boolean,
options: FormatterOptions
): ValidationResult {
let rangeOverflow = value != null && maxValue != null && value.compare(maxValue) > 0;
let rangeUnderflow = value != null && minValue != null && value.compare(minValue) < 0;
let isUnavailable = (value != null && isDateUnavailable?.(value)) || false;
let isInvalid = rangeOverflow || rangeUnderflow || isUnavailable;
let errors = [];
if (isInvalid) {
let locale = getLocale();
let strings = LocalizedStringDictionary.getGlobalDictionaryForPackage('@react-stately/datepicker') || dictionary;
let formatter = new LocalizedStringFormatter(locale, strings);
let dateFormatter = new DateFormatter(locale, getFormatOptions({}, options));
let timeZone = dateFormatter.resolvedOptions().timeZone;
if (rangeUnderflow) {
errors.push(formatter.format('rangeUnderflow', {minValue: dateFormatter.format(minValue.toDate(timeZone))}));
}
if (rangeOverflow) {
errors.push(formatter.format('rangeOverflow', {maxValue: dateFormatter.format(maxValue.toDate(timeZone))}));
}
if (isUnavailable) {
errors.push(formatter.format('unavailableDate'));
}
}
return {
isInvalid,
validationErrors: errors,
validationDetails: {
badInput: isUnavailable,
customError: false,
patternMismatch: false,
rangeOverflow,
rangeUnderflow,
stepMismatch: false,
tooLong: false,
tooShort: false,
typeMismatch: false,
valueMissing: false,
valid: !isInvalid
}
};
}
export function getRangeValidationResult(
value: RangeValue<DateValue>,
minValue: DateValue,
maxValue: DateValue,
isDateUnavailable: (v: DateValue) => boolean,
options: FormatterOptions
) {
let startValidation = getValidationResult(
value?.start,
minValue,
maxValue,
isDateUnavailable,
options
);
let endValidation = getValidationResult(
value?.end,
minValue,
maxValue,
isDateUnavailable,
options
);
let result = mergeValidation(startValidation, endValidation);
if (value.end != null && value.start != null && value.end.compare(value.start) < 0) {
let strings = LocalizedStringDictionary.getGlobalDictionaryForPackage('@react-stately/datepicker') || dictionary;
result = mergeValidation(result, {
isInvalid: true,
validationErrors: [strings.getStringForLocale('rangeReversed', getLocale())],
validationDetails: {
...VALID_VALIDITY_STATE,
rangeUnderflow: true,
rangeOverflow: true,
valid: false
}
});
}
return result;
}
export type FieldOptions = Pick<Intl.DateTimeFormatOptions, 'year' | 'month' | 'day' | 'hour' | 'minute' | 'second'>;
interface FormatterOptions {
export interface FormatterOptions {
timeZone?: string,

@@ -31,3 +131,5 @@ hideTimeZone?: boolean,

maxGranularity?: 'year' | 'month' | DatePickerProps<any>['granularity'],
hourCycle?: 12 | 24
hourCycle?: 12 | 24,
showEra?: boolean,
shouldForceLeadingZeros?: boolean
}

@@ -44,2 +146,11 @@

const TWO_DIGIT_FIELD_OPTIONS: FieldOptions = {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
};
export function getFormatOptions(

@@ -49,3 +160,4 @@ fieldOptions: FieldOptions,

): Intl.DateTimeFormatOptions {
fieldOptions = {...DEFAULT_FIELD_OPTIONS, ...fieldOptions};
let defaultFieldOptions = options.shouldForceLeadingZeros ? TWO_DIGIT_FIELD_OPTIONS : DEFAULT_FIELD_OPTIONS;
fieldOptions = {...defaultFieldOptions, ...fieldOptions};
let granularity = options.granularity || 'minute';

@@ -83,2 +195,6 @@ let keys = Object.keys(fieldOptions);

if (options.showEra && startIdx === 0) {
opts.era = 'short';
}
return opts;

@@ -133,17 +249,23 @@ }

// Compute default granularity and time zone from the value. If the value becomes null, keep the last values.
let lastValue = useRef(v);
if (v) {
lastValue.current = v;
}
v = lastValue.current;
let defaultTimeZone = (v && 'timeZone' in v ? v.timeZone : undefined);
granularity = granularity || (v && 'minute' in v ? 'minute' : 'day');
let defaultGranularity: Granularity = (v && 'minute' in v ? 'minute' : 'day');
// props.granularity must actually exist in the value if one is provided.
if (v && !(granularity in v)) {
if (v && granularity && !(granularity in v)) {
throw new Error('Invalid granularity ' + granularity + ' for value ' + v.toString());
}
return [granularity, defaultTimeZone];
let [lastValue, setLastValue] = useState<[Granularity, string]>([defaultGranularity, defaultTimeZone]);
// If the granularity or time zone changed, update the last value.
if (v && (lastValue[0] !== defaultGranularity || lastValue[1] !== defaultTimeZone)) {
setLastValue([defaultGranularity, defaultTimeZone]);
}
if (!granularity) {
granularity = v ? defaultGranularity : lastValue[0];
}
let timeZone = v ? defaultTimeZone : lastValue[1];
return [granularity, timeZone];
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc