@esri/calcite-components
Version:
Web Components for Esri's Calcite Design System.
2,442 lines • 89.4 kB
JavaScript
/*!
* All material copyright ESRI, All Rights Reserved, unless otherwise specified.
* See https://github.com/Esri/calcite-components/blob/master/LICENSE.md for details.
* v1.5.0-next.4
*/
'use strict';
const index = require('./index-55f8a3b7.js');
const form = require('./form-f9d34433.js');
const guid = require('./guid-db20443e.js');
const interactive = require('./interactive-26294f2c.js');
const key = require('./key-2ce02f02.js');
const label = require('./label-fb3080ea.js');
const loadable = require('./loadable-53f729bb.js');
const locale$1 = require('./locale-fc347462.js');
const focusTrapComponent = require('./focusTrapComponent-645b4a75.js');
const t9n = require('./t9n-14d528c4.js');
const maxTenthForMinuteAndSecond = 5;
function createLocaleDateTimeFormatter(locale, numberingSystem, includeSeconds = true) {
const options = {
hour: "2-digit",
minute: "2-digit",
timeZone: "UTC",
numberingSystem: locale$1.getSupportedNumberingSystem(numberingSystem)
};
if (includeSeconds) {
options.second = "2-digit";
}
return locale$1.getDateTimeFormat(locale, options);
}
function formatTimePart(number) {
const numberAsString = number.toString();
return number >= 0 && number <= 9 ? numberAsString.padStart(2, "0") : numberAsString;
}
function formatTimeString(value) {
if (!isValidTime(value)) {
return null;
}
const [hourString, minuteString, secondString] = value.split(":");
const hour = formatTimePart(parseInt(hourString));
const minute = formatTimePart(parseInt(minuteString));
if (secondString) {
const second = formatTimePart(parseInt(secondString));
return `${hour}:${minute}:${second}`;
}
return `${hour}:${minute}`;
}
function getLocaleHourCycle(locale, numberingSystem) {
const formatter = createLocaleDateTimeFormatter(locale, numberingSystem);
const parts = formatter.formatToParts(new Date(Date.UTC(0, 0, 0, 0, 0, 0)));
return getLocalizedTimePart("meridiem", parts) ? "12" : "24";
}
function getLocalizedTimePart(part, parts) {
if (!part || !parts) {
return null;
}
if (part === "hourSuffix") {
const hourIndex = parts.indexOf(parts.find(({ type }) => type === "hour"));
const minuteIndex = parts.indexOf(parts.find(({ type }) => type === "minute"));
const hourSuffix = parts[hourIndex + 1];
return hourSuffix && hourSuffix.type === "literal" && minuteIndex - hourIndex === 2
? hourSuffix.value?.trim() || null
: null;
}
if (part === "minuteSuffix") {
const minuteIndex = parts.indexOf(parts.find(({ type }) => type === "minute"));
const secondIndex = parts.indexOf(parts.find(({ type }) => type === "second"));
const minuteSuffix = parts[minuteIndex + 1];
return minuteSuffix && minuteSuffix.type === "literal" && secondIndex - minuteIndex === 2
? minuteSuffix.value?.trim() || null
: null;
}
if (part === "secondSuffix") {
const secondIndex = parts.indexOf(parts.find(({ type }) => type === "second"));
const secondSuffix = parts[secondIndex + 1];
return secondSuffix && secondSuffix.type === "literal" ? secondSuffix.value?.trim() || null : null;
}
return parts.find(({ type }) => (part == "meridiem" ? type === "dayPeriod" : type === part))?.value || null;
}
function getMeridiem(hour) {
if (!locale$1.isValidNumber(hour)) {
return null;
}
const hourAsNumber = parseInt(hour);
return hourAsNumber >= 0 && hourAsNumber <= 11 ? "AM" : "PM";
}
function isValidTime(value) {
if (!value || value.startsWith(":") || value.endsWith(":")) {
return false;
}
const splitValue = value.split(":");
const validLength = splitValue.length > 1 && splitValue.length < 4;
if (!validLength) {
return false;
}
const [hour, minute, second] = splitValue;
const hourAsNumber = parseInt(splitValue[0]);
const minuteAsNumber = parseInt(splitValue[1]);
const secondAsNumber = parseInt(splitValue[2]);
const hourValid = locale$1.isValidNumber(hour) && hourAsNumber >= 0 && hourAsNumber < 24;
const minuteValid = locale$1.isValidNumber(minute) && minuteAsNumber >= 0 && minuteAsNumber < 60;
const secondValid = locale$1.isValidNumber(second) && secondAsNumber >= 0 && secondAsNumber < 60;
if ((hourValid && minuteValid && !second) || (hourValid && minuteValid && secondValid)) {
return true;
}
}
function isValidTimePart(value, part) {
if (part === "meridiem") {
return value === "AM" || value === "PM";
}
if (!locale$1.isValidNumber(value)) {
return false;
}
const valueAsNumber = Number(value);
return part === "hour" ? valueAsNumber >= 0 && valueAsNumber < 24 : valueAsNumber >= 0 && valueAsNumber < 60;
}
function localizeTimePart({ value, part, locale, numberingSystem }) {
if (!isValidTimePart(value, part)) {
return;
}
const valueAsNumber = parseInt(value);
const date = new Date(Date.UTC(0, 0, 0, part === "hour" ? valueAsNumber : part === "meridiem" ? (value === "AM" ? 0 : 12) : 0, part === "minute" ? valueAsNumber : 0, part === "second" ? valueAsNumber : 0));
if (!date) {
return;
}
const formatter = createLocaleDateTimeFormatter(locale, numberingSystem);
const parts = formatter.formatToParts(date);
return getLocalizedTimePart(part, parts);
}
function localizeTimeString({ value, locale, numberingSystem, includeSeconds = true }) {
if (!isValidTime(value)) {
return null;
}
const { hour, minute, second = "0" } = parseTimeString(value);
const dateFromTimeString = new Date(Date.UTC(0, 0, 0, parseInt(hour), parseInt(minute), parseInt(second)));
const formatter = createLocaleDateTimeFormatter(locale, numberingSystem, includeSeconds);
return formatter?.format(dateFromTimeString) || null;
}
function localizeTimeStringToParts({ value, locale, numberingSystem }) {
if (!isValidTime(value)) {
return null;
}
const { hour, minute, second = "0" } = parseTimeString(value);
const dateFromTimeString = new Date(Date.UTC(0, 0, 0, parseInt(hour), parseInt(minute), parseInt(second)));
if (dateFromTimeString) {
const formatter = createLocaleDateTimeFormatter(locale, numberingSystem);
const parts = formatter.formatToParts(dateFromTimeString);
return {
localizedHour: getLocalizedTimePart("hour", parts),
localizedHourSuffix: getLocalizedTimePart("hourSuffix", parts),
localizedMinute: getLocalizedTimePart("minute", parts),
localizedMinuteSuffix: getLocalizedTimePart("minuteSuffix", parts),
localizedSecond: getLocalizedTimePart("second", parts),
localizedSecondSuffix: getLocalizedTimePart("secondSuffix", parts),
localizedMeridiem: getLocalizedTimePart("meridiem", parts)
};
}
return null;
}
function getTimeParts({ value, locale, numberingSystem }) {
if (!isValidTime(value)) {
return null;
}
const { hour, minute, second = "0" } = parseTimeString(value);
const dateFromTimeString = new Date(Date.UTC(0, 0, 0, parseInt(hour), parseInt(minute), parseInt(second)));
if (dateFromTimeString) {
const formatter = createLocaleDateTimeFormatter(locale, numberingSystem);
const parts = formatter.formatToParts(dateFromTimeString);
return parts;
}
return null;
}
function parseTimeString(value) {
if (isValidTime(value)) {
const [hour, minute, second] = value.split(":");
return {
hour,
minute,
second
};
}
return {
hour: null,
minute: null,
second: null
};
}
function toISOTimeString(value, includeSeconds = true) {
if (!isValidTime(value)) {
return "";
}
const { hour, minute, second } = parseTimeString(value);
let isoTimeString = `${formatTimePart(parseInt(hour))}:${formatTimePart(parseInt(minute))}`;
if (includeSeconds) {
isoTimeString += `:${formatTimePart(parseInt((includeSeconds && second) || "0"))}`;
}
return isoTimeString;
}
const CSS$1 = {
toggleIcon: "toggle-icon"
};
var SECONDS_A_MINUTE = 60;
var SECONDS_A_HOUR = SECONDS_A_MINUTE * 60;
var SECONDS_A_DAY = SECONDS_A_HOUR * 24;
var SECONDS_A_WEEK = SECONDS_A_DAY * 7;
var MILLISECONDS_A_SECOND = 1e3;
var MILLISECONDS_A_MINUTE = SECONDS_A_MINUTE * MILLISECONDS_A_SECOND;
var MILLISECONDS_A_HOUR = SECONDS_A_HOUR * MILLISECONDS_A_SECOND;
var MILLISECONDS_A_DAY = SECONDS_A_DAY * MILLISECONDS_A_SECOND;
var MILLISECONDS_A_WEEK = SECONDS_A_WEEK * MILLISECONDS_A_SECOND; // English locales
var MS = 'millisecond';
var S = 'second';
var MIN = 'minute';
var H = 'hour';
var D = 'day';
var W = 'week';
var M = 'month';
var Q = 'quarter';
var Y = 'year';
var DATE = 'date';
var FORMAT_DEFAULT = 'YYYY-MM-DDTHH:mm:ssZ';
var INVALID_DATE_STRING = 'Invalid Date'; // regex
var REGEX_PARSE = /^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/;
var REGEX_FORMAT = /\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g;
// English [en]
// We don't need weekdaysShort, weekdaysMin, monthsShort in en.js locale
const en = {
name: 'en',
weekdays: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),
months: 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),
ordinal: function ordinal(n) {
var s = ['th', 'st', 'nd', 'rd'];
var v = n % 100;
return "[" + n + (s[(v - 20) % 10] || s[v] || s[0]) + "]";
}
};
const en$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
'default': en
});
var padStart = function padStart(string, length, pad) {
var s = String(string);
if (!s || s.length >= length) return string;
return "" + Array(length + 1 - s.length).join(pad) + string;
};
var padZoneStr = function padZoneStr(instance) {
var negMinutes = -instance.utcOffset();
var minutes = Math.abs(negMinutes);
var hourOffset = Math.floor(minutes / 60);
var minuteOffset = minutes % 60;
return "" + (negMinutes <= 0 ? '+' : '-') + padStart(hourOffset, 2, '0') + ":" + padStart(minuteOffset, 2, '0');
};
var monthDiff = function monthDiff(a, b) {
// function from moment.js in order to keep the same result
if (a.date() < b.date()) return -monthDiff(b, a);
var wholeMonthDiff = (b.year() - a.year()) * 12 + (b.month() - a.month());
var anchor = a.clone().add(wholeMonthDiff, M);
var c = b - anchor < 0;
var anchor2 = a.clone().add(wholeMonthDiff + (c ? -1 : 1), M);
return +(-(wholeMonthDiff + (b - anchor) / (c ? anchor - anchor2 : anchor2 - anchor)) || 0);
};
var absFloor = function absFloor(n) {
return n < 0 ? Math.ceil(n) || 0 : Math.floor(n);
};
var prettyUnit = function prettyUnit(u) {
var special = {
M: M,
y: Y,
w: W,
d: D,
D: DATE,
h: H,
m: MIN,
s: S,
ms: MS,
Q: Q
};
return special[u] || String(u || '').toLowerCase().replace(/s$/, '');
};
var isUndefined = function isUndefined(s) {
return s === undefined;
};
const U = {
s: padStart,
z: padZoneStr,
m: monthDiff,
a: absFloor,
p: prettyUnit,
u: isUndefined
};
var L = 'en'; // global locale
var Ls = {}; // global loaded locale
Ls[L] = en;
var isDayjs = function isDayjs(d) {
return d instanceof Dayjs;
}; // eslint-disable-line no-use-before-define
var parseLocale = function parseLocale(preset, object, isLocal) {
var l;
if (!preset) return L;
if (typeof preset === 'string') {
var presetLower = preset.toLowerCase();
if (Ls[presetLower]) {
l = presetLower;
}
if (object) {
Ls[presetLower] = object;
l = presetLower;
}
var presetSplit = preset.split('-');
if (!l && presetSplit.length > 1) {
return parseLocale(presetSplit[0]);
}
} else {
var name = preset.name;
Ls[name] = preset;
l = name;
}
if (!isLocal && l) L = l;
return l || !isLocal && L;
};
var dayjs = function dayjs(date, c) {
if (isDayjs(date)) {
return date.clone();
} // eslint-disable-next-line no-nested-ternary
var cfg = typeof c === 'object' ? c : {};
cfg.date = date;
cfg.args = arguments; // eslint-disable-line prefer-rest-params
return new Dayjs(cfg); // eslint-disable-line no-use-before-define
};
var wrapper = function wrapper(date, instance) {
return dayjs(date, {
locale: instance.$L,
utc: instance.$u,
x: instance.$x,
$offset: instance.$offset // todo: refactor; do not use this.$offset in you code
});
};
var Utils = U; // for plugin use
Utils.l = parseLocale;
Utils.i = isDayjs;
Utils.w = wrapper;
var parseDate = function parseDate(cfg) {
var date = cfg.date,
utc = cfg.utc;
if (date === null) return new Date(NaN); // null is invalid
if (Utils.u(date)) return new Date(); // today
if (date instanceof Date) return new Date(date);
if (typeof date === 'string' && !/Z$/i.test(date)) {
var d = date.match(REGEX_PARSE);
if (d) {
var m = d[2] - 1 || 0;
var ms = (d[7] || '0').substring(0, 3);
if (utc) {
return new Date(Date.UTC(d[1], m, d[3] || 1, d[4] || 0, d[5] || 0, d[6] || 0, ms));
}
return new Date(d[1], m, d[3] || 1, d[4] || 0, d[5] || 0, d[6] || 0, ms);
}
}
return new Date(date); // everything else
};
var Dayjs = /*#__PURE__*/function () {
function Dayjs(cfg) {
this.$L = parseLocale(cfg.locale, null, true);
this.parse(cfg); // for plugin
}
var _proto = Dayjs.prototype;
_proto.parse = function parse(cfg) {
this.$d = parseDate(cfg);
this.$x = cfg.x || {};
this.init();
};
_proto.init = function init() {
var $d = this.$d;
this.$y = $d.getFullYear();
this.$M = $d.getMonth();
this.$D = $d.getDate();
this.$W = $d.getDay();
this.$H = $d.getHours();
this.$m = $d.getMinutes();
this.$s = $d.getSeconds();
this.$ms = $d.getMilliseconds();
} // eslint-disable-next-line class-methods-use-this
;
_proto.$utils = function $utils() {
return Utils;
};
_proto.isValid = function isValid() {
return !(this.$d.toString() === INVALID_DATE_STRING);
};
_proto.isSame = function isSame(that, units) {
var other = dayjs(that);
return this.startOf(units) <= other && other <= this.endOf(units);
};
_proto.isAfter = function isAfter(that, units) {
return dayjs(that) < this.startOf(units);
};
_proto.isBefore = function isBefore(that, units) {
return this.endOf(units) < dayjs(that);
};
_proto.$g = function $g(input, get, set) {
if (Utils.u(input)) return this[get];
return this.set(set, input);
};
_proto.unix = function unix() {
return Math.floor(this.valueOf() / 1000);
};
_proto.valueOf = function valueOf() {
// timezone(hour) * 60 * 60 * 1000 => ms
return this.$d.getTime();
};
_proto.startOf = function startOf(units, _startOf) {
var _this = this;
// startOf -> endOf
var isStartOf = !Utils.u(_startOf) ? _startOf : true;
var unit = Utils.p(units);
var instanceFactory = function instanceFactory(d, m) {
var ins = Utils.w(_this.$u ? Date.UTC(_this.$y, m, d) : new Date(_this.$y, m, d), _this);
return isStartOf ? ins : ins.endOf(D);
};
var instanceFactorySet = function instanceFactorySet(method, slice) {
var argumentStart = [0, 0, 0, 0];
var argumentEnd = [23, 59, 59, 999];
return Utils.w(_this.toDate()[method].apply( // eslint-disable-line prefer-spread
_this.toDate('s'), (isStartOf ? argumentStart : argumentEnd).slice(slice)), _this);
};
var $W = this.$W,
$M = this.$M,
$D = this.$D;
var utcPad = "set" + (this.$u ? 'UTC' : '');
switch (unit) {
case Y:
return isStartOf ? instanceFactory(1, 0) : instanceFactory(31, 11);
case M:
return isStartOf ? instanceFactory(1, $M) : instanceFactory(0, $M + 1);
case W:
{
var weekStart = this.$locale().weekStart || 0;
var gap = ($W < weekStart ? $W + 7 : $W) - weekStart;
return instanceFactory(isStartOf ? $D - gap : $D + (6 - gap), $M);
}
case D:
case DATE:
return instanceFactorySet(utcPad + "Hours", 0);
case H:
return instanceFactorySet(utcPad + "Minutes", 1);
case MIN:
return instanceFactorySet(utcPad + "Seconds", 2);
case S:
return instanceFactorySet(utcPad + "Milliseconds", 3);
default:
return this.clone();
}
};
_proto.endOf = function endOf(arg) {
return this.startOf(arg, false);
};
_proto.$set = function $set(units, _int) {
var _C$D$C$DATE$C$M$C$Y$C;
// private set
var unit = Utils.p(units);
var utcPad = "set" + (this.$u ? 'UTC' : '');
var name = (_C$D$C$DATE$C$M$C$Y$C = {}, _C$D$C$DATE$C$M$C$Y$C[D] = utcPad + "Date", _C$D$C$DATE$C$M$C$Y$C[DATE] = utcPad + "Date", _C$D$C$DATE$C$M$C$Y$C[M] = utcPad + "Month", _C$D$C$DATE$C$M$C$Y$C[Y] = utcPad + "FullYear", _C$D$C$DATE$C$M$C$Y$C[H] = utcPad + "Hours", _C$D$C$DATE$C$M$C$Y$C[MIN] = utcPad + "Minutes", _C$D$C$DATE$C$M$C$Y$C[S] = utcPad + "Seconds", _C$D$C$DATE$C$M$C$Y$C[MS] = utcPad + "Milliseconds", _C$D$C$DATE$C$M$C$Y$C)[unit];
var arg = unit === D ? this.$D + (_int - this.$W) : _int;
if (unit === M || unit === Y) {
// clone is for badMutable plugin
var date = this.clone().set(DATE, 1);
date.$d[name](arg);
date.init();
this.$d = date.set(DATE, Math.min(this.$D, date.daysInMonth())).$d;
} else if (name) this.$d[name](arg);
this.init();
return this;
};
_proto.set = function set(string, _int2) {
return this.clone().$set(string, _int2);
};
_proto.get = function get(unit) {
return this[Utils.p(unit)]();
};
_proto.add = function add(number, units) {
var _this2 = this,
_C$MIN$C$H$C$S$unit;
number = Number(number); // eslint-disable-line no-param-reassign
var unit = Utils.p(units);
var instanceFactorySet = function instanceFactorySet(n) {
var d = dayjs(_this2);
return Utils.w(d.date(d.date() + Math.round(n * number)), _this2);
};
if (unit === M) {
return this.set(M, this.$M + number);
}
if (unit === Y) {
return this.set(Y, this.$y + number);
}
if (unit === D) {
return instanceFactorySet(1);
}
if (unit === W) {
return instanceFactorySet(7);
}
var step = (_C$MIN$C$H$C$S$unit = {}, _C$MIN$C$H$C$S$unit[MIN] = MILLISECONDS_A_MINUTE, _C$MIN$C$H$C$S$unit[H] = MILLISECONDS_A_HOUR, _C$MIN$C$H$C$S$unit[S] = MILLISECONDS_A_SECOND, _C$MIN$C$H$C$S$unit)[unit] || 1; // ms
var nextTimeStamp = this.$d.getTime() + number * step;
return Utils.w(nextTimeStamp, this);
};
_proto.subtract = function subtract(number, string) {
return this.add(number * -1, string);
};
_proto.format = function format(formatStr) {
var _this3 = this;
var locale = this.$locale();
if (!this.isValid()) return locale.invalidDate || INVALID_DATE_STRING;
var str = formatStr || FORMAT_DEFAULT;
var zoneStr = Utils.z(this);
var $H = this.$H,
$m = this.$m,
$M = this.$M;
var weekdays = locale.weekdays,
months = locale.months,
meridiem = locale.meridiem;
var getShort = function getShort(arr, index, full, length) {
return arr && (arr[index] || arr(_this3, str)) || full[index].slice(0, length);
};
var get$H = function get$H(num) {
return Utils.s($H % 12 || 12, num, '0');
};
var meridiemFunc = meridiem || function (hour, minute, isLowercase) {
var m = hour < 12 ? 'AM' : 'PM';
return isLowercase ? m.toLowerCase() : m;
};
var matches = {
YY: String(this.$y).slice(-2),
YYYY: Utils.s(this.$y, 4, '0'),
M: $M + 1,
MM: Utils.s($M + 1, 2, '0'),
MMM: getShort(locale.monthsShort, $M, months, 3),
MMMM: getShort(months, $M),
D: this.$D,
DD: Utils.s(this.$D, 2, '0'),
d: String(this.$W),
dd: getShort(locale.weekdaysMin, this.$W, weekdays, 2),
ddd: getShort(locale.weekdaysShort, this.$W, weekdays, 3),
dddd: weekdays[this.$W],
H: String($H),
HH: Utils.s($H, 2, '0'),
h: get$H(1),
hh: get$H(2),
a: meridiemFunc($H, $m, true),
A: meridiemFunc($H, $m, false),
m: String($m),
mm: Utils.s($m, 2, '0'),
s: String(this.$s),
ss: Utils.s(this.$s, 2, '0'),
SSS: Utils.s(this.$ms, 3, '0'),
Z: zoneStr // 'ZZ' logic below
};
return str.replace(REGEX_FORMAT, function (match, $1) {
return $1 || matches[match] || zoneStr.replace(':', '');
}); // 'ZZ'
};
_proto.utcOffset = function utcOffset() {
// Because a bug at FF24, we're rounding the timezone offset around 15 minutes
// https://github.com/moment/moment/pull/1871
return -Math.round(this.$d.getTimezoneOffset() / 15) * 15;
};
_proto.diff = function diff(input, units, _float) {
var _C$Y$C$M$C$Q$C$W$C$D$;
var unit = Utils.p(units);
var that = dayjs(input);
var zoneDelta = (that.utcOffset() - this.utcOffset()) * MILLISECONDS_A_MINUTE;
var diff = this - that;
var result = Utils.m(this, that);
result = (_C$Y$C$M$C$Q$C$W$C$D$ = {}, _C$Y$C$M$C$Q$C$W$C$D$[Y] = result / 12, _C$Y$C$M$C$Q$C$W$C$D$[M] = result, _C$Y$C$M$C$Q$C$W$C$D$[Q] = result / 3, _C$Y$C$M$C$Q$C$W$C$D$[W] = (diff - zoneDelta) / MILLISECONDS_A_WEEK, _C$Y$C$M$C$Q$C$W$C$D$[D] = (diff - zoneDelta) / MILLISECONDS_A_DAY, _C$Y$C$M$C$Q$C$W$C$D$[H] = diff / MILLISECONDS_A_HOUR, _C$Y$C$M$C$Q$C$W$C$D$[MIN] = diff / MILLISECONDS_A_MINUTE, _C$Y$C$M$C$Q$C$W$C$D$[S] = diff / MILLISECONDS_A_SECOND, _C$Y$C$M$C$Q$C$W$C$D$)[unit] || diff; // milliseconds
return _float ? result : Utils.a(result);
};
_proto.daysInMonth = function daysInMonth() {
return this.endOf(M).$D;
};
_proto.$locale = function $locale() {
// get locale object
return Ls[this.$L];
};
_proto.locale = function locale(preset, object) {
if (!preset) return this.$L;
var that = this.clone();
var nextLocaleName = parseLocale(preset, object, true);
if (nextLocaleName) that.$L = nextLocaleName;
return that;
};
_proto.clone = function clone() {
return Utils.w(this.$d, this);
};
_proto.toDate = function toDate() {
return new Date(this.valueOf());
};
_proto.toJSON = function toJSON() {
return this.isValid() ? this.toISOString() : null;
};
_proto.toISOString = function toISOString() {
// ie 8 return
// new Dayjs(this.valueOf() + this.$d.getTimezoneOffset() * 60000)
// .format('YYYY-MM-DDTHH:mm:ss.SSS[Z]')
return this.$d.toISOString();
};
_proto.toString = function toString() {
return this.$d.toUTCString();
};
return Dayjs;
}();
var proto = Dayjs.prototype;
dayjs.prototype = proto;
[['$ms', MS], ['$s', S], ['$m', MIN], ['$H', H], ['$W', D], ['$M', M], ['$y', Y], ['$D', DATE]].forEach(function (g) {
proto[g[1]] = function (input) {
return this.$g(input, g[0], g[1]);
};
});
dayjs.extend = function (plugin, option) {
if (!plugin.$i) {
// install plugin only once
plugin(option, Dayjs, dayjs);
plugin.$i = true;
}
return dayjs;
};
dayjs.locale = parseLocale;
dayjs.isDayjs = isDayjs;
dayjs.unix = function (timestamp) {
return dayjs(timestamp * 1e3);
};
dayjs.en = Ls[L];
dayjs.Ls = Ls;
dayjs.p = {};
// eslint-disable-next-line import/prefer-default-export
var t = function t(format) {
return format.replace(/(\[[^\]]+])|(MMMM|MM|DD|dddd)/g, function (_, a, b) {
return a || b.slice(1);
});
};
var englishFormats = {
LTS: 'h:mm:ss A',
LT: 'h:mm A',
L: 'MM/DD/YYYY',
LL: 'MMMM D, YYYY',
LLL: 'MMMM D, YYYY h:mm A',
LLLL: 'dddd, MMMM D, YYYY h:mm A'
};
var u = function u(formatStr, formats) {
return formatStr.replace(/(\[[^\]]+])|(LTS?|l{1,4}|L{1,4})/g, function (_, a, b) {
var B = b && b.toUpperCase();
return a || formats[b] || englishFormats[b] || t(formats[B]);
});
};
var formattingTokens = /(\[[^[]*\])|([-_:/.,()\s]+)|(A|a|YYYY|YY?|MM?M?M?|Do|DD?|hh?|HH?|mm?|ss?|S{1,3}|z|ZZ?)/g;
var match1 = /\d/; // 0 - 9
var match2 = /\d\d/; // 00 - 99
var match3 = /\d{3}/; // 000 - 999
var match4 = /\d{4}/; // 0000 - 9999
var match1to2 = /\d\d?/; // 0 - 99
var matchSigned = /[+-]?\d+/; // -inf - inf
var matchOffset = /[+-]\d\d:?(\d\d)?|Z/; // +00:00 -00:00 +0000 or -0000 +00 or Z
var matchWord = /\d*[^-_:/,()\s\d]+/; // Word
var locale = {};
var parseTwoDigitYear = function parseTwoDigitYear(input) {
input = +input;
return input + (input > 68 ? 1900 : 2000);
};
function offsetFromString(string) {
if (!string) return 0;
if (string === 'Z') return 0;
var parts = string.match(/([+-]|\d\d)/g);
var minutes = +(parts[1] * 60) + (+parts[2] || 0);
return minutes === 0 ? 0 : parts[0] === '+' ? -minutes : minutes; // eslint-disable-line no-nested-ternary
}
var addInput = function addInput(property) {
return function (input) {
this[property] = +input;
};
};
var zoneExpressions = [matchOffset, function (input) {
var zone = this.zone || (this.zone = {});
zone.offset = offsetFromString(input);
}];
var getLocalePart = function getLocalePart(name) {
var part = locale[name];
return part && (part.indexOf ? part : part.s.concat(part.f));
};
var meridiemMatch = function meridiemMatch(input, isLowerCase) {
var isAfternoon;
var _locale = locale,
meridiem = _locale.meridiem;
if (!meridiem) {
isAfternoon = input === (isLowerCase ? 'pm' : 'PM');
} else {
for (var i = 1; i <= 24; i += 1) {
// todo: fix input === meridiem(i, 0, isLowerCase)
if (input.indexOf(meridiem(i, 0, isLowerCase)) > -1) {
isAfternoon = i > 12;
break;
}
}
}
return isAfternoon;
};
var expressions = {
A: [matchWord, function (input) {
this.afternoon = meridiemMatch(input, false);
}],
a: [matchWord, function (input) {
this.afternoon = meridiemMatch(input, true);
}],
S: [match1, function (input) {
this.milliseconds = +input * 100;
}],
SS: [match2, function (input) {
this.milliseconds = +input * 10;
}],
SSS: [match3, function (input) {
this.milliseconds = +input;
}],
s: [match1to2, addInput('seconds')],
ss: [match1to2, addInput('seconds')],
m: [match1to2, addInput('minutes')],
mm: [match1to2, addInput('minutes')],
H: [match1to2, addInput('hours')],
h: [match1to2, addInput('hours')],
HH: [match1to2, addInput('hours')],
hh: [match1to2, addInput('hours')],
D: [match1to2, addInput('day')],
DD: [match2, addInput('day')],
Do: [matchWord, function (input) {
var _locale2 = locale,
ordinal = _locale2.ordinal;
var _input$match = input.match(/\d+/);
this.day = _input$match[0];
if (!ordinal) return;
for (var i = 1; i <= 31; i += 1) {
if (ordinal(i).replace(/\[|\]/g, '') === input) {
this.day = i;
}
}
}],
M: [match1to2, addInput('month')],
MM: [match2, addInput('month')],
MMM: [matchWord, function (input) {
var months = getLocalePart('months');
var monthsShort = getLocalePart('monthsShort');
var matchIndex = (monthsShort || months.map(function (_) {
return _.slice(0, 3);
})).indexOf(input) + 1;
if (matchIndex < 1) {
throw new Error();
}
this.month = matchIndex % 12 || matchIndex;
}],
MMMM: [matchWord, function (input) {
var months = getLocalePart('months');
var matchIndex = months.indexOf(input) + 1;
if (matchIndex < 1) {
throw new Error();
}
this.month = matchIndex % 12 || matchIndex;
}],
Y: [matchSigned, addInput('year')],
YY: [match2, function (input) {
this.year = parseTwoDigitYear(input);
}],
YYYY: [match4, addInput('year')],
Z: zoneExpressions,
ZZ: zoneExpressions
};
function correctHours(time) {
var afternoon = time.afternoon;
if (afternoon !== undefined) {
var hours = time.hours;
if (afternoon) {
if (hours < 12) {
time.hours += 12;
}
} else if (hours === 12) {
time.hours = 0;
}
delete time.afternoon;
}
}
function makeParser(format) {
format = u(format, locale && locale.formats);
var array = format.match(formattingTokens);
var length = array.length;
for (var i = 0; i < length; i += 1) {
var token = array[i];
var parseTo = expressions[token];
var regex = parseTo && parseTo[0];
var parser = parseTo && parseTo[1];
if (parser) {
array[i] = {
regex: regex,
parser: parser
};
} else {
array[i] = token.replace(/^\[|\]$/g, '');
}
}
return function (input) {
var time = {};
for (var _i = 0, start = 0; _i < length; _i += 1) {
var _token = array[_i];
if (typeof _token === 'string') {
start += _token.length;
} else {
var _regex = _token.regex,
_parser = _token.parser;
var part = input.slice(start);
var match = _regex.exec(part);
var value = match[0];
_parser.call(time, value);
input = input.replace(value, '');
}
}
correctHours(time);
return time;
};
}
var parseFormattedInput = function parseFormattedInput(input, format, utc) {
try {
if (['x', 'X'].indexOf(format) > -1) return new Date((format === 'X' ? 1000 : 1) * input);
var parser = makeParser(format);
var _parser2 = parser(input),
year = _parser2.year,
month = _parser2.month,
day = _parser2.day,
hours = _parser2.hours,
minutes = _parser2.minutes,
seconds = _parser2.seconds,
milliseconds = _parser2.milliseconds,
zone = _parser2.zone;
var now = new Date();
var d = day || (!year && !month ? now.getDate() : 1);
var y = year || now.getFullYear();
var M = 0;
if (!(year && !month)) {
M = month > 0 ? month - 1 : now.getMonth();
}
var h = hours || 0;
var m = minutes || 0;
var s = seconds || 0;
var ms = milliseconds || 0;
if (zone) {
return new Date(Date.UTC(y, M, d, h, m, s, ms + zone.offset * 60 * 1000));
}
if (utc) {
return new Date(Date.UTC(y, M, d, h, m, s, ms));
}
return new Date(y, M, d, h, m, s, ms);
} catch (e) {
return new Date(''); // Invalid Date
}
};
const customParseFormat = (function (o, C, d) {
d.p.customParseFormat = true;
if (o && o.parseTwoDigitYear) {
parseTwoDigitYear = o.parseTwoDigitYear;
}
var proto = C.prototype;
var oldParse = proto.parse;
proto.parse = function (cfg) {
var date = cfg.date,
utc = cfg.utc,
args = cfg.args;
this.$u = utc;
var format = args[1];
if (typeof format === 'string') {
var isStrictWithoutLocale = args[2] === true;
var isStrictWithLocale = args[3] === true;
var isStrict = isStrictWithoutLocale || isStrictWithLocale;
var pl = args[2];
if (isStrictWithLocale) {
pl = args[2];
}
locale = this.$locale();
if (!isStrictWithoutLocale && pl) {
locale = d.Ls[pl];
}
this.$d = parseFormattedInput(date, format, utc);
this.init();
if (pl && pl !== true) this.$L = this.locale(pl).$L; // use != to treat
// input number 1410715640579 and format string '1410715640579' equal
// eslint-disable-next-line eqeqeq
if (isStrict && date != this.format(format)) {
this.$d = new Date('');
} // reset global locale to make parallel unit test
locale = {};
} else if (format instanceof Array) {
var len = format.length;
for (var i = 1; i <= len; i += 1) {
args[1] = format[i - 1];
var result = d.apply(this, args);
if (result.isValid()) {
this.$d = result.$d;
this.$L = result.$L;
this.init();
break;
}
if (i === len) this.$d = new Date('');
}
} else {
oldParse.call(this, cfg);
}
};
});
const localeData = (function (o, c, dayjs) {
// locale needed later
var proto = c.prototype;
var getLocalePart = function getLocalePart(part) {
return part && (part.indexOf ? part : part.s);
};
var getShort = function getShort(ins, target, full, num, localeOrder) {
var locale = ins.name ? ins : ins.$locale();
var targetLocale = getLocalePart(locale[target]);
var fullLocale = getLocalePart(locale[full]);
var result = targetLocale || fullLocale.map(function (f) {
return f.slice(0, num);
});
if (!localeOrder) return result;
var weekStart = locale.weekStart;
return result.map(function (_, index) {
return result[(index + (weekStart || 0)) % 7];
});
};
var getDayjsLocaleObject = function getDayjsLocaleObject() {
return dayjs.Ls[dayjs.locale()];
};
var getLongDateFormat = function getLongDateFormat(l, format) {
return l.formats[format] || t(l.formats[format.toUpperCase()]);
};
var localeData = function localeData() {
var _this = this;
return {
months: function months(instance) {
return instance ? instance.format('MMMM') : getShort(_this, 'months');
},
monthsShort: function monthsShort(instance) {
return instance ? instance.format('MMM') : getShort(_this, 'monthsShort', 'months', 3);
},
firstDayOfWeek: function firstDayOfWeek() {
return _this.$locale().weekStart || 0;
},
weekdays: function weekdays(instance) {
return instance ? instance.format('dddd') : getShort(_this, 'weekdays');
},
weekdaysMin: function weekdaysMin(instance) {
return instance ? instance.format('dd') : getShort(_this, 'weekdaysMin', 'weekdays', 2);
},
weekdaysShort: function weekdaysShort(instance) {
return instance ? instance.format('ddd') : getShort(_this, 'weekdaysShort', 'weekdays', 3);
},
longDateFormat: function longDateFormat(format) {
return getLongDateFormat(_this.$locale(), format);
},
meridiem: this.$locale().meridiem,
ordinal: this.$locale().ordinal
};
};
proto.localeData = function () {
return localeData.bind(this)();
};
dayjs.localeData = function () {
var localeObject = getDayjsLocaleObject();
return {
firstDayOfWeek: function firstDayOfWeek() {
return localeObject.weekStart || 0;
},
weekdays: function weekdays() {
return dayjs.weekdays();
},
weekdaysShort: function weekdaysShort() {
return dayjs.weekdaysShort();
},
weekdaysMin: function weekdaysMin() {
return dayjs.weekdaysMin();
},
months: function months() {
return dayjs.months();
},
monthsShort: function monthsShort() {
return dayjs.monthsShort();
},
longDateFormat: function longDateFormat(format) {
return getLongDateFormat(localeObject, format);
},
meridiem: localeObject.meridiem,
ordinal: localeObject.ordinal
};
};
dayjs.months = function () {
return getShort(getDayjsLocaleObject(), 'months');
};
dayjs.monthsShort = function () {
return getShort(getDayjsLocaleObject(), 'monthsShort', 'months', 3);
};
dayjs.weekdays = function (localeOrder) {
return getShort(getDayjsLocaleObject(), 'weekdays', null, null, localeOrder);
};
dayjs.weekdaysShort = function (localeOrder) {
return getShort(getDayjsLocaleObject(), 'weekdaysShort', 'weekdays', 3, localeOrder);
};
dayjs.weekdaysMin = function (localeOrder) {
return getShort(getDayjsLocaleObject(), 'weekdaysMin', 'weekdays', 2, localeOrder);
};
});
const localizedFormat = (function (o, c, d) {
var proto = c.prototype;
var oldFormat = proto.format;
d.en.formats = englishFormats;
proto.format = function (formatStr) {
if (formatStr === void 0) {
formatStr = FORMAT_DEFAULT;
}
var _this$$locale = this.$locale(),
_this$$locale$formats = _this$$locale.formats,
formats = _this$$locale$formats === void 0 ? {} : _this$$locale$formats;
var result = u(formatStr, formats);
return oldFormat.call(this, result);
};
});
// Plugin template from https://day.js.org/docs/en/plugin/plugin
const preParsePostFormat = (function (option, dayjsClass) {
var oldParse = dayjsClass.prototype.parse;
dayjsClass.prototype.parse = function (cfg) {
if (typeof cfg.date === 'string') {
var locale = this.$locale();
cfg.date = locale && locale.preparse ? locale.preparse(cfg.date) : cfg.date;
} // original parse result
return oldParse.bind(this)(cfg);
}; // // overriding existing API
// // e.g. extend dayjs().format()
var oldFormat = dayjsClass.prototype.format;
dayjsClass.prototype.format = function () {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
// original format result
var result = oldFormat.call.apply(oldFormat, [this].concat(args)); // return modified result
var locale = this.$locale();
return locale && locale.postformat ? locale.postformat(result) : result;
};
var oldFromTo = dayjsClass.prototype.fromToBase;
if (oldFromTo) {
dayjsClass.prototype.fromToBase = function (input, withoutSuffix, instance, isFrom) {
var locale = this.$locale() || instance.$locale(); // original format result
return oldFromTo.call(this, input, withoutSuffix, instance, isFrom, locale && locale.postformat);
};
}
});
const updateLocale = (function (option, Dayjs, dayjs) {
dayjs.updateLocale = function (locale, customConfig) {
var localeList = dayjs.Ls;
var localeConfig = localeList[locale];
if (!localeConfig) return;
var customConfigKeys = customConfig ? Object.keys(customConfig) : [];
customConfigKeys.forEach(function (c) {
localeConfig[c] = customConfig[c];
});
return localeConfig; // eslint-disable-line consistent-return
};
});
const inputTimePickerCss = "@keyframes in{0%{opacity:0}100%{opacity:1}}@keyframes in-down{0%{opacity:0;transform:translate3D(0, -5px, 0)}100%{opacity:1;transform:translate3D(0, 0, 0)}}@keyframes in-up{0%{opacity:0;transform:translate3D(0, 5px, 0)}100%{opacity:1;transform:translate3D(0, 0, 0)}}@keyframes in-right{0%{opacity:0;transform:translate3D(-5px, 0, 0)}100%{opacity:1;transform:translate3D(0, 0, 0)}}@keyframes in-left{0%{opacity:0;transform:translate3D(5px, 0, 0)}100%{opacity:1;transform:translate3D(0, 0, 0)}}@keyframes in-scale{0%{opacity:0;transform:scale3D(0.95, 0.95, 1)}100%{opacity:1;transform:scale3D(1, 1, 1)}}:root{--calcite-animation-timing:calc(150ms * var(--calcite-internal-duration-factor));--calcite-internal-duration-factor:var(--calcite-duration-factor, 1);--calcite-internal-animation-timing-fast:calc(100ms * var(--calcite-internal-duration-factor));--calcite-internal-animation-timing-medium:calc(200ms * var(--calcite-internal-duration-factor));--calcite-internal-animation-timing-slow:calc(300ms * var(--calcite-internal-duration-factor))}.calcite-animate{opacity:0;animation-fill-mode:both;animation-duration:var(--calcite-animation-timing)}.calcite-animate__in{animation-name:in}.calcite-animate__in-down{animation-name:in-down}.calcite-animate__in-up{animation-name:in-up}.calcite-animate__in-right{animation-name:in-right}.calcite-animate__in-left{animation-name:in-left}.calcite-animate__in-scale{animation-name:in-scale}@media (prefers-reduced-motion: reduce){:root{--calcite-internal-duration-factor:0.01}}:root{--calcite-floating-ui-transition:var(--calcite-animation-timing);--calcite-floating-ui-z-index:var(--calcite-app-z-index-dropdown)}:host([hidden]){display:none}:host([disabled]){cursor:default;-webkit-user-select:none;user-select:none;opacity:var(--calcite-ui-opacity-disabled)}:host([disabled]) *,:host([disabled]) ::slotted(*){pointer-events:none}:host{display:inline-block;-webkit-user-select:none;user-select:none}:host([disabled]) ::slotted([calcite-hydrated][disabled]),:host([disabled]) [calcite-hydrated][disabled]{opacity:1}::slotted(input[slot=hidden-form-input]){margin:0 !important;opacity:0 !important;outline:none !important;padding:0 !important;position:absolute !important;inset:0 !important;transform:none !important;-webkit-appearance:none !important;z-index:-1 !important}:host([scale=s]){--calcite-toggle-spacing:0.5rem}:host([scale=m]){--calcite-toggle-spacing:0.75rem}:host([scale=l]){--calcite-toggle-spacing:1rem}.input-wrapper{position:relative}.toggle-icon{position:absolute;display:flex;inline-size:1rem;cursor:pointer;align-items:center;inset-inline-end:0;inset-block:0;padding-inline:var(--calcite-toggle-spacing)}";
// some bundlers (e.g., Webpack) need dynamic import paths to be static
const supportedDayJsLocaleToLocaleConfigImport = new Map([
["ar", () => Promise.resolve().then(function () { return require('./ar-2289868b.js'); })],
["bg", () => Promise.resolve().then(function () { return require('./bg-b08dd8f3.js'); })],
["bs", () => Promise.resolve().then(function () { return require('./bs-e9791d9c.js'); })],
["ca", () => Promise.resolve().then(function () { return require('./ca-dfdbe040.js'); })],
["cs", () => Promise.resolve().then(function () { return require('./cs-2fef5628.js'); })],
["da", () => Promise.resolve().then(function () { return require('./da-3ebbf817.js'); })],
["de", () => Promise.resolve().then(function () { return require('./de-08b4ba5c.js'); })],
["de-at", () => Promise.resolve().then(function () { return require('./de-at-97957f64.js'); })],
["de-ch", () => Promise.resolve().then(function () { return require('./de-ch-e8718578.js'); })],
["el", () => Promise.resolve().then(function () { return require('./el-450199f8.js'); })],
["en", () => Promise.resolve().then(function () { return en$1; })],
["en-au", () => Promise.resolve().then(function () { return require('./en-au-b26a1ded.js'); })],
["en-ca", () => Promise.resolve().then(function () { return require('./en-ca-a1264f94.js'); })],
["en-gb", () => Promise.resolve().then(function () { return require('./en-gb-809a4db2.js'); })],
["es", () => Promise.resolve().then(function () { return require('./es-494ac985.js'); })],
["es-mx", () => Promise.resolve().then(function () { return require('./es-mx-fbbf5320.js'); })],
["et", () => Promise.resolve().then(function () { return require('./et-155e9580.js'); })],
["fi", () => Promise.resolve().then(function () { return require('./fi-e939ea9d.js'); })],
["fr", () => Promise.resolve().then(function () { return require('./fr-2c7d9e30.js'); })],
["fr-ch", () => Promise.resolve().then(function () { return require('./fr-ch-76447f1b.js'); })],
["he", () => Promise.resolve().then(function () { return require('./he-7bc7d996.js'); })],
["hi", () => Promise.resolve().then(function () { return require('./hi-4d59acf6.js'); })],
["hr", () => Promise.resolve().then(function () { return require('./hr-a00f62a8.js'); })],
["hu", () => Promise.resolve().then(function () { return require('./hu-937261d5.js'); })],
["id", () => Promise.resolve().then(function () { return require('./id-69199b81.js'); })],
["it", () => Promise.resolve().then(function () { return require('./it-45e3e844.js'); })],
["it-ch", () => Promise.resolve().then(function () { return require('./it-ch-77bff418.js'); })],
["ja", () => Promise.resolve().then(function () { return require('./ja-f10ef4d4.js'); })],
["ko", () => Promise.resolve().then(function () { return require('./ko-8687cb8b.js'); })],
["lt", () => Promise.resolve().then(function () { return require('./lt-17f00030.js'); })],
["lv", () => Promise.resolve().then(function () { return require('./lv-150c7a9b.js'); })],
["mk", () => Promise.resolve().then(function () { return require('./mk-f28752fd.js'); })],
["nl", () => Promise.resolve().then(function () { return require('./nl-e3033021.js'); })],
["nb", () => Promise.resolve().then(function () { return require('./nb-958650ea.js'); })],
["pl", () => Promise.resolve().then(function () { return require('./pl-60f08bd5.js'); })],
["pt", () => Promise.resolve().then(function () { return require('./pt-1642d822.js'); })],
["pt-br", () => Promise.resolve().then(function () { return require('./pt-br-a7d60174.js'); })],
["ro", () => Promise.resolve().then(function () { return require('./ro-c6e43008.js'); })],
["ru", () => Promise.resolve().then(function () { return require('./ru-339ffe2f.js'); })],
["sk", () => Promise.resolve().then(function () { return require('./sk-d4560630.js'); })],
["sl", () => Promise.resolve().then(function () { return require('./sl-f8a2dfed.js'); })],
["sr", () => Promise.resolve().then(function () { return require('./sr-b3fb3ad9.js'); })],
["sv", () => Promise.resolve().then(function () { return require('./sv-019f208c.js'); })],
["th", () => Promise.resolve().then(function () { return require('./th-42ad9f21.js'); })],
["tr", () => Promise.resolve().then(function () { return require('./tr-268cd169.js'); })],
["uk", () => Promise.resolve().then(function () { return require('./uk-33c7557b.js'); })],
["vi", () => Promise.resolve().then(function () { return require('./vi-74660052.js'); })],
["zh-cn", () => Promise.resolve().then(function () { return require('./zh-cn-c25e09b9.js'); })],
["zh-hk", () => Promise.resolve().then(function () { return require('./zh-hk-2042e2b3.js'); })],
["zh-tw", () => Promise.resolve().then(function () { return require('./zh-tw-92fe6a60.js'); })]
]);
dayjs.extend(customParseFormat);
dayjs.extend(localeData);
dayjs.extend(localizedFormat);
dayjs.extend(preParsePostFormat);
dayjs.extend(updateLocale);
const InputTimePicker = class {
constructor(hostRef) {
index.registerInstance(this, hostRef);
this.calciteInputTimePickerChange = index.createEvent(this, "calciteInputTimePickerChange", 7);
this.focusOnOpen = false;
this.dialogId = `time-picker-dialog--${guid.guid()}`;
/** whether the value of the input was changed as a result of user typing or not */
this.userChangedValue = false;
this.referenceElementId = `input-time-picker-${guid.guid()}`;
//--------------------------------------------------------------------------
//
// Event Listeners
//
//--------------------------------------------------------------------------
this.hostBlurHandler = () => {
const inputValue = this.calciteInputEl.value;
const delocalizedInputValue = this.delocalizeTimeString(inputValue);
if (!delocalizedInputValue) {
this.setValue("");
return;
}
if (delocalizedInputValue !== this.value) {
this.setValue(delocalizedInputValue);
}
const localizedTimeString = localizeTimeString({
value: this.value,
locale: this.effectiveLocale,
numberingSystem: this.numberingSystem,
includeSeconds: this.shouldIncludeSeconds()
});
if (localizedTimeString !== inputValue) {
this.setInputValue(localizedTimeString);
}
this.deactivate();
};
this.calciteInternalInputFocusHandler = (event) => {
if (!this.readOnly) {
event.stopPropagation();
}
};
this.calciteInternalInputInputHandler = (event) => {
const { effectiveLocale: locale, numberingSystem } = this;
if (numberingSystem && numberingSystem !== "latn") {
const target = event.target;
locale$1.numberStringFormatter.numberFormatOptions = {
locale,
numberingSystem,
useGrouping: false
};
const valueInNumberingSystem = locale$1.numberStringFormatter
.delocalize(target.value)
.split("")
.map((char) => key.numberKeys.includes(char)
? locale$1.numberStringFormatter.numberFormatter.format(Number(char))
: char)
.join("");
this.setInputValue(valueInNumberingSystem);
}
};
this.timePickerChangeHandler = (event) => {
event.stopPropagation();
const target = event.target;
const value = target.value;
const includeSeconds = this.shouldIncludeSeconds();
this.setValue(toISOTimeString(value, includeSeconds));
this.setInputValue(localizeTimeString({
value,
locale: this.effectiveLocale,
numberingSystem: this.numberingSystem,
includeSeconds
}));
};
this.popoverCloseHandler = () => {
focusTrapComponent.deactivateFocusTrap(this, {
onDeactivate: () => {
this.calciteInputEl.setFocus();
this.focusOnOpen = false;
}
});
};
this.popoverOpenHandler = () => {
focusTrapComponent.activateFocusTrap(this, {
onActivate: () => {
if (this.focusOnOpen) {
this.calciteTimePickerEl.setFocus();
this.focusOnOpen = false;
}
}
});
};
this.keyDownHandler = (event) => {
const { defaultPrevented, key } = event;
if (defaultPrevented) {
return;
}
if (key === "Enter") {
if (form.submitForm(this)) {
event.preventDefault();
this.calciteInputEl.setFocus();
}
if (event.composedPath().includes(this.calciteTimePickerEl)) {
return;
}
const newValue = this.delocalizeTimeString(this.calciteInputEl.value);
this.setValue(newValue);
const localizedTimeString = localizeTimeString({
value: this.value,
locale: this.effectiveLocale,
numberingSystem: this.numberingSystem,
includeSeconds: this.shouldIncludeSeconds()
});
if (newValue && this.calciteInputEl.value !== localizedTimeString) {
this.setInputValue(localizedTimeString);
}
}
else if (key === "ArrowDown") {
this.open = true;
this.focusOnOpen = true;
event.preventDefault();
}
else if (key === "Escape" && this.open) {
this.open = false;
event.preventDefault();
this.calciteInputEl.setFocus();
}
};
this.setCalcitePopoverEl = (el) => {
this.popoverEl = el;
};
this.setCalciteInputEl = (el) => {
this.calciteInputEl = el;
};
this.setCalciteTimePickerEl = (el) => {
this.calciteTimePickerEl = el;
focusTrapComponent.connectFocusTrap(this, {
focusTrapEl: el,
focusTrapOptions: {
initialFocus: false,
setReturnFocus: false
}
});
};
this.setInputValue = (newInputValue) => {
if (!this.calciteInputEl) {
return;
}
this.calciteInputEl.value = newInputValue;
};
/**
* Sets the value and emits a change event.
* This is used to update the value as a result of user interaction.
*
* @param value
*/
this.setValue = (value) => {
const oldValue = this.value;
const newValue = formatTimeString(value) || "";
if (newValue === oldValue) {
return;
}
this.userChangedValue = true;
this.value = newValue || "";
const changeEvent = this.calciteInputTimePickerChange.emit();
if (changeEvent.defaultPrevented) {
this.userChangedValue = false;
this.value = oldValue;
this.setInputValue(localizeTimeString({
value: oldValue,
locale: this.effectiveLocale,
numberingSystem: this.numberingSystem,
includeSeconds: this.shouldIncludeSeconds()
}));
}
};
/**
* Sets the value directly without emitting a change event.
* This is used to update the value on initial load and when props change that are not the result of user interaction.
*
* @param value
*/
this.setValueDirectly = (value) => {
const includeSeconds = this.shouldIncludeSeconds();
this.value = toISOTimeString(value, includeSeconds);
this.setInputValue(this.value
? localizeTimeString({
value: this.value,
includeSeconds,
locale: this.effectiveLocale,
numberingSystem: this.numberingSystem
})
: "");
};
this.onInputWrapperClick = () => {
this.open = !this.open;
};
this.deactivate = () => {
this.open = false;
};
this.open = false;
this.disabled = false;
this.focusTrapDisabled = false;
this.form = undefined;
this.readOnly = false;
this.messageOverrides = undefined;
this.messages = undefined;
this.name = undefined;
this.numberingSystem = undefined;
this.required = false;
this.scale = "m";
this.overlayPositioning = "absolute";
this.placement = "auto";
this.step = 60;
this.value = null;
this.defaultMessages = undefined;
this.effectiveLocale = "";
}
openHandler(value) {
if (this.disabled || this.readOnly) {
this.open = false;
return;
}
if (value) {
this.reposition(true);
}
}
handleFocusTrapDisabled(focusTrapDisabled) {
if (!this.open) {
return;
}
focusTrapDisabled ? focusTrapComponent.deactivateFocusTrap(this) : focusTrapComponent.activateFocusTrap(this);
}
handleDisabledAndReadOnlyChange(value) {
if (!value) {
this.open = false;
}
}
onMessagesChange() {
/* wired up by t9n util */
}
numberingSystemWatcher(numberingSystem) {
this.setInputValue(localizeTimeString({
value: this.value,
locale: this.effectiveLocale,
numberingSystem,
includeSeconds: this.shouldIncludeSeconds()
}));
}
stepWatcher(newStep, oldStep) {
if ((oldStep >= 60 && newStep > 0 && newStep < 60) ||
(newStep >= 60 && oldStep > 0 && oldStep < 60)) {
this.setValueDirectly(this.value);
}
}
valueWatcher(newValue) {
if (!this.userChangedValue) {
this.setValueDirectly(newValue);
}
this.userChangedValue = false;
}
async effectiveLocaleWatcher(locale) {
await this.loadDateTimeLocaleData();
this.setInputValue(localizeTimeString({
value: this.value,
locale,
numberingSystem: this.numberingSystem,
includeSeconds: this.shouldIncludeSeconds()
}));
}
// --------------------------------------------------------------------------
//
// Public Methods
//
// --------------------------------------------------------------------------
/** Sets focus on the component. */
async setFocus() {
await loadable.componentLoaded(this);
this.el.focus();
}
/**
* Updates the position of the component.
*
* @param delayed
*/
async reposition(delayed = false) {
this.popoverEl?.reposition(delayed);
}
// --------------------------------------------------------------------------
//
// Private Methods
//
// --------------------------------------------------------------------------
delocalizeTimeString(value) {
// we need to set the corresponding locale before parsing, otherwise it defaults to English (possible dayjs bug)
dayjs.locale(this.effectiveLocale.toLowerCase());
const dayjsParseResult = dayjs(value, ["LTS", "LT"]);
if (dayjsParseResult.isValid()) {
let unformattedTimeString = `${dayjsParseResult.get("hour")}:${dayjsParseResult.get("minute")}`;
if (this.shouldIncludeSeconds()) {
unformattedTimeString += `:${dayjsParseResult.get("seconds") || 0}`;
}
return formatTimeString(unformattedTimeString) || "";
}
return "";
}
async loadDateTimeLocaleData() {
let supportedLocale = locale$1.getSupportedLocale(this.effectiveLocale).toLowerCase();
if (supportedLocale === "no") {
supportedLocale = "nb";
}
if (supportedLocale === "pt-pt") {
supportedLocale = "pt";
}
const { default: localeConfig } = await supportedDayJsLocaleToLocaleConfigImport.get(supportedLocale)();
dayjs.locale(localeConfig, null, true);
dayjs.updateLocale(supportedLocale, this.getExtendedLocaleConfig(supportedLocale));
}
getExtendedLocaleConfig(locale) {
if (locale === "ar") {
return {
meridiem: (hour) => (hour > 12 ? "م" : "ص"),
formats: {
LT: "HH:mm A",
LTS: "HH:mm:ss A",
L: "DD/MM/YYYY",
LL: "D MMMM YYYY",
LLL: "D MMMM YYYY HH:mm A",
LLLL: "dddd D MMMM YYYY HH:mm A"
}
};
}
if (locale === "en-au") {
return {
meridiem: (hour) => (hour > 12 ? "pm" : "am")
};
}
if (locale === "en-ca") {
return {
meridiem: (hour) => (hour > 12 ? "p.m." : "a.m.")
};
}
if (locale === "el") {
return {
meridiem: (hour) => (hour > 12 ? "μ.μ." : "π.μ.")
};
}
if (locale === "hi") {
return {
formats: {
LT: "h:mm A",
LTS: "h:mm:ss A",
L: "DD/MM/YYYY",
LL: "D MMMM YYYY",
LLL: "D MMMM YYYY, h:mm A",
LLLL: "dddd, D MMMM YYYY, h:mm A"
},
meridiem: (hour) => (hour > 12 ? "pm" : "am")
};
}
if (locale === "ko") {
return {
meridiem: (hour) => (hour > 12 ? "오후" : "오전")
};
}
if (locale === "zh-tw") {
return {
formats: {
LT: "AHH:mm",
LTS: "AHH:mm:ss"
}
};
}
if (locale === "zh-hk") {
return {
formats: {
LT: "AHH:mm",
LTS: "AHH:mm:ss"
},
meridiem: (hour) => (hour > 12 ? "下午" : "上午")
};
}
}
onLabelClick() {
this.setFocus();
}
shouldIncludeSeconds() {
return this.step < 60;
}
//--------------------------------------------------------------------------
//
// Lifecycle
//
//--------------------------------------------------------------------------
connectedCallback() {
interactive.connectInteractive(this);
locale$1.connectLocalized(this);
if (isValidTime(this.value)) {
this.setValueDirectly(this.value);
}
else {
this.value = undefined;
}
label.connectLabel(this);
form.connectForm(this);
t9n.connectMessages(this);
}
async componentWillLoad() {
loadable.setUpLoadableComponent(this);
await Promise.all([t9n.setUpMessages(this), this.loadDateTimeLocaleData()]);
}
componentDidLoad() {
loadable.setComponentLoaded(this);
if (isValidTime(this.value)) {
this.setInputValue(localizeTimeString({
value: this.value,
locale: this.effectiveLocale,
numberingSystem: this.numberingSystem,
includeSeconds: this.shouldIncludeSeconds()
}));
}
}
disconnectedCallback() {
interactive.disconnectInteractive(this);
label.disconnectLabel(this);
form.disconnectForm(this);
locale$1.disconnectLocalized(this);
focusTrapComponent.deactivateFocusTrap(this);
t9n.disconnectMessages(this);
}
componentDidRender() {
interactive.updateHostInteraction(this);
}
// --------------------------------------------------------------------------
//
// Render Methods
//
// --------------------------------------------------------------------------
render() {
const { disabled, messages, readOnly, dialogId } = this;
return (index.h(index.Host, { onBlur: this.hostBlurHandler, onKeyDown: this.keyDownHandler }, index.h("div", { class: "input-wrapper", onClick: this.onInputWrapperClick }, index.h("calcite-input", { "aria-autocomplete": "none", "aria-haspopup": "dialog", disabled: disabled, icon: "clock", id: this.referenceElementId, label: label.getLabelText(this), lang: this.effectiveLocale, onCalciteInputInput: this.calciteInternalInputInputHandler, onCalciteInternalInputFocus: this.calciteInternalInputFocusHandler, readOnly: readOnly, role: "combobox", scale: this.scale, step: this.step,
// eslint-disable-next-line react/jsx-sort-props
ref: this.setCalciteInputEl }), this.renderToggleIcon(this.open)), index.h("calcite-popover", { focusTrapDisabled: true, id: dialogId, label: messages.chooseTime, lang: this.effectiveLocale, onCalcitePopoverClose: this.popoverCloseHandler, onCalcitePopoverOpen: this.popoverOpenHandler, open: this.open, overlayPositioning: this.overlayPositioning, placement: this.placement, referenceElement: this.referenceElementId, triggerDisabled: true,
// eslint-disable-next-line react/jsx-sort-props
ref: this.setCalcitePopoverEl }, index.h("calcite-time-picker", { lang: this.effectiveLocale, messageOverrides: this.messageOverrides, numberingSystem: this.numberingSystem, onCalciteInternalTimePickerChange: this.timePickerChangeHandler, scale: this.scale, step: this.step, tabIndex: this.open ? undefined : -1, value: this.value,
// eslint-disable-next-line react/jsx-sort-props
ref: this.setCalciteTimePickerEl })), index.h(form.HiddenFormInputSlot, { component: this })));
}
renderToggleIcon(open) {
return (index.h("span", { class: CSS$1.toggleIcon }, index.h("calcite-icon", { icon: open ? "chevron-up" : "chevron-down", scale: "s" })));
}
static get delegatesFocus() { return true; }
static get assetsDirs() { return ["assets"]; }
get el() { return index.getElement(this); }
static get watchers() { return {
"open": ["openHandler"],
"focusTrapDisabled": ["handleFocusTrapDisabled"],
"disabled": ["handleDisabledAndReadOnlyChange"],
"readOnly": ["handleDisabledAndReadOnlyChange"],
"messageOverrides": ["onMessagesChange"],
"numberingSystem": ["numberingSystemWatcher"],
"step": ["stepWatcher"],
"value": ["valueWatcher"],
"effectiveLocale": ["effectiveLocaleWatcher"]
}; }
};
InputTimePicker.style = inputTimePickerCss;
const CSS = {
button: "button",
buttonBottomLeft: "button--bottom-left",
buttonBottomRight: "button--bottom-right",
buttonHourDown: "button--hour-down",
buttonHourUp: "button--hour-up",
buttonMeridiemDown: "button--meridiem-down",
buttonMeridiemUp: "button--meridiem-up",
buttonMinuteDown: "button--minute-down",
buttonMinuteUp: "button--minute-up",
buttonSecondDown: "button--second-down",
buttonSecondUp: "button--second-up",
buttonTopLeft: "button--top-left",
buttonTopRight: "button--top-right",
column: "column",
delimiter: "delimiter",
hour: "hour",
input: "input",
meridiem: "meridiem",
minute: "minute",
second: "second",
showMeridiem: "show-meridiem",
showSecond: "show-second",
"scale-s": "scale-s",
"scale-m": "scale-m",
"scale-l": "scale-l",
timePicker: "time-picker",
meridiemStart: "meridiem--start"
};
const timePickerCss = "@keyframes in{0%{opacity:0}100%{opacity:1}}@keyframes in-down{0%{opacity:0;transform:translate3D(0, -5px, 0)}100%{opacity:1;transform:translate3D(0, 0, 0)}}@keyframes in-up{0%{opacity:0;transform:translate3D(0, 5px, 0)}100%{opacity:1;transform:translate3D(0, 0, 0)}}@keyframes in-right{0%{opacity:0;transform:translate3D(-5px, 0, 0)}100%{opacity:1;transform:translate3D(0, 0, 0)}}@keyframes in-left{0%{opacity:0;transform:translate3D(5px, 0, 0)}100%{opacity:1;transform:translate3D(0, 0, 0)}}@keyframes in-scale{0%{opacity:0;transform:scale3D(0.95, 0.95, 1)}100%{opacity:1;transform:scale3D(1, 1, 1)}}:root{--calcite-animation-timing:calc(150ms * var(--calcite-internal-duration-factor));--calcite-internal-duration-factor:var(--calcite-duration-factor, 1);--calcite-internal-animation-timing-fast:calc(100ms * var(--calcite-internal-duration-factor));--calcite-internal-animation-timing-medium:calc(200ms * var(--calcite-internal-duration-factor));--calcite-internal-animation-timing-slow:calc(300ms * var(--calcite-internal-duration-factor))}.calcite-animate{opacity:0;animation-fill-mode:both;animation-duration:var(--calcite-animation-timing)}.calcite-animate__in{animation-name:in}.calcite-animate__in-down{animation-name:in-down}.calcite-animate__in-up{animation-name:in-up}.calcite-animate__in-right{animation-name:in-right}.calcite-animate__in-left{animation-name:in-left}.calcite-animate__in-scale{animation-name:in-scale}@media (prefers-reduced-motion: reduce){:root{--calcite-internal-duration-factor:0.01}}:root{--calcite-floating-ui-transition:var(--calcite-animation-timing);--calcite-floating-ui-z-index:var(--calcite-app-z-index-dropdown)}:host([hidden]){display:none}:host{display:inline-block}.time-picker{display:flex;-webkit-user-select:none;user-select:none;align-items:center;background-color:var(--calcite-ui-foreground-1);font-weight:var(--calcite-font-weight-medium);color:var(--calcite-ui-text-1);--tw-shadow:0 6px 20px -4px rgba(0, 0, 0, 0.1), 0 4px 12px -2px rgba(0, 0, 0, 0.08);--tw-shadow-colored:0 6px 20px -4px var(--tw-shadow-color), 0 4px 12px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow);border-radius:var(--calcite-border-radius)}.time-picker .column{display:flex;flex-direction:column}.time-picker .meridiem--start{order:-1}.time-picker .button{display:inline-flex;cursor:pointer;align-items:center;justify-content:center;background-color:var(--calcite-ui-foreground-1)}.time-picker .button:hover,.time-picker .button:focus{background-color:var(--calcite-ui-foreground-2);outline:2px solid transparent;outline-offset:2px;z-index:var(--calcite-app-z-index-header);outline-offset:0}.time-picker .button:active{background-color:var(--calcite-ui-foreground-3)}.time-picker .button.top-left{border-start-start-radius:var(--calcite-border-radius)}.time-picker .button.bottom-left{border-end-start-radius:var(--calcite-border-radius)}.time-picker .button.top-right{border-start-end-radius:var(--calcite-border-radius)}.time-picker .button.bottom-right{border-end-end-radius:var(--calcite-border-radius)}.time-picker .button calcite-icon{color:var(--calcite-ui-text-3)}.time-picker .input{display:inline-flex;cursor:pointer;align-items:center;justify-content:center;background-color:var(--calcite-ui-foreground-1);font-weight:var(--calcite-font-weight-medium)}.time-picker .input:hover{box-shadow:inset 0 0 0 2px var(--calcite-ui-foreground-2);z-index:var(--calcite-app-z-index-header)}.time-picker .input:focus,.time-picker .input:hover:focus{outline:2px solid transparent;outline-offset:2px;box-shadow:inset 0 0 0 2px var(--calcite-ui-brand);z-index:var(--calcite-app-z-index-header);outline-offset:0}.time-picker.scale-s{font-size:var(--calcite-font-size--1)}.time-picker.scale-s .button,.time-picker.scale-s .input{padding-inline:0.75rem;padding-block:0.25rem}.time-picker.scale-s:not(.show-meridiem) .delimiter:last-child{padding-inline-end:0.75rem}.time-picker.scale-m{font-size:var(--calcite-font-size-0)}.time-picker.scale-m .button,.time-picker.scale-m .input{padding-inline:1rem;padding-block:0.5rem}.time-picker.scale-m:not(.show-meridiem) .delimiter:last-child{padding-inline-end:1rem}.time-picker.scale-l{font-size:var(--calcite-font-size-1)}.time-picker.scale-l .button,.time-picker.scale-l .input{padding-inline:1.25rem;padding-block:0.75rem}.time-picker.scale-l:not(.show-meridiem) .delimiter:last-child{padding-inline-end:1.25rem}";
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
const TimePicker = class {
constructor(hostRef) {
index.registerInstance(this, hostRef);
this.calciteInternalTimePickerBlur = index.createEvent(this, "calciteInternalTimePickerBlur", 6);
this.calciteInternalTimePickerChange = index.createEvent(this, "calciteInternalTimePickerChange", 6);
this.calciteInternalTimePickerFocus = index.createEvent(this, "calciteInternalTimePickerFocus", 6);
this.decrementHour = () => {
const newHour = !this.hour ? 0 : this.hour === "00" ? 23 : parseInt(this.hour) - 1;
this.setValuePart("hour", newHour);
};
this.decrementMeridiem = () => {
const newMeridiem = this.meridiem === "PM" ? "AM" : "PM";
this.setValuePart("meridiem", newMeridiem);
};
this.decrementMinuteOrSecond = (key) => {
let newValue;
if (locale$1.isValidNumber(this[key])) {
const valueAsNumber = parseInt(this[key]);
newValue = valueAsNumber === 0 ? 59 : valueAsNumber - 1;
}
else {
newValue = 59;
}
this.setValuePart(key, newValue);
};
this.decrementMinute = () => {
this.decrementMinuteOrSecond("minute");
};
this.decrementSecond = () => {
this.decrementMinuteOrSecond("second");
};
this.focusHandler = (event) => {
this.activeEl = event.currentTarget;
};
this.hourDownButtonKeyDownHandler = (event) => {
if (this.buttonActivated(event)) {
this.decrementHour();
}
};
this.hourKeyDownHandler = (event) => {
const { key: key$1 } = event;
if (key.numberKeys.includes(key$1)) {
const keyAsNumber = parseInt(key$1);
let newHour;
if (locale$1.isValidNumber(this.hour)) {
switch (this.hourCycle) {
case "12":
newHour =
this.hour === "01" && keyAsNumber >= 0 && keyAsNumber <= 2
? `1${keyAsNumber}`
: keyAsNumber;
break;
case "24":
if (this.hour === "01") {
newHour = `1${keyAsNumber}`;
}
else if (this.hour === "02" && keyAsNumber >= 0 && keyAsNumber <= 3) {
newHour = `2${keyAsNumber}`;
}
else {
newHour = keyAsNumber;
}
break;
}
}
else {
newHour = keyAsNumber;
}
this.setValuePart("hour", newHour);
}
else {
switch (key$1) {
case "Backspace":
case "Delete":
this.setValuePart("hour", null);
break;
case "ArrowDown":
event.preventDefault();
this.decrementHour();
break;
case "ArrowUp":
event.preventDefault();
this.incrementHour();
break;
case " ":
event.preventDefault();
break;
}
}
};
this.hourUpButtonKeyDownHandler = (event) => {
if (this.buttonActivated(event)) {
this.incrementHour();
}
};
this.incrementMeridiem = () => {
const newMeridiem = this.meridiem === "AM" ? "PM" : "AM";
this.setValuePart("meridiem", newMeridiem);
};
this.incrementHour = () => {
const newHour = locale$1.isValidNumber(this.hour)
? this.hour === "23"
? 0
: parseInt(this.hour) + 1
: 1;
this.setValuePart("hour", newHour);
};
this.incrementMinuteOrSecond = (key) => {
const newValue = locale$1.isValidNumber(this[key])
? this[key] === "59"
? 0
: parseInt(this[key]) + 1
: 0;
this.setValuePart(key, newValue);
};
this.incrementMinute = () => {
this.incrementMinuteOrSecond("minute");
};
this.incrementSecond = () => {
this.incrementMinuteOrSecond("second");
};
this.meridiemDownButtonKeyDownHandler = (event) => {
if (this.buttonActivated(event)) {
this.decrementMeridiem();
}
};
this.meridiemKeyDownHandler = (event) => {
switch (event.key) {
case "a":
this.setValuePart("meridiem", "AM");
break;
case "p":
this.setValuePart("meridiem", "PM");
break;
case "Backspace":
case "Delete":
this.setValuePart("meridiem", null);
break;
case "ArrowUp":
event.preventDefault();
this.incrementMeridiem();
break;
case "ArrowDown":
event.preventDefault();
this.decrementMeridiem();
break;
case " ":
event.preventDefault();
break;
}
};
this.meridiemUpButtonKeyDownHandler = (event) => {
if (this.buttonActivated(event)) {
this.incrementMeridiem();
}
};
this.minuteDownButtonKeyDownHandler = (event) => {
if (this.buttonActivated(event)) {
this.decrementMinute();
}
};
this.minuteKeyDownHandler = (event) => {
const { key: key$1 } = event;
if (key.numberKeys.includes(key$1)) {
const keyAsNumber = parseInt(key$1);
let newMinute;
if (locale$1.isValidNumber(this.minute) && this.minute.startsWith("0")) {
const minuteAsNumber = parseInt(this.minute);
newMinute =
minuteAsNumber > maxTenthForMinuteAndSecond
? keyAsNumber
: `${minuteAsNumber}${keyAsNumber}`;
}
else {
newMinute = keyAsNumber;
}
this.setValuePart("minute", newMinute);
}
else {
switch (key$1) {
case "Backspace":
case "Delete":
this.setValuePart("minute", null);
break;
case "ArrowDown":
event.preventDefault();
this.decrementMinute();
break;
case "ArrowUp":
event.preventDefault();
this.incrementMinute();
break;
case " ":
event.preventDefault();
break;
}
}
};
this.minuteUpButtonKeyDownHandler = (event) => {
if (this.buttonActivated(event)) {
this.incrementMinute();
}
};
this.secondDownButtonKeyDownHandler = (event) => {
if (this.buttonActivated(event)) {
this.decrementSecond();
}
};
this.secondKeyDownHandler = (event) => {
const { key: key$1 } = event;
if (key.numberKeys.includes(key$1)) {
const keyAsNumber = parseInt(key$1);
let newSecond;
if (locale$1.isValidNumber(this.second) && this.second.startsWith("0")) {
const secondAsNumber = parseInt(this.second);
newSecond =
secondAsNumber > maxTenthForMinuteAndSecond
? keyAsNumber
: `${secondAsNumber}${keyAsNumber}`;
}
else {
newSecond = keyAsNumber;
}
this.setValuePart("second", newSecond);
}
else {
switch (key$1) {
case "Backspace":
case "Delete":
this.setValuePart("second", null);
break;
case "ArrowDown":
event.preventDefault();
this.decrementSecond();
break;
case "ArrowUp":
event.preventDefault();
this.incrementSecond();
break;
case " ":
event.preventDefault();
break;
}
}
};
this.secondUpButtonKeyDownHandler = (event) => {
if (this.buttonActivated(event)) {
this.incrementSecond();
}
};
this.setHourEl = (el) => (this.hourEl = el);
this.setMeridiemEl = (el) => (this.meridiemEl = el);
this.setMinuteEl = (el) => (this.minuteEl = el);
this.setSecondEl = (el) => (this.secondEl = el);
this.setValue = (value, emit = true) => {
if (isValidTime(value)) {
const { hour, minute, second } = parseTimeString(value);
const { effectiveLocale: locale, numberingSystem } = this;
const { localizedHour, localizedHourSuffix, localizedMinute, localizedMinuteSuffix, localizedSecond, localizedSecondSuffix, localizedMeridiem } = localizeTimeStringToParts({ value, locale, numberingSystem });
this.localizedHour = localizedHour;
this.localizedHourSuffix = localizedHourSuffix;
this.localizedMinute = localizedMinute;
this.localizedMinuteSuffix = localizedMinuteSuffix;
this.localizedSecond = localizedSecond;
this.localizedSecondSuffix = localizedSecondSuffix;
this.hour = hour;
this.minute = minute;
this.second = second;
if (localizedMeridiem) {
this.localizedMeridiem = localizedMeridiem;
this.meridiem = getMeridiem(this.hour);
const formatParts = getTimeParts({ value, locale, numberingSystem });
this.meridiemOrder = this.getMeridiemOrder(formatParts);
}
}
else {
this.hour = null;
this.localizedHour = null;
this.localizedHourSuffix = null;
this.localizedMeridiem = null;
this.localizedMinute = null;
this.localizedMinuteSuffix = null;
this.localizedSecond = null;
this.localizedSecondSuffix = null;
this.meridiem = null;
this.minute = null;
this.second = null;
this.value = null;
}
if (emit) {
this.calciteInternalTimePickerChange.emit();
}
};
this.setValuePart = (key, value, emit = true) => {
const { effectiveLocale: locale, numberingSystem } = this;
if (key === "meridiem") {
this.meridiem = value;
if (locale$1.isValidNumber(this.hour)) {
const hourAsNumber = parseInt(this.hour);
switch (value) {
case "AM":
if (hourAsNumber >= 12) {
this.hour = formatTimePart(hourAsNumber - 12);
}
break;
case "PM":
if (hourAsNumber < 12) {
this.hour = formatTimePart(hourAsNumber + 12);
}
break;
}
this.localizedHour = localizeTimePart({
value: this.hour,
part: "hour",
locale,
numberingSystem
});
}
}
else {
this[key] = typeof value === "number" ? formatTimePart(value) : value;
this[`localized${capitalize(key)}`] = localizeTimePart({
value: this[key],
part: key,
locale,
numberingSystem
});
}
if (this.hour && this.minute) {
let newValue = `${this.hour}:${this.minute}`;
if (this.showSecond) {
newValue = `${newValue}:${this.second ?? "00"}`;
}
this.value = newValue;
}
else {
this.value = null;
}
this.localizedMeridiem = this.value
? localizeTimeStringToParts({ value: this.value, locale, numberingSystem })
?.localizedMeridiem || null
: localizeTimePart({ value: this.meridiem, part: "meridiem", locale, numberingSystem });
if (emit) {
this.calciteInternalTimePickerChange.emit();
}
};
this.scale = "m";
this.step = 60;
this.numberingSystem = undefined;
this.value = null;
this.messages = undefined;
this.messageOverrides = undefined;
this.effectiveLocale = "";
this.hour = undefined;
this.hourCycle = undefined;
this.localizedHour = undefined;
this.localizedHourSuffix = undefined;
this.localizedMeridiem = undefined;
this.localizedMinute = undefined;
this.localizedMinuteSuffix = undefined;
this.localizedSecond = undefined;
this.localizedSecondSuffix = undefined;
this.meridiem = undefined;
this.minute = undefined;
this.second = undefined;
this.showSecond = undefined;
this.defaultMessages = undefined;
}
stepChange() {
this.updateShowSecond();
}
valueWatcher(newValue) {
this.setValue(newValue, false);
}
onMessagesChange() {
/* wired up by t9n util */
}
effectiveLocaleWatcher() {
this.updateLocale();
}
//--------------------------------------------------------------------------
//
// Event Listeners
//
//--------------------------------------------------------------------------
hostBlurHandler() {
this.calciteInternalTimePickerBlur.emit();
}
hostFocusHandler() {
this.calciteInternalTimePickerFocus.emit();
}
keyDownHandler(event) {
const { defaultPrevented, key } = event;
if (defaultPrevented) {
return;
}
switch (this.activeEl) {
case this.hourEl:
if (key === "ArrowRight") {
this.focusPart("minute");
event.preventDefault();
}
break;
case this.minuteEl:
switch (key) {
case "ArrowLeft":
this.focusPart("hour");
event.preventDefault();
break;
case "ArrowRight":
if (this.step !== 60) {
this.focusPart("second");
event.preventDefault();
}
else if (this.hourCycle === "12") {
this.focusPart("meridiem");
event.preventDefault();
}
break;
}
break;
case this.secondEl:
switch (key) {
case "ArrowLeft":
this.focusPart("minute");
event.preventDefault();
break;
case "ArrowRight":
if (this.hourCycle === "12") {
this.focusPart("meridiem");
event.preventDefault();
}
break;
}
break;
case this.meridiemEl:
switch (key) {
case "ArrowLeft":
if (this.step !== 60) {
this.focusPart("second");
event.preventDefault();
}
else {
this.focusPart("minute");
event.preventDefault();
}
break;
}
break;
}
}
//--------------------------------------------------------------------------
//
// Public Methods
//
//--------------------------------------------------------------------------
/**
* Sets focus on the component's first focusable element.
*/
async setFocus() {
await loadable.componentLoaded(this);
this.el?.focus();
}
// --------------------------------------------------------------------------
//
// Private Methods
//
// --------------------------------------------------------------------------
updateShowSecond() {
this.showSecond = this.step < 60;
}
async focusPart(target) {
await loadable.componentLoaded(this);
this[`${target || "hour"}El`]?.focus();
}
buttonActivated(event) {
const { key: key$1 } = event;
if (key$1 === " ") {
event.preventDefault();
}
return key.isActivationKey(key$1);
}
getMeridiemOrder(formatParts) {
const locale = this.effectiveLocale;
const isRTLKind = locale === "ar" || locale === "he";
if (formatParts && !isRTLKind) {
const index = formatParts.findIndex((parts) => {
return parts.value === this.localizedMeridiem;
});
return index;
}
return 0;
}
updateLocale() {
t9n.updateMessages(this, this.effectiveLocale);
this.hourCycle = getLocaleHourCycle(this.effectiveLocale, this.numberingSystem);
this.setValue(this.value, false);
}
// --------------------------------------------------------------------------
//
// Lifecycle
//
// --------------------------------------------------------------------------
connectedCallback() {
locale$1.connectLocalized(this);
this.updateLocale();
t9n.connectMessages(this);
this.updateShowSecond();
this.meridiemOrder = this.getMeridiemOrder(getTimeParts({
value: "0:00:00",
locale: this.effectiveLocale,
numberingSystem: this.numberingSystem
}));
}
async componentWillLoad() {
loadable.setUpLoadableComponent(this);
await t9n.setUpMessages(this);
}
componentDidLoad() {
loadable.setComponentLoaded(this);
}
disconnectedCallback() {
locale$1.disconnectLocalized(this);
t9n.disconnectMessages(this);
}
// --------------------------------------------------------------------------
//
// Render Methods
//
// --------------------------------------------------------------------------
render() {
const hourIsNumber = locale$1.isValidNumber(this.hour);
const iconScale = this.scale === "s" || this.scale === "m" ? "s" : "m";
const minuteIsNumber = locale$1.isValidNumber(this.minute);
const secondIsNumber = locale$1.isValidNumber(this.second);
const showMeridiem = this.hourCycle === "12";
return (index.h("div", { class: {
[CSS.timePicker]: true,
[CSS.showMeridiem]: showMeridiem,
[CSS.showSecond]: this.showSecond,
[CSS[`scale-${this.scale}`]]: true
}, dir: "ltr" }, index.h("div", { class: CSS.column, role: "group" }, index.h("span", { "aria-label": this.messages.hourUp, class: {
[CSS.button]: true,
[CSS.buttonHourUp]: true,
[CSS.buttonTopLeft]: true
}, onClick: this.incrementHour, onKeyDown: this.hourUpButtonKeyDownHandler, role: "button" }, index.h("calcite-icon", { icon: "chevron-up", scale: iconScale })), index.h("span", { "aria-label": this.messages.hour, "aria-valuemax": "23", "aria-valuemin": "1", "aria-valuenow": (hourIsNumber && parseInt(this.hour)) || "0", "aria-valuetext": this.hour, class: {
[CSS.input]: true,
[CSS.hour]: true
}, onFocus: this.focusHandler, onKeyDown: this.hourKeyDownHandler, role: "spinbutton", tabIndex: 0,
// eslint-disable-next-line react/jsx-sort-props
ref: this.setHourEl }, this.localizedHour || "--"), index.h("span", { "aria-label": this.messages.hourDown, class: {
[CSS.button]: true,
[CSS.buttonHourDown]: true,
[CSS.buttonBottomLeft]: true
}, onClick: this.decrementHour, onKeyDown: this.hourDownButtonKeyDownHandler, role: "button" }, index.h("calcite-icon", { icon: "chevron-down", scale: iconScale }))), index.h("span", { class: CSS.delimiter }, this.localizedHourSuffix), index.h("div", { class: CSS.column, role: "group" }, index.h("span", { "aria-label": this.messages.minuteUp, class: {
[CSS.button]: true,
[CSS.buttonMinuteUp]: true
}, onClick: this.incrementMinute, onKeyDown: this.minuteUpButtonKeyDownHandler, role: "button", tabIndex: -1 }, index.h("calcite-icon", { icon: "chevron-up", scale: iconScale })), index.h("span", { "aria-label": this.messages.minute, "aria-valuemax": "12", "aria-valuemin": "1", "aria-valuenow": (minuteIsNumber && parseInt(this.minute)) || "0", "aria-valuetext": this.minute, class: {
[CSS.input]: true,
[CSS.minute]: true
}, onFocus: this.focusHandler, onKeyDown: this.minuteKeyDownHandler, role: "spinbutton", tabIndex: 0,
// eslint-disable-next-line react/jsx-sort-props
ref: this.setMinuteEl }, this.localizedMinute || "--"), index.h("span", { "aria-label": this.messages.minuteDown, class: {
[CSS.button]: true,
[CSS.buttonMinuteDown]: true
}, onClick: this.decrementMinute, onKeyDown: this.minuteDownButtonKeyDownHandler, role: "button" }, index.h("calcite-icon", { icon: "chevron-down", scale: iconScale }))), this.showSecond && index.h("span", { class: CSS.delimiter }, this.localizedMinuteSuffix), this.showSecond && (index.h("div", { class: CSS.column, role: "group" }, index.h("span", { "aria-label": this.messages.secondUp, class: {
[CSS.button]: true,
[CSS.buttonSecondUp]: true
}, onClick: this.incrementSecond, onKeyDown: this.secondUpButtonKeyDownHandler, role: "button" }, index.h("calcite-icon", { icon: "chevron-up", scale: iconScale })), index.h("span", { "aria-label": this.messages.second, "aria-valuemax": "59", "aria-valuemin": "0", "aria-valuenow": (secondIsNumber && parseInt(this.second)) || "0", "aria-valuetext": this.second, class: {
[CSS.input]: true,
[CSS.second]: true
}, onFocus: this.focusHandler, onKeyDown: this.secondKeyDownHandler, role: "spinbutton", tabIndex: 0,
// eslint-disable-next-line react/jsx-sort-props
ref: this.setSecondEl }, this.localizedSecond || "--"), index.h("span", { "aria-label": this.messages.secondDown, class: {
[CSS.button]: true,
[CSS.buttonSecondDown]: true
}, onClick: this.decrementSecond, onKeyDown: this.secondDownButtonKeyDownHandler, role: "button" }, index.h("calcite-icon", { icon: "chevron-down", scale: iconScale })))), this.localizedSecondSuffix && (index.h("span", { class: CSS.delimiter }, this.localizedSecondSuffix)), showMeridiem && (index.h("div", { class: {
[CSS.column]: true,
[CSS.meridiemStart]: this.meridiemOrder === 0
}, role: "group" }, index.h("span", { "aria-label": this.messages.meridiemUp, class: {
[CSS.button]: true,
[CSS.buttonMeridiemUp]: true,
[CSS.buttonTopRight]: true
}, onClick: this.incrementMeridiem, onKeyDown: this.meridiemUpButtonKeyDownHandler, role: "button" }, index.h("calcite-icon", { icon: "chevron-up", scale: iconScale })), index.h("span", { "aria-label": this.messages.meridiem, "aria-valuemax": "2", "aria-valuemin": "1", "aria-valuenow": (this.meridiem === "PM" && "2") || "1", "aria-valuetext": this.meridiem, class: {
[CSS.input]: true,
[CSS.meridiem]: true
}, onFocus: this.focusHandler, onKeyDown: this.meridiemKeyDownHandler, role: "spinbutton", tabIndex: 0,
// eslint-disable-next-line react/jsx-sort-props
ref: this.setMeridiemEl }, this.localizedMeridiem || "--"), index.h("span", { "aria-label": this.messages.meridiemDown, class: {
[CSS.button]: true,
[CSS.buttonMeridiemDown]: true,
[CSS.buttonBottomRight]: true
}, onClick: this.decrementMeridiem, onKeyDown: this.meridiemDownButtonKeyDownHandler, role: "button" }, index.h("calcite-icon", { icon: "chevron-down", scale: iconScale }))))));
}
static get delegatesFocus() { return true; }
static get assetsDirs() { return ["assets"]; }
get el() { return index.getElement(this); }
static get watchers() { return {
"step": ["stepChange"],
"value": ["valueWatcher"],
"messageOverrides": ["onMessagesChange"],
"effectiveLocale": ["effectiveLocaleWatcher"]
}; }
};
TimePicker.style = timePickerCss;
exports.InputTimePicker = InputTimePicker;
exports.TimePicker = TimePicker;
exports.dayjs = dayjs;