data.js 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610
  1. /*!
  2. * (C) Ionic http://ionicframework.com - MIT License
  3. */
  4. import { a as printIonWarning } from './index4.js';
  5. /**
  6. * Returns true if the selected day is equal to the reference day
  7. */
  8. const isSameDay = (baseParts, compareParts) => {
  9. return (baseParts.month === compareParts.month && baseParts.day === compareParts.day && baseParts.year === compareParts.year);
  10. };
  11. /**
  12. * Returns true is the selected day is before the reference day.
  13. */
  14. const isBefore = (baseParts, compareParts) => {
  15. return !!(baseParts.year < compareParts.year ||
  16. (baseParts.year === compareParts.year && baseParts.month < compareParts.month) ||
  17. (baseParts.year === compareParts.year &&
  18. baseParts.month === compareParts.month &&
  19. baseParts.day !== null &&
  20. baseParts.day < compareParts.day));
  21. };
  22. /**
  23. * Returns true is the selected day is after the reference day.
  24. */
  25. const isAfter = (baseParts, compareParts) => {
  26. return !!(baseParts.year > compareParts.year ||
  27. (baseParts.year === compareParts.year && baseParts.month > compareParts.month) ||
  28. (baseParts.year === compareParts.year &&
  29. baseParts.month === compareParts.month &&
  30. baseParts.day !== null &&
  31. baseParts.day > compareParts.day));
  32. };
  33. const warnIfValueOutOfBounds = (value, min, max) => {
  34. const valueArray = Array.isArray(value) ? value : [value];
  35. for (const val of valueArray) {
  36. if ((min !== undefined && isBefore(val, min)) || (max !== undefined && isAfter(val, max))) {
  37. printIonWarning('[ion-datetime] - The value provided to ion-datetime is out of bounds.\n\n' +
  38. `Min: ${JSON.stringify(min)}\n` +
  39. `Max: ${JSON.stringify(max)}\n` +
  40. `Value: ${JSON.stringify(value)}`);
  41. break;
  42. }
  43. }
  44. };
  45. /**
  46. * Determines if given year is a
  47. * leap year. Returns `true` if year
  48. * is a leap year. Returns `false`
  49. * otherwise.
  50. */
  51. const isLeapYear = (year) => {
  52. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  53. };
  54. /**
  55. * Determines the hour cycle for a user.
  56. * If the hour cycle is explicitly defined, just use that.
  57. * Otherwise, we try to derive it from either the specified
  58. * locale extension tags or from Intl.DateTimeFormat directly.
  59. */
  60. const getHourCycle = (locale, hourCycle) => {
  61. /**
  62. * If developer has explicitly enabled 24-hour time
  63. * then return early and do not look at the system default.
  64. */
  65. if (hourCycle !== undefined) {
  66. return hourCycle;
  67. }
  68. /**
  69. * If hourCycle was not specified, check the locale
  70. * that is set on the user's device. We first check the
  71. * Intl.DateTimeFormat hourCycle option as developers can encode this
  72. * option into the locale string. Example: `en-US-u-hc-h23`
  73. */
  74. const formatted = new Intl.DateTimeFormat(locale, { hour: 'numeric' });
  75. const options = formatted.resolvedOptions();
  76. if (options.hourCycle !== undefined) {
  77. return options.hourCycle;
  78. }
  79. /**
  80. * If hourCycle is not specified (either through lack
  81. * of browser support or locale information) then fall
  82. * back to this slower hourCycle check.
  83. */
  84. const date = new Date('5/18/2021 00:00');
  85. const parts = formatted.formatToParts(date);
  86. const hour = parts.find((p) => p.type === 'hour');
  87. if (!hour) {
  88. throw new Error('Hour value not found from DateTimeFormat');
  89. }
  90. /**
  91. * Midnight for h11 starts at 0:00am
  92. * Midnight for h12 starts at 12:00am
  93. * Midnight for h23 starts at 00:00
  94. * Midnight for h24 starts at 24:00
  95. */
  96. switch (hour.value) {
  97. case '0':
  98. return 'h11';
  99. case '12':
  100. return 'h12';
  101. case '00':
  102. return 'h23';
  103. case '24':
  104. return 'h24';
  105. default:
  106. throw new Error(`Invalid hour cycle "${hourCycle}"`);
  107. }
  108. };
  109. /**
  110. * Determine if the hour cycle uses a 24-hour format.
  111. * Returns true for h23 and h24. Returns false otherwise.
  112. * If you don't know the hourCycle, use getHourCycle above
  113. * and pass the result into this function.
  114. */
  115. const is24Hour = (hourCycle) => {
  116. return hourCycle === 'h23' || hourCycle === 'h24';
  117. };
  118. /**
  119. * Given a date object, returns the number
  120. * of days in that month.
  121. * Month value begin at 1, not 0.
  122. * i.e. January = month 1.
  123. */
  124. const getNumDaysInMonth = (month, year) => {
  125. return month === 4 || month === 6 || month === 9 || month === 11
  126. ? 30
  127. : month === 2
  128. ? isLeapYear(year)
  129. ? 29
  130. : 28
  131. : 31;
  132. };
  133. /**
  134. * Certain locales display month then year while
  135. * others display year then month.
  136. * We can use Intl.DateTimeFormat to determine
  137. * the ordering for each locale.
  138. * The formatOptions param can be used to customize
  139. * which pieces of a date to compare against the month
  140. * with. For example, some locales render dd/mm/yyyy
  141. * while others render mm/dd/yyyy. This function can be
  142. * used for variations of the same "month first" check.
  143. */
  144. const isMonthFirstLocale = (locale, formatOptions = {
  145. month: 'numeric',
  146. year: 'numeric',
  147. }) => {
  148. /**
  149. * By setting month and year we guarantee that only
  150. * month, year, and literal (slashes '/', for example)
  151. * values are included in the formatToParts results.
  152. *
  153. * The ordering of the parts will be determined by
  154. * the locale. So if the month is the first value,
  155. * then we know month should be shown first. If the
  156. * year is the first value, then we know year should be shown first.
  157. *
  158. * This ordering can be controlled by customizing the locale property.
  159. */
  160. const parts = new Intl.DateTimeFormat(locale, formatOptions).formatToParts(new Date());
  161. return parts[0].type === 'month';
  162. };
  163. /**
  164. * Determines if the given locale formats the day period (am/pm) to the
  165. * left or right of the hour.
  166. * @param locale The locale to check.
  167. * @returns `true` if the locale formats the day period to the left of the hour.
  168. */
  169. const isLocaleDayPeriodRTL = (locale) => {
  170. const parts = new Intl.DateTimeFormat(locale, { hour: 'numeric' }).formatToParts(new Date());
  171. return parts[0].type === 'dayPeriod';
  172. };
  173. const ISO_8601_REGEXP =
  174. // eslint-disable-next-line no-useless-escape
  175. /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/;
  176. // eslint-disable-next-line no-useless-escape
  177. const TIME_REGEXP = /^((\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/;
  178. /**
  179. * Use to convert a string of comma separated numbers or
  180. * an array of numbers, and clean up any user input
  181. */
  182. const convertToArrayOfNumbers = (input) => {
  183. if (input === undefined) {
  184. return;
  185. }
  186. let processedInput = input;
  187. if (typeof input === 'string') {
  188. // convert the string to an array of strings
  189. // auto remove any whitespace and [] characters
  190. processedInput = input.replace(/\[|\]|\s/g, '').split(',');
  191. }
  192. let values;
  193. if (Array.isArray(processedInput)) {
  194. // ensure each value is an actual number in the returned array
  195. values = processedInput.map((num) => parseInt(num, 10)).filter(isFinite);
  196. }
  197. else {
  198. values = [processedInput];
  199. }
  200. return values;
  201. };
  202. /**
  203. * Extracts date information
  204. * from a .calendar-day element
  205. * into DatetimeParts.
  206. */
  207. const getPartsFromCalendarDay = (el) => {
  208. return {
  209. month: parseInt(el.getAttribute('data-month'), 10),
  210. day: parseInt(el.getAttribute('data-day'), 10),
  211. year: parseInt(el.getAttribute('data-year'), 10),
  212. dayOfWeek: parseInt(el.getAttribute('data-day-of-week'), 10),
  213. };
  214. };
  215. function parseDate(val) {
  216. if (Array.isArray(val)) {
  217. const parsedArray = [];
  218. for (const valStr of val) {
  219. const parsedVal = parseDate(valStr);
  220. /**
  221. * If any of the values weren't parsed correctly, consider
  222. * the entire batch incorrect. This simplifies the type
  223. * signatures by having "undefined" be a general error case
  224. * instead of returning (Datetime | undefined)[], which is
  225. * harder for TS to perform type narrowing on.
  226. */
  227. if (!parsedVal) {
  228. return undefined;
  229. }
  230. parsedArray.push(parsedVal);
  231. }
  232. return parsedArray;
  233. }
  234. // manually parse IS0 cuz Date.parse cannot be trusted
  235. // ISO 8601 format: 1994-12-15T13:47:20Z
  236. let parse = null;
  237. if (val != null && val !== '') {
  238. // try parsing for just time first, HH:MM
  239. parse = TIME_REGEXP.exec(val);
  240. if (parse) {
  241. // adjust the array so it fits nicely with the datetime parse
  242. parse.unshift(undefined, undefined);
  243. parse[2] = parse[3] = undefined;
  244. }
  245. else {
  246. // try parsing for full ISO datetime
  247. parse = ISO_8601_REGEXP.exec(val);
  248. }
  249. }
  250. if (parse === null) {
  251. // wasn't able to parse the ISO datetime
  252. printIonWarning(`[ion-datetime] - Unable to parse date string: ${val}. Please provide a valid ISO 8601 datetime string.`);
  253. return undefined;
  254. }
  255. // ensure all the parse values exist with at least 0
  256. for (let i = 1; i < 8; i++) {
  257. parse[i] = parse[i] !== undefined ? parseInt(parse[i], 10) : undefined;
  258. }
  259. // can also get second and millisecond from parse[6] and parse[7] if needed
  260. return {
  261. year: parse[1],
  262. month: parse[2],
  263. day: parse[3],
  264. hour: parse[4],
  265. minute: parse[5],
  266. ampm: parse[4] < 12 ? 'am' : 'pm',
  267. };
  268. }
  269. const clampDate = (dateParts, minParts, maxParts) => {
  270. if (minParts && isBefore(dateParts, minParts)) {
  271. return minParts;
  272. }
  273. else if (maxParts && isAfter(dateParts, maxParts)) {
  274. return maxParts;
  275. }
  276. return dateParts;
  277. };
  278. /**
  279. * Parses an hour and returns if the value is in the morning (am) or afternoon (pm).
  280. * @param hour The hour to format, should be 0-23
  281. * @returns `pm` if the hour is greater than or equal to 12, `am` if less than 12.
  282. */
  283. const parseAmPm = (hour) => {
  284. return hour >= 12 ? 'pm' : 'am';
  285. };
  286. /**
  287. * Takes a max date string and creates a DatetimeParts
  288. * object, filling in any missing information.
  289. * For example, max="2012" would fill in the missing
  290. * month, day, hour, and minute information.
  291. */
  292. const parseMaxParts = (max, todayParts) => {
  293. const result = parseDate(max);
  294. /**
  295. * If min was not a valid date then return undefined.
  296. */
  297. if (result === undefined) {
  298. return;
  299. }
  300. const { month, day, year, hour, minute } = result;
  301. /**
  302. * When passing in `max` or `min`, developers
  303. * can pass in any ISO-8601 string. This means
  304. * that not all of the date/time fields are defined.
  305. * For example, passing max="2012" is valid even though
  306. * there is no month, day, hour, or minute data.
  307. * However, all of this data is required when clamping the date
  308. * so that the correct initial value can be selected. As a result,
  309. * we need to fill in any omitted data with the min or max values.
  310. */
  311. const yearValue = year !== null && year !== void 0 ? year : todayParts.year;
  312. const monthValue = month !== null && month !== void 0 ? month : 12;
  313. return {
  314. month: monthValue,
  315. day: day !== null && day !== void 0 ? day : getNumDaysInMonth(monthValue, yearValue),
  316. /**
  317. * Passing in "HH:mm" is a valid ISO-8601
  318. * string, so we just default to the current year
  319. * in this case.
  320. */
  321. year: yearValue,
  322. hour: hour !== null && hour !== void 0 ? hour : 23,
  323. minute: minute !== null && minute !== void 0 ? minute : 59,
  324. };
  325. };
  326. /**
  327. * Takes a min date string and creates a DatetimeParts
  328. * object, filling in any missing information.
  329. * For example, min="2012" would fill in the missing
  330. * month, day, hour, and minute information.
  331. */
  332. const parseMinParts = (min, todayParts) => {
  333. const result = parseDate(min);
  334. /**
  335. * If min was not a valid date then return undefined.
  336. */
  337. if (result === undefined) {
  338. return;
  339. }
  340. const { month, day, year, hour, minute } = result;
  341. /**
  342. * When passing in `max` or `min`, developers
  343. * can pass in any ISO-8601 string. This means
  344. * that not all of the date/time fields are defined.
  345. * For example, passing max="2012" is valid even though
  346. * there is no month, day, hour, or minute data.
  347. * However, all of this data is required when clamping the date
  348. * so that the correct initial value can be selected. As a result,
  349. * we need to fill in any omitted data with the min or max values.
  350. */
  351. return {
  352. month: month !== null && month !== void 0 ? month : 1,
  353. day: day !== null && day !== void 0 ? day : 1,
  354. /**
  355. * Passing in "HH:mm" is a valid ISO-8601
  356. * string, so we just default to the current year
  357. * in this case.
  358. */
  359. year: year !== null && year !== void 0 ? year : todayParts.year,
  360. hour: hour !== null && hour !== void 0 ? hour : 0,
  361. minute: minute !== null && minute !== void 0 ? minute : 0,
  362. };
  363. };
  364. const twoDigit = (val) => {
  365. return ('0' + (val !== undefined ? Math.abs(val) : '0')).slice(-2);
  366. };
  367. const fourDigit = (val) => {
  368. return ('000' + (val !== undefined ? Math.abs(val) : '0')).slice(-4);
  369. };
  370. function convertDataToISO(data) {
  371. if (Array.isArray(data)) {
  372. return data.map((parts) => convertDataToISO(parts));
  373. }
  374. // https://www.w3.org/TR/NOTE-datetime
  375. let rtn = '';
  376. if (data.year !== undefined) {
  377. // YYYY
  378. rtn = fourDigit(data.year);
  379. if (data.month !== undefined) {
  380. // YYYY-MM
  381. rtn += '-' + twoDigit(data.month);
  382. if (data.day !== undefined) {
  383. // YYYY-MM-DD
  384. rtn += '-' + twoDigit(data.day);
  385. if (data.hour !== undefined) {
  386. // YYYY-MM-DDTHH:mm:SS
  387. rtn += `T${twoDigit(data.hour)}:${twoDigit(data.minute)}:00`;
  388. }
  389. }
  390. }
  391. }
  392. else if (data.hour !== undefined) {
  393. // HH:mm
  394. rtn = twoDigit(data.hour) + ':' + twoDigit(data.minute);
  395. }
  396. return rtn;
  397. }
  398. /**
  399. * Converts an 12 hour value to 24 hours.
  400. */
  401. const convert12HourTo24Hour = (hour, ampm) => {
  402. if (ampm === undefined) {
  403. return hour;
  404. }
  405. /**
  406. * If AM and 12am
  407. * then return 00:00.
  408. * Otherwise just return
  409. * the hour since it is
  410. * already in 24 hour format.
  411. */
  412. if (ampm === 'am') {
  413. if (hour === 12) {
  414. return 0;
  415. }
  416. return hour;
  417. }
  418. /**
  419. * If PM and 12pm
  420. * just return 12:00
  421. * since it is already
  422. * in 24 hour format.
  423. * Otherwise add 12 hours
  424. * to the time.
  425. */
  426. if (hour === 12) {
  427. return 12;
  428. }
  429. return hour + 12;
  430. };
  431. const getStartOfWeek = (refParts) => {
  432. const { dayOfWeek } = refParts;
  433. if (dayOfWeek === null || dayOfWeek === undefined) {
  434. throw new Error('No day of week provided');
  435. }
  436. return subtractDays(refParts, dayOfWeek);
  437. };
  438. const getEndOfWeek = (refParts) => {
  439. const { dayOfWeek } = refParts;
  440. if (dayOfWeek === null || dayOfWeek === undefined) {
  441. throw new Error('No day of week provided');
  442. }
  443. return addDays(refParts, 6 - dayOfWeek);
  444. };
  445. const getNextDay = (refParts) => {
  446. return addDays(refParts, 1);
  447. };
  448. const getPreviousDay = (refParts) => {
  449. return subtractDays(refParts, 1);
  450. };
  451. const getPreviousWeek = (refParts) => {
  452. return subtractDays(refParts, 7);
  453. };
  454. const getNextWeek = (refParts) => {
  455. return addDays(refParts, 7);
  456. };
  457. /**
  458. * Given datetime parts, subtract
  459. * numDays from the date.
  460. * Returns a new DatetimeParts object
  461. * Currently can only go backward at most 1 month.
  462. */
  463. const subtractDays = (refParts, numDays) => {
  464. const { month, day, year } = refParts;
  465. if (day === null) {
  466. throw new Error('No day provided');
  467. }
  468. const workingParts = {
  469. month,
  470. day,
  471. year,
  472. };
  473. workingParts.day = day - numDays;
  474. /**
  475. * If wrapping to previous month
  476. * update days and decrement month
  477. */
  478. if (workingParts.day < 1) {
  479. workingParts.month -= 1;
  480. }
  481. /**
  482. * If moving to previous year, reset
  483. * month to December and decrement year
  484. */
  485. if (workingParts.month < 1) {
  486. workingParts.month = 12;
  487. workingParts.year -= 1;
  488. }
  489. /**
  490. * Determine how many days are in the current
  491. * month
  492. */
  493. if (workingParts.day < 1) {
  494. const daysInMonth = getNumDaysInMonth(workingParts.month, workingParts.year);
  495. /**
  496. * Take num days in month and add the
  497. * number of underflow days. This number will
  498. * be negative.
  499. * Example: 1 week before Jan 2, 2021 is
  500. * December 26, 2021 so:
  501. * 2 - 7 = -5
  502. * 31 + (-5) = 26
  503. */
  504. workingParts.day = daysInMonth + workingParts.day;
  505. }
  506. return workingParts;
  507. };
  508. /**
  509. * Given datetime parts, add
  510. * numDays to the date.
  511. * Returns a new DatetimeParts object
  512. * Currently can only go forward at most 1 month.
  513. */
  514. const addDays = (refParts, numDays) => {
  515. const { month, day, year } = refParts;
  516. if (day === null) {
  517. throw new Error('No day provided');
  518. }
  519. const workingParts = {
  520. month,
  521. day,
  522. year,
  523. };
  524. const daysInMonth = getNumDaysInMonth(month, year);
  525. workingParts.day = day + numDays;
  526. /**
  527. * If wrapping to next month
  528. * update days and increment month
  529. */
  530. if (workingParts.day > daysInMonth) {
  531. workingParts.day -= daysInMonth;
  532. workingParts.month += 1;
  533. }
  534. /**
  535. * If moving to next year, reset
  536. * month to January and increment year
  537. */
  538. if (workingParts.month > 12) {
  539. workingParts.month = 1;
  540. workingParts.year += 1;
  541. }
  542. return workingParts;
  543. };
  544. /**
  545. * Given DatetimeParts, generate the previous month.
  546. */
  547. const getPreviousMonth = (refParts) => {
  548. /**
  549. * If current month is January, wrap backwards
  550. * to December of the previous year.
  551. */
  552. const month = refParts.month === 1 ? 12 : refParts.month - 1;
  553. const year = refParts.month === 1 ? refParts.year - 1 : refParts.year;
  554. const numDaysInMonth = getNumDaysInMonth(month, year);
  555. const day = numDaysInMonth < refParts.day ? numDaysInMonth : refParts.day;
  556. return { month, year, day };
  557. };
  558. /**
  559. * Given DatetimeParts, generate the next month.
  560. */
  561. const getNextMonth = (refParts) => {
  562. /**
  563. * If current month is December, wrap forwards
  564. * to January of the next year.
  565. */
  566. const month = refParts.month === 12 ? 1 : refParts.month + 1;
  567. const year = refParts.month === 12 ? refParts.year + 1 : refParts.year;
  568. const numDaysInMonth = getNumDaysInMonth(month, year);
  569. const day = numDaysInMonth < refParts.day ? numDaysInMonth : refParts.day;
  570. return { month, year, day };
  571. };
  572. const changeYear = (refParts, yearDelta) => {
  573. const month = refParts.month;
  574. const year = refParts.year + yearDelta;
  575. const numDaysInMonth = getNumDaysInMonth(month, year);
  576. const day = numDaysInMonth < refParts.day ? numDaysInMonth : refParts.day;
  577. return { month, year, day };
  578. };
  579. /**
  580. * Given DatetimeParts, generate the previous year.
  581. */
  582. const getPreviousYear = (refParts) => {
  583. return changeYear(refParts, -1);
  584. };
  585. /**
  586. * Given DatetimeParts, generate the next year.
  587. */
  588. const getNextYear = (refParts) => {
  589. return changeYear(refParts, 1);
  590. };
  591. /**
  592. * If PM, then internal value should
  593. * be converted to 24-hr time.
  594. * Does not apply when public
  595. * values are already 24-hr time.
  596. */
  597. const getInternalHourValue = (hour, use24Hour, ampm) => {
  598. if (use24Hour) {
  599. return hour;
  600. }
  601. return convert12HourTo24Hour(hour, ampm);
  602. };
  603. /**
  604. * Unless otherwise stated, all month values are
  605. * 1 indexed instead of the typical 0 index in JS Date.
  606. * Example:
  607. * January = Month 0 when using JS Date
  608. * January = Month 1 when using this datetime util
  609. */
  610. /**
  611. * Given the current datetime parts and a new AM/PM value
  612. * calculate what the hour should be in 24-hour time format.
  613. * Used when toggling the AM/PM segment since we store our hours
  614. * in 24-hour time format internally.
  615. */
  616. const calculateHourFromAMPM = (currentParts, newAMPM) => {
  617. const { ampm: currentAMPM, hour } = currentParts;
  618. let newHour = hour;
  619. /**
  620. * If going from AM --> PM, need to update the
  621. *
  622. */
  623. if (currentAMPM === 'am' && newAMPM === 'pm') {
  624. newHour = convert12HourTo24Hour(newHour, 'pm');
  625. /**
  626. * If going from PM --> AM
  627. */
  628. }
  629. else if (currentAMPM === 'pm' && newAMPM === 'am') {
  630. newHour = Math.abs(newHour - 12);
  631. }
  632. return newHour;
  633. };
  634. /**
  635. * Updates parts to ensure that month and day
  636. * values are valid. For days that do not exist,
  637. * or are outside the min/max bounds, the closest
  638. * valid day is used.
  639. */
  640. const validateParts = (parts, minParts, maxParts) => {
  641. const { month, day, year } = parts;
  642. const partsCopy = clampDate(Object.assign({}, parts), minParts, maxParts);
  643. const numDays = getNumDaysInMonth(month, year);
  644. /**
  645. * If the max number of days
  646. * is greater than the day we want
  647. * to set, update the DatetimeParts
  648. * day field to be the max days.
  649. */
  650. if (day !== null && numDays < day) {
  651. partsCopy.day = numDays;
  652. }
  653. /**
  654. * If value is same day as min day,
  655. * make sure the time value is in bounds.
  656. */
  657. if (minParts !== undefined && isSameDay(partsCopy, minParts)) {
  658. /**
  659. * If the hour is out of bounds,
  660. * update both the hour and minute.
  661. * This is done so that the new time
  662. * is closest to what the user selected.
  663. */
  664. if (partsCopy.hour !== undefined && minParts.hour !== undefined) {
  665. if (partsCopy.hour < minParts.hour) {
  666. partsCopy.hour = minParts.hour;
  667. partsCopy.minute = minParts.minute;
  668. /**
  669. * If only the minute is out of bounds,
  670. * set it to the min minute.
  671. */
  672. }
  673. else if (partsCopy.hour === minParts.hour &&
  674. partsCopy.minute !== undefined &&
  675. minParts.minute !== undefined &&
  676. partsCopy.minute < minParts.minute) {
  677. partsCopy.minute = minParts.minute;
  678. }
  679. }
  680. }
  681. /**
  682. * If value is same day as max day,
  683. * make sure the time value is in bounds.
  684. */
  685. if (maxParts !== undefined && isSameDay(parts, maxParts)) {
  686. /**
  687. * If the hour is out of bounds,
  688. * update both the hour and minute.
  689. * This is done so that the new time
  690. * is closest to what the user selected.
  691. */
  692. if (partsCopy.hour !== undefined && maxParts.hour !== undefined) {
  693. if (partsCopy.hour > maxParts.hour) {
  694. partsCopy.hour = maxParts.hour;
  695. partsCopy.minute = maxParts.minute;
  696. /**
  697. * If only the minute is out of bounds,
  698. * set it to the max minute.
  699. */
  700. }
  701. else if (partsCopy.hour === maxParts.hour &&
  702. partsCopy.minute !== undefined &&
  703. maxParts.minute !== undefined &&
  704. partsCopy.minute > maxParts.minute) {
  705. partsCopy.minute = maxParts.minute;
  706. }
  707. }
  708. }
  709. return partsCopy;
  710. };
  711. /**
  712. * Returns the closest date to refParts
  713. * that also meets the constraints of
  714. * the *Values params.
  715. */
  716. const getClosestValidDate = ({ refParts, monthValues, dayValues, yearValues, hourValues, minuteValues, minParts, maxParts, }) => {
  717. const { hour, minute, day, month, year } = refParts;
  718. const copyParts = Object.assign(Object.assign({}, refParts), { dayOfWeek: undefined });
  719. if (yearValues !== undefined) {
  720. // Filters out years that are out of the min/max bounds
  721. const filteredYears = yearValues.filter((year) => {
  722. if (minParts !== undefined && year < minParts.year) {
  723. return false;
  724. }
  725. if (maxParts !== undefined && year > maxParts.year) {
  726. return false;
  727. }
  728. return true;
  729. });
  730. copyParts.year = findClosestValue(year, filteredYears);
  731. }
  732. if (monthValues !== undefined) {
  733. // Filters out months that are out of the min/max bounds
  734. const filteredMonths = monthValues.filter((month) => {
  735. if (minParts !== undefined && copyParts.year === minParts.year && month < minParts.month) {
  736. return false;
  737. }
  738. if (maxParts !== undefined && copyParts.year === maxParts.year && month > maxParts.month) {
  739. return false;
  740. }
  741. return true;
  742. });
  743. copyParts.month = findClosestValue(month, filteredMonths);
  744. }
  745. // Day is nullable but cannot be undefined
  746. if (day !== null && dayValues !== undefined) {
  747. // Filters out days that are out of the min/max bounds
  748. const filteredDays = dayValues.filter((day) => {
  749. if (minParts !== undefined && isBefore(Object.assign(Object.assign({}, copyParts), { day }), minParts)) {
  750. return false;
  751. }
  752. if (maxParts !== undefined && isAfter(Object.assign(Object.assign({}, copyParts), { day }), maxParts)) {
  753. return false;
  754. }
  755. return true;
  756. });
  757. copyParts.day = findClosestValue(day, filteredDays);
  758. }
  759. if (hour !== undefined && hourValues !== undefined) {
  760. // Filters out hours that are out of the min/max bounds
  761. const filteredHours = hourValues.filter((hour) => {
  762. if ((minParts === null || minParts === void 0 ? void 0 : minParts.hour) !== undefined && isSameDay(copyParts, minParts) && hour < minParts.hour) {
  763. return false;
  764. }
  765. if ((maxParts === null || maxParts === void 0 ? void 0 : maxParts.hour) !== undefined && isSameDay(copyParts, maxParts) && hour > maxParts.hour) {
  766. return false;
  767. }
  768. return true;
  769. });
  770. copyParts.hour = findClosestValue(hour, filteredHours);
  771. copyParts.ampm = parseAmPm(copyParts.hour);
  772. }
  773. if (minute !== undefined && minuteValues !== undefined) {
  774. // Filters out minutes that are out of the min/max bounds
  775. const filteredMinutes = minuteValues.filter((minute) => {
  776. if ((minParts === null || minParts === void 0 ? void 0 : minParts.minute) !== undefined &&
  777. isSameDay(copyParts, minParts) &&
  778. copyParts.hour === minParts.hour &&
  779. minute < minParts.minute) {
  780. return false;
  781. }
  782. if ((maxParts === null || maxParts === void 0 ? void 0 : maxParts.minute) !== undefined &&
  783. isSameDay(copyParts, maxParts) &&
  784. copyParts.hour === maxParts.hour &&
  785. minute > maxParts.minute) {
  786. return false;
  787. }
  788. return true;
  789. });
  790. copyParts.minute = findClosestValue(minute, filteredMinutes);
  791. }
  792. return copyParts;
  793. };
  794. /**
  795. * Finds the value in "values" that is
  796. * numerically closest to "reference".
  797. * This function assumes that "values" is
  798. * already sorted in ascending order.
  799. * @param reference The reference number to use
  800. * when finding the closest value
  801. * @param values The allowed values that will be
  802. * searched to find the closest value to "reference"
  803. */
  804. const findClosestValue = (reference, values) => {
  805. let closestValue = values[0];
  806. let rank = Math.abs(closestValue - reference);
  807. for (let i = 1; i < values.length; i++) {
  808. const value = values[i];
  809. /**
  810. * This code prioritizes the first
  811. * closest result. Given two values
  812. * with the same distance from reference,
  813. * this code will prioritize the smaller of
  814. * the two values.
  815. */
  816. const valueRank = Math.abs(value - reference);
  817. if (valueRank < rank) {
  818. closestValue = value;
  819. rank = valueRank;
  820. }
  821. }
  822. return closestValue;
  823. };
  824. const getFormattedDayPeriod = (dayPeriod) => {
  825. if (dayPeriod === undefined) {
  826. return '';
  827. }
  828. return dayPeriod.toUpperCase();
  829. };
  830. /**
  831. * Including time zone options may lead to the rendered text showing a
  832. * different time from what was selected in the Datetime, which could cause
  833. * confusion.
  834. */
  835. const stripTimeZone = (formatOptions) => {
  836. return Object.assign(Object.assign({}, formatOptions), {
  837. /**
  838. * Setting the time zone to UTC ensures that the value shown is always the
  839. * same as what was selected and safeguards against older Safari bugs with
  840. * Intl.DateTimeFormat.
  841. */
  842. timeZone: 'UTC',
  843. /**
  844. * We do not want to display the time zone name
  845. */
  846. timeZoneName: undefined });
  847. };
  848. const getLocalizedTime = (locale, refParts, hourCycle, formatOptions = { hour: 'numeric', minute: 'numeric' }) => {
  849. const timeParts = {
  850. hour: refParts.hour,
  851. minute: refParts.minute,
  852. };
  853. if (timeParts.hour === undefined || timeParts.minute === undefined) {
  854. return 'Invalid Time';
  855. }
  856. return new Intl.DateTimeFormat(locale, Object.assign(Object.assign({}, stripTimeZone(formatOptions)), {
  857. /**
  858. * We use hourCycle here instead of hour12 due to:
  859. * https://bugs.chromium.org/p/chromium/issues/detail?id=1347316&q=hour12&can=2
  860. */
  861. hourCycle })).format(new Date(convertDataToISO(Object.assign({
  862. /**
  863. * JS uses a simplified ISO 8601 format which allows for
  864. * date-only formats and date-time formats, but not
  865. * time-only formats: https://tc39.es/ecma262/#sec-date-time-string-format
  866. * As a result, developers who only pass a time will get
  867. * an "Invalid Date" error. To account for this, we make sure that
  868. * year/day/month values are set when passing to new Date().
  869. * The Intl.DateTimeFormat call above only uses the hour/minute
  870. * values, so passing these date values should have no impact
  871. * on the time output.
  872. */
  873. year: 2023, day: 1, month: 1 }, timeParts)) + 'Z'));
  874. };
  875. /**
  876. * Adds padding to a time value so
  877. * that it is always 2 digits.
  878. */
  879. const addTimePadding = (value) => {
  880. const valueToString = value.toString();
  881. if (valueToString.length > 1) {
  882. return valueToString;
  883. }
  884. return `0${valueToString}`;
  885. };
  886. /**
  887. * Formats 24 hour times so that
  888. * it always has 2 digits. For
  889. * 12 hour times it ensures that
  890. * hour 0 is formatted as '12'.
  891. */
  892. const getFormattedHour = (hour, hourCycle) => {
  893. /**
  894. * Midnight for h11 starts at 0:00am
  895. * Midnight for h12 starts at 12:00am
  896. * Midnight for h23 starts at 00:00
  897. * Midnight for h24 starts at 24:00
  898. */
  899. if (hour === 0) {
  900. switch (hourCycle) {
  901. case 'h11':
  902. return '0';
  903. case 'h12':
  904. return '12';
  905. case 'h23':
  906. return '00';
  907. case 'h24':
  908. return '24';
  909. default:
  910. throw new Error(`Invalid hour cycle "${hourCycle}"`);
  911. }
  912. }
  913. const use24Hour = is24Hour(hourCycle);
  914. /**
  915. * h23 and h24 use 24 hour times.
  916. */
  917. if (use24Hour) {
  918. return addTimePadding(hour);
  919. }
  920. return hour.toString();
  921. };
  922. /**
  923. * Generates an aria-label to be read by screen readers
  924. * given a local, a date, and whether or not that date is
  925. * today's date.
  926. */
  927. const generateDayAriaLabel = (locale, today, refParts) => {
  928. if (refParts.day === null) {
  929. return null;
  930. }
  931. /**
  932. * MM/DD/YYYY will return midnight in the user's timezone.
  933. */
  934. const date = getNormalizedDate(refParts);
  935. const labelString = new Intl.DateTimeFormat(locale, {
  936. weekday: 'long',
  937. month: 'long',
  938. day: 'numeric',
  939. timeZone: 'UTC',
  940. }).format(date);
  941. /**
  942. * If date is today, prepend "Today" so screen readers indicate
  943. * that the date is today.
  944. */
  945. return today ? `Today, ${labelString}` : labelString;
  946. };
  947. /**
  948. * Given a locale and a date object,
  949. * return a formatted string that includes
  950. * the month name and full year.
  951. * Example: May 2021
  952. */
  953. const getMonthAndYear = (locale, refParts) => {
  954. const date = getNormalizedDate(refParts);
  955. return new Intl.DateTimeFormat(locale, { month: 'long', year: 'numeric', timeZone: 'UTC' }).format(date);
  956. };
  957. /**
  958. * Given a locale and a date object,
  959. * return a formatted string that includes
  960. * the numeric day.
  961. * Note: Some languages will add literal characters
  962. * to the end. This function removes those literals.
  963. * Example: 29
  964. */
  965. const getDay = (locale, refParts) => {
  966. return getLocalizedDateTimeParts(locale, refParts, { day: 'numeric' }).find((obj) => obj.type === 'day').value;
  967. };
  968. /**
  969. * Given a locale and a date object,
  970. * return a formatted string that includes
  971. * the numeric year.
  972. * Example: 2022
  973. */
  974. const getYear = (locale, refParts) => {
  975. return getLocalizedDateTime(locale, refParts, { year: 'numeric' });
  976. };
  977. /**
  978. * Given reference parts, return a JS Date object
  979. * with a normalized time.
  980. */
  981. const getNormalizedDate = (refParts) => {
  982. var _a, _b, _c;
  983. const timeString = refParts.hour !== undefined && refParts.minute !== undefined ? ` ${refParts.hour}:${refParts.minute}` : '';
  984. /**
  985. * We use / notation here for the date
  986. * so we do not need to do extra work and pad values with zeroes.
  987. * Values such as YYYY-MM are still valid, so
  988. * we add fallback values so we still get
  989. * a valid date otherwise we will pass in a string
  990. * like "//2023". Some browsers, such as Chrome, will
  991. * account for this and still return a valid date. However,
  992. * this is not a consistent behavior across all browsers.
  993. */
  994. return new Date(`${(_a = refParts.month) !== null && _a !== void 0 ? _a : 1}/${(_b = refParts.day) !== null && _b !== void 0 ? _b : 1}/${(_c = refParts.year) !== null && _c !== void 0 ? _c : 2023}${timeString} GMT+0000`);
  995. };
  996. /**
  997. * Given a locale, DatetimeParts, and options
  998. * format the DatetimeParts according to the options
  999. * and locale combination. This returns a string. If
  1000. * you want an array of the individual pieces
  1001. * that make up the localized date string, use
  1002. * getLocalizedDateTimeParts.
  1003. */
  1004. const getLocalizedDateTime = (locale, refParts, options) => {
  1005. const date = getNormalizedDate(refParts);
  1006. return getDateTimeFormat(locale, stripTimeZone(options)).format(date);
  1007. };
  1008. /**
  1009. * Given a locale, DatetimeParts, and options
  1010. * format the DatetimeParts according to the options
  1011. * and locale combination. This returns an array of
  1012. * each piece of the date.
  1013. */
  1014. const getLocalizedDateTimeParts = (locale, refParts, options) => {
  1015. const date = getNormalizedDate(refParts);
  1016. return getDateTimeFormat(locale, options).formatToParts(date);
  1017. };
  1018. /**
  1019. * Wrapper function for Intl.DateTimeFormat.
  1020. * Allows developers to apply an allowed format to DatetimeParts.
  1021. * This function also has built in safeguards for older browser bugs
  1022. * with Intl.DateTimeFormat.
  1023. */
  1024. const getDateTimeFormat = (locale, options) => {
  1025. return new Intl.DateTimeFormat(locale, Object.assign(Object.assign({}, options), { timeZone: 'UTC' }));
  1026. };
  1027. /**
  1028. * Gets a localized version of "Today"
  1029. * Falls back to "Today" in English for
  1030. * browsers that do not support RelativeTimeFormat.
  1031. */
  1032. const getTodayLabel = (locale) => {
  1033. if ('RelativeTimeFormat' in Intl) {
  1034. const label = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' }).format(0, 'day');
  1035. return label.charAt(0).toUpperCase() + label.slice(1);
  1036. }
  1037. else {
  1038. return 'Today';
  1039. }
  1040. };
  1041. /**
  1042. * When calling toISOString(), the browser
  1043. * will convert the date to UTC time by either adding
  1044. * or subtracting the time zone offset.
  1045. * To work around this, we need to either add
  1046. * or subtract the time zone offset to the Date
  1047. * object prior to calling toISOString().
  1048. * This allows us to get an ISO string
  1049. * that is in the user's time zone.
  1050. *
  1051. * Example:
  1052. * Time zone offset is 240
  1053. * Meaning: The browser needs to add 240 minutes
  1054. * to the Date object to get UTC time.
  1055. * What Ionic does: We subtract 240 minutes
  1056. * from the Date object. The browser then adds
  1057. * 240 minutes in toISOString(). The result
  1058. * is a time that is in the user's time zone
  1059. * and not UTC.
  1060. *
  1061. * Note: Some timezones include minute adjustments
  1062. * such as 30 or 45 minutes. This is why we use setMinutes
  1063. * instead of setHours.
  1064. * Example: India Standard Time
  1065. * Timezone offset: -330 = -5.5 hours.
  1066. *
  1067. * List of timezones with 30 and 45 minute timezones:
  1068. * https://www.timeanddate.com/time/time-zones-interesting.html
  1069. */
  1070. const removeDateTzOffset = (date) => {
  1071. const tzOffset = date.getTimezoneOffset();
  1072. date.setMinutes(date.getMinutes() - tzOffset);
  1073. return date;
  1074. };
  1075. const DATE_AM = removeDateTzOffset(new Date('2022T01:00'));
  1076. const DATE_PM = removeDateTzOffset(new Date('2022T13:00'));
  1077. /**
  1078. * Formats the locale's string representation of the day period (am/pm) for a given
  1079. * ref parts day period.
  1080. *
  1081. * @param locale The locale to format the day period in.
  1082. * @param value The date string, in ISO format.
  1083. * @returns The localized day period (am/pm) representation of the given value.
  1084. */
  1085. const getLocalizedDayPeriod = (locale, dayPeriod) => {
  1086. const date = dayPeriod === 'am' ? DATE_AM : DATE_PM;
  1087. const localizedDayPeriod = new Intl.DateTimeFormat(locale, {
  1088. hour: 'numeric',
  1089. timeZone: 'UTC',
  1090. })
  1091. .formatToParts(date)
  1092. .find((part) => part.type === 'dayPeriod');
  1093. if (localizedDayPeriod) {
  1094. return localizedDayPeriod.value;
  1095. }
  1096. return getFormattedDayPeriod(dayPeriod);
  1097. };
  1098. /**
  1099. * Formats the datetime's value to a string, for use in the native input.
  1100. *
  1101. * @param value The value to format, either an ISO string or an array thereof.
  1102. */
  1103. const formatValue = (value) => {
  1104. return Array.isArray(value) ? value.join(',') : value;
  1105. };
  1106. /**
  1107. * Returns the current date as
  1108. * an ISO string in the user's
  1109. * time zone.
  1110. */
  1111. const getToday = () => {
  1112. /**
  1113. * ion-datetime intentionally does not
  1114. * parse time zones/do automatic time zone
  1115. * conversion when accepting user input.
  1116. * However when we get today's date string,
  1117. * we want it formatted relative to the user's
  1118. * time zone.
  1119. *
  1120. * When calling toISOString(), the browser
  1121. * will convert the date to UTC time by either adding
  1122. * or subtracting the time zone offset.
  1123. * To work around this, we need to either add
  1124. * or subtract the time zone offset to the Date
  1125. * object prior to calling toISOString().
  1126. * This allows us to get an ISO string
  1127. * that is in the user's time zone.
  1128. */
  1129. return removeDateTzOffset(new Date()).toISOString();
  1130. };
  1131. const minutes = [
  1132. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
  1133. 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
  1134. ];
  1135. // h11 hour system uses 0-11. Midnight starts at 0:00am.
  1136. const hour11 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
  1137. // h12 hour system uses 0-12. Midnight starts at 12:00am.
  1138. const hour12 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
  1139. // h23 hour system uses 0-23. Midnight starts at 0:00.
  1140. const hour23 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23];
  1141. // h24 hour system uses 1-24. Midnight starts at 24:00.
  1142. const hour24 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 0];
  1143. /**
  1144. * Given a locale and a mode,
  1145. * return an array with formatted days
  1146. * of the week. iOS should display days
  1147. * such as "Mon" or "Tue".
  1148. * MD should display days such as "M"
  1149. * or "T".
  1150. */
  1151. const getDaysOfWeek = (locale, mode, firstDayOfWeek = 0) => {
  1152. /**
  1153. * Nov 1st, 2020 starts on a Sunday.
  1154. * ion-datetime assumes weeks start on Sunday,
  1155. * but is configurable via `firstDayOfWeek`.
  1156. */
  1157. const weekdayFormat = mode === 'ios' ? 'short' : 'narrow';
  1158. const intl = new Intl.DateTimeFormat(locale, { weekday: weekdayFormat });
  1159. const startDate = new Date('11/01/2020');
  1160. const daysOfWeek = [];
  1161. /**
  1162. * For each day of the week,
  1163. * get the day name.
  1164. */
  1165. for (let i = firstDayOfWeek; i < firstDayOfWeek + 7; i++) {
  1166. const currentDate = new Date(startDate);
  1167. currentDate.setDate(currentDate.getDate() + i);
  1168. daysOfWeek.push(intl.format(currentDate));
  1169. }
  1170. return daysOfWeek;
  1171. };
  1172. /**
  1173. * Returns an array containing all of the
  1174. * days in a month for a given year. Values are
  1175. * aligned with a week calendar starting on
  1176. * the firstDayOfWeek value (Sunday by default)
  1177. * using null values.
  1178. */
  1179. const getDaysOfMonth = (month, year, firstDayOfWeek) => {
  1180. const numDays = getNumDaysInMonth(month, year);
  1181. const firstOfMonth = new Date(`${month}/1/${year}`).getDay();
  1182. /**
  1183. * To get the first day of the month aligned on the correct
  1184. * day of the week, we need to determine how many "filler" days
  1185. * to generate. These filler days as empty/disabled buttons
  1186. * that fill the space of the days of the week before the first
  1187. * of the month.
  1188. *
  1189. * There are two cases here:
  1190. *
  1191. * 1. If firstOfMonth = 4, firstDayOfWeek = 0 then the offset
  1192. * is (4 - (0 + 1)) = 3. Since the offset loop goes from 0 to 3 inclusive,
  1193. * this will generate 4 filler days (0, 1, 2, 3), and then day of week 4 will have
  1194. * the first day of the month.
  1195. *
  1196. * 2. If firstOfMonth = 2, firstDayOfWeek = 4 then the offset
  1197. * is (6 - (4 - 2)) = 4. Since the offset loop goes from 0 to 4 inclusive,
  1198. * this will generate 5 filler days (0, 1, 2, 3, 4), and then day of week 5 will have
  1199. * the first day of the month.
  1200. */
  1201. const offset = firstOfMonth >= firstDayOfWeek ? firstOfMonth - (firstDayOfWeek + 1) : 6 - (firstDayOfWeek - firstOfMonth);
  1202. let days = [];
  1203. for (let i = 1; i <= numDays; i++) {
  1204. days.push({ day: i, dayOfWeek: (offset + i) % 7 });
  1205. }
  1206. for (let i = 0; i <= offset; i++) {
  1207. days = [{ day: null, dayOfWeek: null }, ...days];
  1208. }
  1209. return days;
  1210. };
  1211. /**
  1212. * Returns an array of pre-defined hour
  1213. * values based on the provided hourCycle.
  1214. */
  1215. const getHourData = (hourCycle) => {
  1216. switch (hourCycle) {
  1217. case 'h11':
  1218. return hour11;
  1219. case 'h12':
  1220. return hour12;
  1221. case 'h23':
  1222. return hour23;
  1223. case 'h24':
  1224. return hour24;
  1225. default:
  1226. throw new Error(`Invalid hour cycle "${hourCycle}"`);
  1227. }
  1228. };
  1229. /**
  1230. * Given a local, reference datetime parts and option
  1231. * max/min bound datetime parts, calculate the acceptable
  1232. * hour and minute values according to the bounds and locale.
  1233. */
  1234. const generateTime = (locale, refParts, hourCycle = 'h12', minParts, maxParts, hourValues, minuteValues) => {
  1235. const computedHourCycle = getHourCycle(locale, hourCycle);
  1236. const use24Hour = is24Hour(computedHourCycle);
  1237. let processedHours = getHourData(computedHourCycle);
  1238. let processedMinutes = minutes;
  1239. let isAMAllowed = true;
  1240. let isPMAllowed = true;
  1241. if (hourValues) {
  1242. processedHours = processedHours.filter((hour) => hourValues.includes(hour));
  1243. }
  1244. if (minuteValues) {
  1245. processedMinutes = processedMinutes.filter((minute) => minuteValues.includes(minute));
  1246. }
  1247. if (minParts) {
  1248. /**
  1249. * If ref day is the same as the
  1250. * minimum allowed day, filter hour/minute
  1251. * values according to min hour and minute.
  1252. */
  1253. if (isSameDay(refParts, minParts)) {
  1254. /**
  1255. * Users may not always set the hour/minute for
  1256. * min value (i.e. 2021-06-02) so we should allow
  1257. * all hours/minutes in that case.
  1258. */
  1259. if (minParts.hour !== undefined) {
  1260. processedHours = processedHours.filter((hour) => {
  1261. const convertedHour = refParts.ampm === 'pm' ? (hour + 12) % 24 : hour;
  1262. return (use24Hour ? hour : convertedHour) >= minParts.hour;
  1263. });
  1264. isAMAllowed = minParts.hour < 13;
  1265. }
  1266. if (minParts.minute !== undefined) {
  1267. /**
  1268. * The minimum minute range should not be enforced when
  1269. * the hour is greater than the min hour.
  1270. *
  1271. * For example with a minimum range of 09:30, users
  1272. * should be able to select 10:00-10:29 and beyond.
  1273. */
  1274. let isPastMinHour = false;
  1275. if (minParts.hour !== undefined && refParts.hour !== undefined) {
  1276. if (refParts.hour > minParts.hour) {
  1277. isPastMinHour = true;
  1278. }
  1279. }
  1280. processedMinutes = processedMinutes.filter((minute) => {
  1281. if (isPastMinHour) {
  1282. return true;
  1283. }
  1284. return minute >= minParts.minute;
  1285. });
  1286. }
  1287. /**
  1288. * If ref day is before minimum
  1289. * day do not render any hours/minute values
  1290. */
  1291. }
  1292. else if (isBefore(refParts, minParts)) {
  1293. processedHours = [];
  1294. processedMinutes = [];
  1295. isAMAllowed = isPMAllowed = false;
  1296. }
  1297. }
  1298. if (maxParts) {
  1299. /**
  1300. * If ref day is the same as the
  1301. * maximum allowed day, filter hour/minute
  1302. * values according to max hour and minute.
  1303. */
  1304. if (isSameDay(refParts, maxParts)) {
  1305. /**
  1306. * Users may not always set the hour/minute for
  1307. * max value (i.e. 2021-06-02) so we should allow
  1308. * all hours/minutes in that case.
  1309. */
  1310. if (maxParts.hour !== undefined) {
  1311. processedHours = processedHours.filter((hour) => {
  1312. const convertedHour = refParts.ampm === 'pm' ? (hour + 12) % 24 : hour;
  1313. return (use24Hour ? hour : convertedHour) <= maxParts.hour;
  1314. });
  1315. isPMAllowed = maxParts.hour >= 12;
  1316. }
  1317. if (maxParts.minute !== undefined && refParts.hour === maxParts.hour) {
  1318. // The available minutes should only be filtered when the hour is the same as the max hour.
  1319. // For example if the max hour is 10:30 and the current hour is 10:00,
  1320. // users should be able to select 00-30 minutes.
  1321. // If the current hour is 09:00, users should be able to select 00-60 minutes.
  1322. processedMinutes = processedMinutes.filter((minute) => minute <= maxParts.minute);
  1323. }
  1324. /**
  1325. * If ref day is after minimum
  1326. * day do not render any hours/minute values
  1327. */
  1328. }
  1329. else if (isAfter(refParts, maxParts)) {
  1330. processedHours = [];
  1331. processedMinutes = [];
  1332. isAMAllowed = isPMAllowed = false;
  1333. }
  1334. }
  1335. return {
  1336. hours: processedHours,
  1337. minutes: processedMinutes,
  1338. am: isAMAllowed,
  1339. pm: isPMAllowed,
  1340. };
  1341. };
  1342. /**
  1343. * Given DatetimeParts, generate the previous,
  1344. * current, and and next months.
  1345. */
  1346. const generateMonths = (refParts, forcedDate) => {
  1347. const current = { month: refParts.month, year: refParts.year, day: refParts.day };
  1348. /**
  1349. * If we're forcing a month to appear, and it's different from the current month,
  1350. * ensure it appears by replacing the next or previous month as appropriate.
  1351. */
  1352. if (forcedDate !== undefined && (refParts.month !== forcedDate.month || refParts.year !== forcedDate.year)) {
  1353. const forced = { month: forcedDate.month, year: forcedDate.year, day: forcedDate.day };
  1354. const forcedMonthIsBefore = isBefore(forced, current);
  1355. return forcedMonthIsBefore
  1356. ? [forced, current, getNextMonth(refParts)]
  1357. : [getPreviousMonth(refParts), current, forced];
  1358. }
  1359. return [getPreviousMonth(refParts), current, getNextMonth(refParts)];
  1360. };
  1361. const getMonthColumnData = (locale, refParts, minParts, maxParts, monthValues, formatOptions = {
  1362. month: 'long',
  1363. }) => {
  1364. const { year } = refParts;
  1365. const months = [];
  1366. if (monthValues !== undefined) {
  1367. let processedMonths = monthValues;
  1368. if ((maxParts === null || maxParts === void 0 ? void 0 : maxParts.month) !== undefined) {
  1369. processedMonths = processedMonths.filter((month) => month <= maxParts.month);
  1370. }
  1371. if ((minParts === null || minParts === void 0 ? void 0 : minParts.month) !== undefined) {
  1372. processedMonths = processedMonths.filter((month) => month >= minParts.month);
  1373. }
  1374. processedMonths.forEach((processedMonth) => {
  1375. const date = new Date(`${processedMonth}/1/${year} GMT+0000`);
  1376. const monthString = new Intl.DateTimeFormat(locale, Object.assign(Object.assign({}, formatOptions), { timeZone: 'UTC' })).format(date);
  1377. months.push({ text: monthString, value: processedMonth });
  1378. });
  1379. }
  1380. else {
  1381. const maxMonth = maxParts && maxParts.year === year ? maxParts.month : 12;
  1382. const minMonth = minParts && minParts.year === year ? minParts.month : 1;
  1383. for (let i = minMonth; i <= maxMonth; i++) {
  1384. /**
  1385. *
  1386. * There is a bug on iOS 14 where
  1387. * Intl.DateTimeFormat takes into account
  1388. * the local timezone offset when formatting dates.
  1389. *
  1390. * Forcing the timezone to 'UTC' fixes the issue. However,
  1391. * we should keep this workaround as it is safer. In the event
  1392. * this breaks in another browser, we will not be impacted
  1393. * because all dates will be interpreted in UTC.
  1394. *
  1395. * Example:
  1396. * new Intl.DateTimeFormat('en-US', { month: 'long' }).format(new Date('Sat Apr 01 2006 00:00:00 GMT-0400 (EDT)')) // "March"
  1397. * new Intl.DateTimeFormat('en-US', { month: 'long', timeZone: 'UTC' }).format(new Date('Sat Apr 01 2006 00:00:00 GMT-0400 (EDT)')) // "April"
  1398. *
  1399. * In certain timezones, iOS 14 shows the wrong
  1400. * date for .toUTCString(). To combat this, we
  1401. * force all of the timezones to GMT+0000 (UTC).
  1402. *
  1403. * Example:
  1404. * Time Zone: Central European Standard Time
  1405. * new Date('1/1/1992').toUTCString() // "Tue, 31 Dec 1991 23:00:00 GMT"
  1406. * new Date('1/1/1992 GMT+0000').toUTCString() // "Wed, 01 Jan 1992 00:00:00 GMT"
  1407. */
  1408. const date = new Date(`${i}/1/${year} GMT+0000`);
  1409. const monthString = new Intl.DateTimeFormat(locale, Object.assign(Object.assign({}, formatOptions), { timeZone: 'UTC' })).format(date);
  1410. months.push({ text: monthString, value: i });
  1411. }
  1412. }
  1413. return months;
  1414. };
  1415. /**
  1416. * Returns information regarding
  1417. * selectable dates (i.e 1st, 2nd, 3rd, etc)
  1418. * within a reference month.
  1419. * @param locale The locale to format the date with
  1420. * @param refParts The reference month/year to generate dates for
  1421. * @param minParts The minimum bound on the date that can be returned
  1422. * @param maxParts The maximum bound on the date that can be returned
  1423. * @param dayValues The allowed date values
  1424. * @returns Date data to be used in ion-picker-column
  1425. */
  1426. const getDayColumnData = (locale, refParts, minParts, maxParts, dayValues, formatOptions = {
  1427. day: 'numeric',
  1428. }) => {
  1429. const { month, year } = refParts;
  1430. const days = [];
  1431. /**
  1432. * If we have max/min bounds that in the same
  1433. * month/year as the refParts, we should
  1434. * use the define day as the max/min day.
  1435. * Otherwise, fallback to the max/min days in a month.
  1436. */
  1437. const numDaysInMonth = getNumDaysInMonth(month, year);
  1438. const maxDay = (maxParts === null || maxParts === void 0 ? void 0 : maxParts.day) !== null && (maxParts === null || maxParts === void 0 ? void 0 : maxParts.day) !== undefined && maxParts.year === year && maxParts.month === month
  1439. ? maxParts.day
  1440. : numDaysInMonth;
  1441. const minDay = (minParts === null || minParts === void 0 ? void 0 : minParts.day) !== null && (minParts === null || minParts === void 0 ? void 0 : minParts.day) !== undefined && minParts.year === year && minParts.month === month
  1442. ? minParts.day
  1443. : 1;
  1444. if (dayValues !== undefined) {
  1445. let processedDays = dayValues;
  1446. processedDays = processedDays.filter((day) => day >= minDay && day <= maxDay);
  1447. processedDays.forEach((processedDay) => {
  1448. const date = new Date(`${month}/${processedDay}/${year} GMT+0000`);
  1449. const dayString = new Intl.DateTimeFormat(locale, Object.assign(Object.assign({}, formatOptions), { timeZone: 'UTC' })).format(date);
  1450. days.push({ text: dayString, value: processedDay });
  1451. });
  1452. }
  1453. else {
  1454. for (let i = minDay; i <= maxDay; i++) {
  1455. const date = new Date(`${month}/${i}/${year} GMT+0000`);
  1456. const dayString = new Intl.DateTimeFormat(locale, Object.assign(Object.assign({}, formatOptions), { timeZone: 'UTC' })).format(date);
  1457. days.push({ text: dayString, value: i });
  1458. }
  1459. }
  1460. return days;
  1461. };
  1462. const getYearColumnData = (locale, refParts, minParts, maxParts, yearValues) => {
  1463. var _a, _b;
  1464. let processedYears = [];
  1465. if (yearValues !== undefined) {
  1466. processedYears = yearValues;
  1467. if ((maxParts === null || maxParts === void 0 ? void 0 : maxParts.year) !== undefined) {
  1468. processedYears = processedYears.filter((year) => year <= maxParts.year);
  1469. }
  1470. if ((minParts === null || minParts === void 0 ? void 0 : minParts.year) !== undefined) {
  1471. processedYears = processedYears.filter((year) => year >= minParts.year);
  1472. }
  1473. }
  1474. else {
  1475. const { year } = refParts;
  1476. const maxYear = (_a = maxParts === null || maxParts === void 0 ? void 0 : maxParts.year) !== null && _a !== void 0 ? _a : year;
  1477. const minYear = (_b = minParts === null || minParts === void 0 ? void 0 : minParts.year) !== null && _b !== void 0 ? _b : year - 100;
  1478. for (let i = minYear; i <= maxYear; i++) {
  1479. processedYears.push(i);
  1480. }
  1481. }
  1482. return processedYears.map((year) => ({
  1483. text: getYear(locale, { year, month: refParts.month, day: refParts.day }),
  1484. value: year,
  1485. }));
  1486. };
  1487. /**
  1488. * Given a starting date and an upper bound,
  1489. * this functions returns an array of all
  1490. * month objects in that range.
  1491. */
  1492. const getAllMonthsInRange = (currentParts, maxParts) => {
  1493. if (currentParts.month === maxParts.month && currentParts.year === maxParts.year) {
  1494. return [currentParts];
  1495. }
  1496. return [currentParts, ...getAllMonthsInRange(getNextMonth(currentParts), maxParts)];
  1497. };
  1498. /**
  1499. * Creates and returns picker items
  1500. * that represent the days in a month.
  1501. * Example: "Thu, Jun 2"
  1502. */
  1503. const getCombinedDateColumnData = (locale, todayParts, minParts, maxParts, dayValues, monthValues) => {
  1504. let items = [];
  1505. let parts = [];
  1506. /**
  1507. * Get all month objects from the min date
  1508. * to the max date. Note: Do not use getMonthColumnData
  1509. * as that function only generates dates within a
  1510. * single year.
  1511. */
  1512. let months = getAllMonthsInRange(minParts, maxParts);
  1513. /**
  1514. * Filter out any disallowed month values.
  1515. */
  1516. if (monthValues) {
  1517. months = months.filter(({ month }) => monthValues.includes(month));
  1518. }
  1519. /**
  1520. * Get all of the days in the month.
  1521. * From there, generate an array where
  1522. * each item has the month, date, and day
  1523. * of work as the text.
  1524. */
  1525. months.forEach((monthObject) => {
  1526. const referenceMonth = { month: monthObject.month, day: null, year: monthObject.year };
  1527. const monthDays = getDayColumnData(locale, referenceMonth, minParts, maxParts, dayValues, {
  1528. month: 'short',
  1529. day: 'numeric',
  1530. weekday: 'short',
  1531. });
  1532. const dateParts = [];
  1533. const dateColumnItems = [];
  1534. monthDays.forEach((dayObject) => {
  1535. const isToday = isSameDay(Object.assign(Object.assign({}, referenceMonth), { day: dayObject.value }), todayParts);
  1536. /**
  1537. * Today's date should read as "Today" (localized)
  1538. * not the actual date string
  1539. */
  1540. dateColumnItems.push({
  1541. text: isToday ? getTodayLabel(locale) : dayObject.text,
  1542. value: `${referenceMonth.year}-${referenceMonth.month}-${dayObject.value}`,
  1543. });
  1544. /**
  1545. * When selecting a date in the wheel picker
  1546. * we need access to the raw datetime parts data.
  1547. * The picker column only accepts values of
  1548. * type string or number, so we need to return
  1549. * two sets of data: A data set to be passed
  1550. * to the picker column, and a data set to
  1551. * be used to reference the raw data when
  1552. * updating the picker column value.
  1553. */
  1554. dateParts.push({
  1555. month: referenceMonth.month,
  1556. year: referenceMonth.year,
  1557. day: dayObject.value,
  1558. });
  1559. });
  1560. parts = [...parts, ...dateParts];
  1561. items = [...items, ...dateColumnItems];
  1562. });
  1563. return {
  1564. parts,
  1565. items,
  1566. };
  1567. };
  1568. const getTimeColumnsData = (locale, refParts, hourCycle, minParts, maxParts, allowedHourValues, allowedMinuteValues) => {
  1569. const computedHourCycle = getHourCycle(locale, hourCycle);
  1570. const use24Hour = is24Hour(computedHourCycle);
  1571. const { hours, minutes, am, pm } = generateTime(locale, refParts, computedHourCycle, minParts, maxParts, allowedHourValues, allowedMinuteValues);
  1572. const hoursItems = hours.map((hour) => {
  1573. return {
  1574. text: getFormattedHour(hour, computedHourCycle),
  1575. value: getInternalHourValue(hour, use24Hour, refParts.ampm),
  1576. };
  1577. });
  1578. const minutesItems = minutes.map((minute) => {
  1579. return {
  1580. text: addTimePadding(minute),
  1581. value: minute,
  1582. };
  1583. });
  1584. const dayPeriodItems = [];
  1585. if (am && !use24Hour) {
  1586. dayPeriodItems.push({
  1587. text: getLocalizedDayPeriod(locale, 'am'),
  1588. value: 'am',
  1589. });
  1590. }
  1591. if (pm && !use24Hour) {
  1592. dayPeriodItems.push({
  1593. text: getLocalizedDayPeriod(locale, 'pm'),
  1594. value: 'pm',
  1595. });
  1596. }
  1597. return {
  1598. minutesData: minutesItems,
  1599. hoursData: hoursItems,
  1600. dayPeriodData: dayPeriodItems,
  1601. };
  1602. };
  1603. export { getNumDaysInMonth as A, getCombinedDateColumnData as B, getMonthColumnData as C, getDayColumnData as D, getYearColumnData as E, isMonthFirstLocale as F, getTimeColumnsData as G, isLocaleDayPeriodRTL as H, getMonthAndYear as I, getDaysOfWeek as J, getDaysOfMonth as K, getHourCycle as L, getLocalizedTime as M, getLocalizedDateTime as N, formatValue as O, clampDate as P, parseAmPm as Q, calculateHourFromAMPM as R, getDay as a, isAfter as b, isSameDay as c, getPreviousMonth as d, getNextMonth as e, getPartsFromCalendarDay as f, generateDayAriaLabel as g, getNextYear as h, isBefore as i, getPreviousYear as j, getEndOfWeek as k, getStartOfWeek as l, getPreviousDay as m, getNextDay as n, getPreviousWeek as o, getNextWeek as p, parseMinParts as q, parseMaxParts as r, parseDate as s, convertToArrayOfNumbers as t, convertDataToISO as u, validateParts as v, warnIfValueOutOfBounds as w, getToday as x, getClosestValidDate as y, generateMonths as z };