123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  1. var __extends = (this && this.__extends) || (function () {
  2. var extendStatics = Object.setPrototypeOf ||
  3. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  4. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  5. return function (d, b) {
  6. extendStatics(d, b);
  7. function __() { this.constructor = d; }
  8. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  9. };
  10. })();
  11. var __assign = (this && this.__assign) || Object.assign || function(t) {
  12. for (var s, i = 1, n = arguments.length; i < n; i++) {
  13. s = arguments[i];
  14. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  15. t[p] = s[p];
  16. }
  17. return t;
  18. };
  19. import { Component, ElementRef, EventEmitter, HostListener, Input, Optional, Output, Renderer, ViewEncapsulation } from '@angular/core';
  20. import { NG_VALUE_ACCESSOR } from '@angular/forms';
  21. import { Config } from '../../config/config';
  22. import { PickerController } from '../picker/picker-controller';
  23. import { Form } from '../../util/form';
  24. import { BaseInput } from '../../util/base-input';
  25. import { Item } from '../item/item';
  26. import { clamp, isArray, isBlank, isObject, isPresent, isString } from '../../util/util';
  27. import { compareDates, convertDataToISO, convertFormatToKey, dateDataSortValue, dateSortValue, dateValueRange, daysInMonth, getValueFromFormat, parseDate, parseTemplate, renderDateTime, renderTextFormat, updateDate, } from '../../util/datetime-util';
  28. /**
  29. * @name DateTime
  30. * @description
  31. * The DateTime component is used to present an interface which makes it easy for
  32. * users to select dates and times. Tapping on `<ion-datetime>` will display a picker
  33. * interface that slides up from the bottom of the page. The picker then displays
  34. * scrollable columns that can be used to individually select years, months, days,
  35. * hours and minute values. The DateTime component is similar to the native
  36. * `<input type="datetime-local">` element, however, Ionic's DateTime component makes
  37. * it easy to display the date and time in a preferred format, and manage the datetime
  38. * values.
  39. *
  40. * ```html
  41. * <ion-item>
  42. * <ion-label>Date</ion-label>
  43. * <ion-datetime displayFormat="MM/DD/YYYY" [(ngModel)]="myDate"></ion-datetime>
  44. * </ion-item>
  45. * ```
  46. *
  47. *
  48. * ## Display and Picker Formats
  49. *
  50. * The DateTime component displays the values in two places: in the `<ion-datetime>`
  51. * component, and in the interface that is presented from the bottom of the screen.
  52. * The following chart lists all of the formats that can be used.
  53. *
  54. * | Format | Description | Example |
  55. * |---------|--------------------------------|-------------------------|
  56. * | `YYYY` | Year, 4 digits | `2018` |
  57. * | `YY` | Year, 2 digits | `18` |
  58. * | `M` | Month | `1` ... `12` |
  59. * | `MM` | Month, leading zero | `01` ... `12` |
  60. * | `MMM` | Month, short name | `Jan` |
  61. * | `MMMM` | Month, full name | `January` |
  62. * | `D` | Day | `1` ... `31` |
  63. * | `DD` | Day, leading zero | `01` ... `31` |
  64. * | `DDD` | Day, short name | `Fri` |
  65. * | `DDDD` | Day, full name | `Friday` |
  66. * | `H` | Hour, 24-hour | `0` ... `23` |
  67. * | `HH` | Hour, 24-hour, leading zero | `00` ... `23` |
  68. * | `h` | Hour, 12-hour | `1` ... `12` |
  69. * | `hh` | Hour, 12-hour, leading zero | `01` ... `12` |
  70. * | `a` | 12-hour time period, lowercase | `am` `pm` |
  71. * | `A` | 12-hour time period, uppercase | `AM` `PM` |
  72. * | `m` | Minute | `1` ... `59` |
  73. * | `mm` | Minute, leading zero | `01` ... `59` |
  74. * | `s` | Second | `1` ... `59` |
  75. * | `ss` | Second, leading zero | `01` ... `59` |
  76. * | `Z` | UTC Timezone Offset | `Z or +HH:mm or -HH:mm` |
  77. *
  78. * **Important**: See the [Month Names and Day of the Week Names](#month-names-and-day-of-the-week-names)
  79. * section below on how to use different names for the month and day.
  80. *
  81. * ### Display Format
  82. *
  83. * The `displayFormat` input property specifies how a datetime's value should be
  84. * printed, as formatted text, within the `ion-datetime` component.
  85. *
  86. * In the following example, the display in the `<ion-datetime>` will use the
  87. * month's short name, the numerical day with a leading zero, a comma and the
  88. * four-digit year. In addition to the date, it will display the time with the hours
  89. * in the 24-hour format and the minutes. Any character can be used as a separator.
  90. * An example display using this format is: `Jun 17, 2005 11:06`.
  91. *
  92. * ```html
  93. * <ion-item>
  94. * <ion-label>Date</ion-label>
  95. * <ion-datetime displayFormat="MMM DD, YYYY HH:mm" [(ngModel)]="myDate"></ion-datetime>
  96. * </ion-item>
  97. * ```
  98. *
  99. * ### Picker Format
  100. *
  101. * The `pickerFormat` input property determines which columns should be shown in the
  102. * interface, the order of the columns, and which format to use within each column.
  103. * If the `pickerFormat` input is not provided then it will default to the `displayFormat`.
  104. *
  105. * In the following example, the display in the `<ion-datetime>` will use the
  106. * `MM/YYYY` format, such as `06/2020`. However, the picker interface
  107. * will display two columns with the month's long name, and the four-digit year.
  108. *
  109. * ```html
  110. * <ion-item>
  111. * <ion-label>Date</ion-label>
  112. * <ion-datetime displayFormat="MM/YYYY" pickerFormat="MMMM YYYY" [(ngModel)]="myDate"></ion-datetime>
  113. * </ion-item>
  114. * ```
  115. *
  116. * ### Datetime Data
  117. *
  118. * Historically, handling datetime values within JavaScript, or even within HTML
  119. * inputs, has always been a challenge. Specifically, JavaScript's `Date` object is
  120. * notoriously difficult to correctly parse apart datetime strings or to format
  121. * datetime values. Even worse is how different browsers and JavaScript versions
  122. * parse various datetime strings differently, especially per locale.
  123. *
  124. * But no worries, all is not lost! Ionic's datetime input has been designed so
  125. * developers can avoid the common pitfalls, allowing developers to easily format
  126. * datetime values within the input, and give the user a simple datetime picker for a
  127. * great user experience.
  128. *
  129. * ##### ISO 8601 Datetime Format: YYYY-MM-DDTHH:mmZ
  130. *
  131. * Ionic uses the [ISO 8601 datetime format](https://www.w3.org/TR/NOTE-datetime)
  132. * for its value. The value is simply a string, rather than using JavaScript's `Date`
  133. * object. Additionally, when using the ISO datetime format, it makes it easier
  134. * to serialize and pass within JSON objects, and sending databases a standardized
  135. * format which it can be easily parsed if need be.
  136. *
  137. * To create an ISO datetime string for the current date and time, e.g. use `const currentDate = (new Date()).toISOString();`.
  138. *
  139. * An ISO format can be used as a simple year, or just the hour and minute, or get more
  140. * detailed down to the millisecond and timezone. Any of the ISO formats below can be used,
  141. * and after a user selects a new value, Ionic will continue to use the same ISO format
  142. * which datetime value was originally given as.
  143. *
  144. * | Description | Format | Datetime Value Example |
  145. * |----------------------|------------------------|------------------------------|
  146. * | Year | YYYY | 1994 |
  147. * | Year and Month | YYYY-MM | 1994-12 |
  148. * | Complete Date | YYYY-MM-DD | 1994-12-15 |
  149. * | Date and Time | YYYY-MM-DDTHH:mm | 1994-12-15T13:47 |
  150. * | UTC Timezone | YYYY-MM-DDTHH:mm:ssTZD | 1994-12-15T13:47:20.789Z |
  151. * | Timezone Offset | YYYY-MM-DDTHH:mm:ssTZD | 1994-12-15T13:47:20.789+5:00 |
  152. * | Hour and Minute | HH:mm | 13:47 |
  153. * | Hour, Minute, Second | HH:mm:ss | 13:47:20 |
  154. *
  155. * Note that the year is always four-digits, milliseconds (if it's added) is always
  156. * three-digits, and all others are always two-digits. So the number representing
  157. * January always has a leading zero, such as `01`. Additionally, the hour is always
  158. * in the 24-hour format, so `00` is `12am` on a 12-hour clock, `13` means `1pm`,
  159. * and `23` means `11pm`.
  160. *
  161. * It's also important to note that neither the `displayFormat` or `pickerFormat` can
  162. * set the datetime value's output, which is the value that is set by the component's
  163. * `ngModel`. The format's are merely for displaying the value as text and the picker's
  164. * interface, but the datetime's value is always persisted as a valid ISO 8601 datetime
  165. * string.
  166. *
  167. *
  168. * ## Min and Max Datetimes
  169. *
  170. * Dates are infinite in either direction, so for a user's selection there should be at
  171. * least some form of restricting the dates that can be selected. By default, the maximum
  172. * date is to the end of the current year, and the minimum date is from the beginning
  173. * of the year that was 100 years ago.
  174. *
  175. * To customize the minimum and maximum datetime values, the `min` and `max` component
  176. * inputs can be provided which may make more sense for the app's use-case, rather
  177. * than the default of the last 100 years. Following the same IS0 8601 format listed
  178. * in the table above, each component can restrict which dates can be selected by the
  179. * user. Below is an example of restricting the date selection between the beginning
  180. * of 2016, and October 31st of 2020:
  181. *
  182. * ```html
  183. * <ion-item>
  184. * <ion-label>Date</ion-label>
  185. * <ion-datetime displayFormat="MMMM YYYY" min="2016" max="2020-10-31" [(ngModel)]="myDate">
  186. * </ion-datetime>
  187. * </ion-item>
  188. * ```
  189. *
  190. *
  191. * ## Month Names and Day of the Week Names
  192. *
  193. * At this time, there is no one-size-fits-all standard to automatically choose the correct
  194. * language/spelling for a month name, or day of the week name, depending on the language
  195. * or locale. Good news is that there is an
  196. * [Intl.DateTimeFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat)
  197. * standard which *most* browsers have adopted. However, at this time the standard has not
  198. * been fully implemented by all popular browsers so Ionic is unavailable to take advantage
  199. * of it *yet*. Additionally, Angular also provides an internationalization service, but it
  200. * is still under heavy development so Ionic does not depend on it at this time.
  201. *
  202. * All things considered, the by far easiest solution is to just provide an array of names
  203. * if the app needs to use names other than the default English version of month and day
  204. * names. The month names and day names can be either configured at the app level, or
  205. * individual `ion-datetime` level.
  206. *
  207. * ### App Config Level
  208. *
  209. * ```ts
  210. * //app.module.ts
  211. * @NgModule({
  212. * ...,
  213. * imports: [
  214. * IonicModule.forRoot(MyApp, {
  215. * monthNames: ['janeiro', 'fevereiro', 'mar\u00e7o', ... ],
  216. * monthShortNames: ['jan', 'fev', 'mar', ... ],
  217. * dayNames: ['domingo', 'segunda-feira', 'ter\u00e7a-feira', ... ],
  218. * dayShortNames: ['dom', 'seg', 'ter', ... ],
  219. * })
  220. * ],
  221. * ...
  222. * })
  223. * ```
  224. *
  225. * ### Component Input Level
  226. *
  227. * ```html
  228. * <ion-item>
  229. * <ion-label>Período</ion-label>
  230. * <ion-datetime displayFormat="DDDD MMM D, YYYY" [(ngModel)]="myDate"
  231. * monthNames="janeiro, fevereiro, mar\u00e7o, ..."
  232. * monthShortNames="jan, fev, mar, ..."
  233. * dayNames="domingo, segunda-feira, ter\u00e7a-feira, ..."
  234. * dayShortNames="dom, seg, ter, ..."></ion-datetime>
  235. * </ion-item>
  236. * ```
  237. *
  238. *
  239. * ### Advanced Datetime Validation and Manipulation
  240. *
  241. * The datetime picker provides the simplicity of selecting an exact format, and persists
  242. * the datetime values as a string using the standardized
  243. * [ISO 8601 datetime format](https://www.w3.org/TR/NOTE-datetime).
  244. * However, it's important to note that `ion-datetime` does not attempt to solve all
  245. * situtations when validating and manipulating datetime values. If datetime values need
  246. * to be parsed from a certain format, or manipulated (such as adding 5 days to a date,
  247. * subtracting 30 minutes, etc.), or even formatting data to a specific locale, then we highly
  248. * recommend using [moment.js](http://momentjs.com/) to "Parse, validate, manipulate, and
  249. * display dates in JavaScript". [Moment.js](http://momentjs.com/) has quickly become
  250. * our goto standard when dealing with datetimes within JavaScript, but Ionic does not
  251. * prepackage this dependency since most apps will not require it, and its locale
  252. * configuration should be decided by the end-developer.
  253. *
  254. *
  255. * @usage
  256. * ```html
  257. * <ion-item>
  258. * <ion-label>Date</ion-label>
  259. * <ion-datetime displayFormat="MM/DD/YYYY" [(ngModel)]="myDate">
  260. * </ion-datetime>
  261. * </ion-item>
  262. * ```
  263. *
  264. *
  265. * @demo /docs/demos/src/datetime/
  266. */
  267. var DateTime = (function (_super) {
  268. __extends(DateTime, _super);
  269. function DateTime(form, config, elementRef, renderer, item, _pickerCtrl) {
  270. var _this = _super.call(this, config, elementRef, renderer, 'datetime', {}, form, item, null) || this;
  271. _this._pickerCtrl = _pickerCtrl;
  272. _this._text = '';
  273. _this._locale = {};
  274. /**
  275. * @input {string} The text to display on the picker's cancel button. Default: `Cancel`.
  276. */
  277. _this.cancelText = 'Cancel';
  278. /**
  279. * @input {string} The text to display on the picker's "Done" button. Default: `Done`.
  280. */
  281. _this.doneText = 'Done';
  282. /**
  283. * @input {any} Any additional options that the picker interface can accept.
  284. * See the [Picker API docs](../../picker/Picker) for the picker options.
  285. */
  286. _this.pickerOptions = {};
  287. /**
  288. * @input {string} The text to display when there's no date selected yet.
  289. * Using lowercase to match the input attribute
  290. */
  291. _this.placeholder = '';
  292. /**
  293. * @output {any} Emitted when the datetime selection was cancelled.
  294. */
  295. _this.ionCancel = new EventEmitter();
  296. return _this;
  297. }
  298. /**
  299. * @hidden
  300. */
  301. DateTime.prototype.ngAfterContentInit = function () {
  302. var _this = this;
  303. // first see if locale names were provided in the inputs
  304. // then check to see if they're in the config
  305. // if neither were provided then it will use default English names
  306. ['monthNames', 'monthShortNames', 'dayNames', 'dayShortNames'].forEach(function (type) {
  307. _this._locale[type] = convertToArrayOfStrings(isPresent(_this[type]) ? _this[type] : _this._config.get(type), type);
  308. });
  309. this._initialize();
  310. };
  311. /**
  312. * @hidden
  313. */
  314. DateTime.prototype._inputNormalize = function (val) {
  315. updateDate(this._value, val);
  316. return this._value;
  317. };
  318. /**
  319. * @hidden
  320. */
  321. DateTime.prototype._inputUpdated = function () {
  322. _super.prototype._inputUpdated.call(this);
  323. this.updateText();
  324. };
  325. /**
  326. * @hidden
  327. */
  328. DateTime.prototype._inputShouldChange = function () {
  329. return true;
  330. };
  331. /**
  332. * TODO: REMOVE THIS
  333. * @hidden
  334. */
  335. DateTime.prototype._inputChangeEvent = function () {
  336. return this.value;
  337. };
  338. /**
  339. * @hidden
  340. */
  341. DateTime.prototype._inputNgModelEvent = function () {
  342. return convertDataToISO(this.value);
  343. };
  344. DateTime.prototype._click = function (ev) {
  345. ev.preventDefault();
  346. ev.stopPropagation();
  347. this.open();
  348. };
  349. DateTime.prototype._keyup = function () {
  350. this.open();
  351. };
  352. /**
  353. * @hidden
  354. */
  355. DateTime.prototype.open = function () {
  356. var _this = this;
  357. if (this.isFocus() || this._disabled) {
  358. return;
  359. }
  360. (void 0) /* console.debug */;
  361. // the user may have assigned some options specifically for the picker
  362. var pickerOptions = __assign({}, this.pickerOptions);
  363. // Add a cancel and done button by default to the picker
  364. var defaultButtons = [{
  365. text: this.cancelText,
  366. role: 'cancel',
  367. handler: function () { return _this.ionCancel.emit(_this); }
  368. }, {
  369. text: this.doneText,
  370. handler: function (data) { return _this.value = data; },
  371. }];
  372. pickerOptions.buttons = (pickerOptions.buttons || []).concat(defaultButtons);
  373. // Configure picker under the hood
  374. var picker = this._picker = this._pickerCtrl.create(pickerOptions);
  375. picker.ionChange.subscribe(function () {
  376. _this.validate();
  377. picker.refresh();
  378. });
  379. // Update picker status before presenting
  380. this.generate();
  381. this.validate();
  382. // Present picker
  383. this._fireFocus();
  384. picker.present(pickerOptions);
  385. picker.onDidDismiss(function () {
  386. _this._fireBlur();
  387. });
  388. };
  389. /**
  390. * @hidden
  391. */
  392. DateTime.prototype.generate = function () {
  393. var _this = this;
  394. var picker = this._picker;
  395. // if a picker format wasn't provided, then fallback
  396. // to use the display format
  397. var template = this.pickerFormat || this.displayFormat || DEFAULT_FORMAT;
  398. if (isPresent(template)) {
  399. // make sure we've got up to date sizing information
  400. this.calcMinMax();
  401. // does not support selecting by day name
  402. // automaticallly remove any day name formats
  403. template = template.replace('DDDD', '{~}').replace('DDD', '{~}');
  404. if (template.indexOf('D') === -1) {
  405. // there is not a day in the template
  406. // replace the day name with a numeric one if it exists
  407. template = template.replace('{~}', 'D');
  408. }
  409. // make sure no day name replacer is left in the string
  410. template = template.replace(/{~}/g, '');
  411. // parse apart the given template into an array of "formats"
  412. parseTemplate(template).forEach(function (format) {
  413. // loop through each format in the template
  414. // create a new picker column to build up with data
  415. var key = convertFormatToKey(format);
  416. var values;
  417. // first see if they have exact values to use for this input
  418. if (isPresent(_this[key + 'Values'])) {
  419. // user provide exact values for this date part
  420. values = convertToArrayOfNumbers(_this[key + 'Values'], key);
  421. }
  422. else {
  423. // use the default date part values
  424. values = dateValueRange(format, _this._min, _this._max);
  425. }
  426. var column = {
  427. name: key,
  428. selectedIndex: 0,
  429. options: values.map(function (val) {
  430. return {
  431. value: val,
  432. text: renderTextFormat(format, val, null, _this._locale),
  433. };
  434. })
  435. };
  436. // cool, we've loaded up the columns with options
  437. // preselect the option for this column
  438. var optValue = getValueFromFormat(_this.getValueOrDefault(), format);
  439. var selectedIndex = column.options.findIndex(function (opt) { return opt.value === optValue; });
  440. if (selectedIndex >= 0) {
  441. // set the select index for this column's options
  442. column.selectedIndex = selectedIndex;
  443. }
  444. // add our newly created column to the picker
  445. picker.addColumn(column);
  446. });
  447. // Normalize min/max
  448. var min_1 = this._min;
  449. var max_1 = this._max;
  450. var columns_1 = this._picker.getColumns();
  451. ['month', 'day', 'hour', 'minute']
  452. .filter(function (name) { return !columns_1.find(function (column) { return column.name === name; }); })
  453. .forEach(function (name) {
  454. min_1[name] = 0;
  455. max_1[name] = 0;
  456. });
  457. this.divyColumns();
  458. }
  459. };
  460. /**
  461. * @hidden
  462. */
  463. DateTime.prototype.validateColumn = function (name, index, min, max, lowerBounds, upperBounds) {
  464. (void 0) /* assert */;
  465. (void 0) /* assert */;
  466. var column = this._picker.getColumn(name);
  467. if (!column) {
  468. return 0;
  469. }
  470. var lb = lowerBounds.slice();
  471. var ub = upperBounds.slice();
  472. var options = column.options;
  473. var indexMin = options.length - 1;
  474. var indexMax = 0;
  475. for (var i = 0; i < options.length; i++) {
  476. var opt = options[i];
  477. var value = opt.value;
  478. lb[index] = opt.value;
  479. ub[index] = opt.value;
  480. var disabled = opt.disabled = (value < lowerBounds[index] ||
  481. value > upperBounds[index] ||
  482. dateSortValue(ub[0], ub[1], ub[2], ub[3], ub[4]) < min ||
  483. dateSortValue(lb[0], lb[1], lb[2], lb[3], lb[4]) > max);
  484. if (!disabled) {
  485. indexMin = Math.min(indexMin, i);
  486. indexMax = Math.max(indexMax, i);
  487. }
  488. }
  489. var selectedIndex = column.selectedIndex = clamp(indexMin, column.selectedIndex, indexMax);
  490. opt = column.options[selectedIndex];
  491. if (opt) {
  492. return opt.value;
  493. }
  494. return 0;
  495. };
  496. /**
  497. * @private
  498. */
  499. DateTime.prototype.validate = function () {
  500. var today = new Date();
  501. var minCompareVal = dateDataSortValue(this._min);
  502. var maxCompareVal = dateDataSortValue(this._max);
  503. var yearCol = this._picker.getColumn('year');
  504. (void 0) /* assert */;
  505. var selectedYear = today.getFullYear();
  506. if (yearCol) {
  507. // default to the first value if the current year doesn't exist in the options
  508. if (!yearCol.options.find(function (col) { return col.value === today.getFullYear(); })) {
  509. selectedYear = yearCol.options[0].value;
  510. }
  511. var yearOpt = yearCol.options[yearCol.selectedIndex];
  512. if (yearOpt) {
  513. // they have a selected year value
  514. selectedYear = yearOpt.value;
  515. }
  516. }
  517. var selectedMonth = this.validateColumn('month', 1, minCompareVal, maxCompareVal, [selectedYear, 0, 0, 0, 0], [selectedYear, 12, 31, 23, 59]);
  518. var numDaysInMonth = daysInMonth(selectedMonth, selectedYear);
  519. var selectedDay = this.validateColumn('day', 2, minCompareVal, maxCompareVal, [selectedYear, selectedMonth, 0, 0, 0], [selectedYear, selectedMonth, numDaysInMonth, 23, 59]);
  520. var selectedHour = this.validateColumn('hour', 3, minCompareVal, maxCompareVal, [selectedYear, selectedMonth, selectedDay, 0, 0], [selectedYear, selectedMonth, selectedDay, 23, 59]);
  521. this.validateColumn('minute', 4, minCompareVal, maxCompareVal, [selectedYear, selectedMonth, selectedDay, selectedHour, 0], [selectedYear, selectedMonth, selectedDay, selectedHour, 59]);
  522. };
  523. /**
  524. * @hidden
  525. */
  526. DateTime.prototype.divyColumns = function () {
  527. var pickerColumns = this._picker.getColumns();
  528. var columnsWidth = [];
  529. var col;
  530. var width;
  531. for (var i = 0; i < pickerColumns.length; i++) {
  532. col = pickerColumns[i];
  533. columnsWidth.push(0);
  534. for (var j = 0; j < col.options.length; j++) {
  535. width = col.options[j].text.length;
  536. if (width > columnsWidth[i]) {
  537. columnsWidth[i] = width;
  538. }
  539. }
  540. }
  541. if (columnsWidth.length === 2) {
  542. width = Math.max(columnsWidth[0], columnsWidth[1]);
  543. pickerColumns[0].align = 'right';
  544. pickerColumns[1].align = 'left';
  545. pickerColumns[0].optionsWidth = pickerColumns[1].optionsWidth = width * 17 + "px";
  546. }
  547. else if (columnsWidth.length === 3) {
  548. width = Math.max(columnsWidth[0], columnsWidth[2]);
  549. pickerColumns[0].align = 'right';
  550. pickerColumns[1].columnWidth = columnsWidth[1] * 17 + "px";
  551. pickerColumns[0].optionsWidth = pickerColumns[2].optionsWidth = width * 17 + "px";
  552. pickerColumns[2].align = 'left';
  553. }
  554. };
  555. /**
  556. * @hidden
  557. */
  558. DateTime.prototype.updateText = function () {
  559. // create the text of the formatted data
  560. var template = this.displayFormat || this.pickerFormat || DEFAULT_FORMAT;
  561. this._text = renderDateTime(template, this.getValue(), this._locale);
  562. };
  563. /**
  564. * @hidden
  565. */
  566. DateTime.prototype.getValue = function () {
  567. return this._value;
  568. };
  569. /**
  570. * @hidden
  571. */
  572. DateTime.prototype.getValueOrDefault = function () {
  573. if (this.hasValue()) {
  574. return this._value;
  575. }
  576. var initialDateString = this.getDefaultValueDateString();
  577. var _default = {};
  578. updateDate(_default, initialDateString);
  579. return _default;
  580. };
  581. /**
  582. * Get the default value as a date string
  583. * @hidden
  584. */
  585. DateTime.prototype.getDefaultValueDateString = function () {
  586. if (this.initialValue) {
  587. return this.initialValue;
  588. }
  589. var nowString = (new Date).toISOString();
  590. if (this.max) {
  591. var now = parseDate(nowString);
  592. var max = parseDate(this.max);
  593. var v = void 0;
  594. for (var i in max) {
  595. v = max[i];
  596. if (v === null) {
  597. max[i] = now[i];
  598. }
  599. }
  600. var diff = compareDates(now, max);
  601. // If max is before current time, return max
  602. if (diff > 0) {
  603. return this.max;
  604. }
  605. }
  606. return nowString;
  607. };
  608. /**
  609. * @hidden
  610. */
  611. DateTime.prototype.hasValue = function () {
  612. var val = this._value;
  613. return isPresent(val)
  614. && isObject(val)
  615. && Object.keys(val).length > 0;
  616. };
  617. /**
  618. * @hidden
  619. */
  620. DateTime.prototype.calcMinMax = function (now) {
  621. var todaysYear = (now || new Date()).getFullYear();
  622. if (isPresent(this.yearValues)) {
  623. var years = convertToArrayOfNumbers(this.yearValues, 'year');
  624. if (isBlank(this.min)) {
  625. this.min = Math.min.apply(Math, years);
  626. }
  627. if (isBlank(this.max)) {
  628. this.max = Math.max.apply(Math, years);
  629. }
  630. }
  631. else {
  632. if (isBlank(this.min)) {
  633. this.min = (todaysYear - 100).toString();
  634. }
  635. if (isBlank(this.max)) {
  636. this.max = todaysYear.toString();
  637. }
  638. }
  639. var min = this._min = parseDate(this.min);
  640. var max = this._max = parseDate(this.max);
  641. min.year = min.year || todaysYear;
  642. max.year = max.year || todaysYear;
  643. min.month = min.month || 1;
  644. max.month = max.month || 12;
  645. min.day = min.day || 1;
  646. max.day = max.day || 31;
  647. min.hour = min.hour || 0;
  648. max.hour = max.hour || 23;
  649. min.minute = min.minute || 0;
  650. max.minute = max.minute || 59;
  651. min.second = min.second || 0;
  652. max.second = max.second || 59;
  653. // Ensure min/max constraits
  654. if (min.year > max.year) {
  655. console.error('min.year > max.year');
  656. min.year = max.year - 100;
  657. }
  658. if (min.year === max.year) {
  659. if (min.month > max.month) {
  660. console.error('min.month > max.month');
  661. min.month = 1;
  662. }
  663. else if (min.month === max.month && min.day > max.day) {
  664. console.error('min.day > max.day');
  665. min.day = 1;
  666. }
  667. }
  668. };
  669. DateTime.decorators = [
  670. { type: Component, args: [{
  671. selector: 'ion-datetime',
  672. template: '<div *ngIf="!_text" class="datetime-text datetime-placeholder">{{placeholder}}</div>' +
  673. '<div *ngIf="_text" class="datetime-text">{{_text}}</div>' +
  674. '<button aria-haspopup="true" ' +
  675. 'type="button" ' +
  676. '[id]="id" ' +
  677. 'ion-button="item-cover" ' +
  678. '[attr.aria-labelledby]="_labelId" ' +
  679. '[attr.aria-disabled]="_disabled" ' +
  680. 'class="item-cover">' +
  681. '</button>',
  682. host: {
  683. '[class.datetime-disabled]': '_disabled'
  684. },
  685. providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: DateTime, multi: true }],
  686. encapsulation: ViewEncapsulation.None,
  687. },] },
  688. ];
  689. /** @nocollapse */
  690. DateTime.ctorParameters = function () { return [
  691. { type: Form, },
  692. { type: Config, },
  693. { type: ElementRef, },
  694. { type: Renderer, },
  695. { type: Item, decorators: [{ type: Optional },] },
  696. { type: PickerController, decorators: [{ type: Optional },] },
  697. ]; };
  698. DateTime.propDecorators = {
  699. 'min': [{ type: Input },],
  700. 'max': [{ type: Input },],
  701. 'displayFormat': [{ type: Input },],
  702. 'initialValue': [{ type: Input },],
  703. 'pickerFormat': [{ type: Input },],
  704. 'cancelText': [{ type: Input },],
  705. 'doneText': [{ type: Input },],
  706. 'yearValues': [{ type: Input },],
  707. 'monthValues': [{ type: Input },],
  708. 'dayValues': [{ type: Input },],
  709. 'hourValues': [{ type: Input },],
  710. 'minuteValues': [{ type: Input },],
  711. 'monthNames': [{ type: Input },],
  712. 'monthShortNames': [{ type: Input },],
  713. 'dayNames': [{ type: Input },],
  714. 'dayShortNames': [{ type: Input },],
  715. 'pickerOptions': [{ type: Input },],
  716. 'placeholder': [{ type: Input },],
  717. 'ionCancel': [{ type: Output },],
  718. '_click': [{ type: HostListener, args: ['click', ['$event'],] },],
  719. '_keyup': [{ type: HostListener, args: ['keyup.space',] },],
  720. };
  721. return DateTime;
  722. }(BaseInput));
  723. export { DateTime };
  724. /**
  725. * @hidden
  726. * Use to convert a string of comma separated numbers or
  727. * an array of numbers, and clean up any user input
  728. */
  729. function convertToArrayOfNumbers(input, type) {
  730. if (isString(input)) {
  731. // convert the string to an array of strings
  732. // auto remove any whitespace and [] characters
  733. input = input.replace(/\[|\]|\s/g, '').split(',');
  734. }
  735. var values;
  736. if (isArray(input)) {
  737. // ensure each value is an actual number in the returned array
  738. values = input
  739. .map(function (num) { return parseInt(num, 10); })
  740. .filter(isFinite);
  741. }
  742. if (!values || !values.length) {
  743. console.warn("Invalid \"" + type + "Values\". Must be an array of numbers, or a comma separated string of numbers.");
  744. }
  745. return values;
  746. }
  747. /**
  748. * @hidden
  749. * Use to convert a string of comma separated strings or
  750. * an array of strings, and clean up any user input
  751. */
  752. function convertToArrayOfStrings(input, type) {
  753. if (isPresent(input)) {
  754. if (isString(input)) {
  755. // convert the string to an array of strings
  756. // auto remove any [] characters
  757. input = input.replace(/\[|\]/g, '').split(',');
  758. }
  759. var values;
  760. if (isArray(input)) {
  761. // trim up each string value
  762. values = input.map(function (val) { return val.trim(); });
  763. }
  764. if (!values || !values.length) {
  765. console.warn("Invalid \"" + type + "Names\". Must be an array of strings, or a comma separated string.");
  766. }
  767. return values;
  768. }
  769. }
  770. var DEFAULT_FORMAT = 'MMM D, YYYY';
  771. //# sourceMappingURL=datetime.js.map