@catull/igniteui-angular
Version:
Ignite UI for Angular is a dependency-free Angular toolkit for building modern web apps
1,400 lines • 226 kB
JavaScript
var IgxTimePickerComponent_1;
import { __decorate, __metadata } from "tslib";
import { CommonModule } from '@angular/common';
import { Component, ElementRef, EventEmitter, HostBinding, HostListener, Input, NgModule, Output, TemplateRef, ViewChild, ContentChild, Injectable } from '@angular/core';
import { NG_VALUE_ACCESSOR } from '@angular/forms';
import { HAMMER_GESTURE_CONFIG, HammerGestureConfig } from '@angular/platform-browser';
import { IgxIconModule } from '../icon/index';
import { IgxInputGroupModule, IgxInputGroupComponent } from '../input-group/input-group.component';
import { IgxInputDirective } from '../directives/input/input.directive';
import { IgxAmPmItemDirective, IgxHourItemDirective, IgxMinuteItemDirective, IgxSecondsItemDirective, IgxItemListDirective, IgxTimePickerTemplateDirective, IgxTimePickerActionsDirective } from './time-picker.directives';
import { Subject, fromEvent, interval, animationFrameScheduler } from 'rxjs';
import { IGX_TIME_PICKER_COMPONENT } from './time-picker.common';
import { AbsoluteScrollStrategy } from '../services/overlay/scroll';
import { AutoPositionStrategy } from '../services/overlay/position';
import { takeUntil, throttle } from 'rxjs/operators';
import { IgxButtonModule } from '../directives/button/button.directive';
import { IgxMaskModule } from '../directives/mask/mask.directive';
import { IgxToggleModule, IgxToggleDirective } from '../directives/toggle/toggle.directive';
import { TimeDisplayFormatPipe, TimeInputFormatPipe } from './time-picker.pipes';
import { CurrentResourceStrings } from '../core/i18n/resources';
import { InteractionMode } from '../core/enums';
import { DeprecateProperty } from '../core/deprecateDecorators';
let NEXT_ID = 0;
const ITEMS_COUNT = 7;
let TimePickerHammerConfig = class TimePickerHammerConfig extends HammerGestureConfig {
constructor() {
super(...arguments);
this.overrides = {
pan: { direction: Hammer.DIRECTION_VERTICAL, threshold: 1 }
};
}
};
TimePickerHammerConfig = __decorate([
Injectable()
], TimePickerHammerConfig);
export { TimePickerHammerConfig };
let IgxTimePickerComponent = IgxTimePickerComponent_1 = class IgxTimePickerComponent {
constructor() {
/**
* An @Input property that sets the value of the `id` attribute.
* ```html
* <igx-time-picker [id]="'igx-time-picker-5'" format="h:mm tt" ></igx-time-picker>
* ```
*/
this.id = `igx-time-picker-${NEXT_ID++}`;
/**
* An @Input property that allows you to disable the `igx-time-picker` component. By default `disabled` is set to false.
* ```html
* <igx-time-picker [disabled]="'true'" [vertical]="true" format="h:mm tt" ></igx-time-picker>
* ```
*/
this.disabled = false;
/**
* An @Input property that determines the spin behavior. By default `isSpinLoop` is set to true.
* The seconds, minutes and hour spinning will wrap around by default.
*```html
*<igx-time-picker [isSpinLoop]="false" id="time-picker"></igx-time-picker>
*```
*/
this.isSpinLoop = true;
/**
* An @Input property that Gets/Sets the orientation of the `igxTimePicker`. By default `vertical` is set to false.
* ```html
*<igx-time-picker [vertical]="true" id="time-picker"></igx-time-picker>
* ```
*/
this.vertical = false;
/**
* Sets the character used to prompt the user for input.
* Default value is "'-'".
* ```html
* <igx-time-picker [promptChar] = "'_'">
* ```
* @memberof IgxTimePickerComponent
*/
this.promptChar = '-';
/**
* An @Input property that allows you to switch the interaction mode between
* a dialog picker or dropdown with editable masked input.
* Deafult is dialog picker.
*```html
*public mode = InteractionMode.DROPDOWN;
* //..
*<igx-time-picker [mode]="mode"></igx-time-picker>
*```
* @memberof IgxTimePickerComponent
*/
this.mode = InteractionMode.Dialog;
/**
* Emitted when selection is made. The event contains the selected value. Returns {`oldValue`: `Date`, `newValue`: `Date`}.
*```typescript
* @ViewChild("toast")
*private toast: IgxToastComponent;
*public onValueChanged(timepicker){
* this.toast.show()
*}
* //...
* ```
* ```html
*<igx-time-picker (onValueChanged)="onValueChanged($event)"></igx-time-picker>
*<igx-toast #toast message="The value has been changed!"></igx-toast>
*```
*/
this.onValueChanged = new EventEmitter();
/**
* Emitted when an invalid value is being set. Returns {`timePicker`: `any`, `currentValue`: `Date`, `setThroughUI`: `boolean`}
* ```typescript
*public min: string = "09:00";
*public max: string = "18:00";
*@ViewChild("toast")
*private toast: IgxToastComponent;
*public onValidationFailed(timepicker){
* this.toast.show();
*}
* //...
* ```
* ```html
*<igx-time-picker [minValue]="min" [maxValue]="max" (onValidationFailed)="onValidationFailed($event)"></igx-time-picker>
*<igx-toast #toast message="Value must be between 09:00 and 18:00!"></igx-toast>
* ```
*/
this.onValidationFailed = new EventEmitter();
/**
* Emitted when a timePicker is opened.
*/
this.onOpened = new EventEmitter();
/**
* Emitted when a timePicker is closed.
*/
this.onClosed = new EventEmitter();
/**
* Emitted when a timePicker is being closed.
*/
this.onClosing = new EventEmitter();
/**
* @hidden
*/
this._hourItems = [];
/**
* @hidden
*/
this._minuteItems = [];
/**
* @hidden
*/
this._secondsItems = [];
/**
* @hidden
*/
this._ampmItems = [];
/**
* @hidden
*/
this.cleared = false;
/**
* @hidden
*/
this.isNotEmpty = false;
/**
* @hidden
*/
this.displayFormat = new TimeDisplayFormatPipe(this);
/**
* @hidden
*/
this.inputFormat = new TimeInputFormatPipe(this);
this._resourceStrings = CurrentResourceStrings.TimePickerResStrings;
this._okButtonLabel = null;
this._cancelButtonLabel = null;
this._itemsDelta = { hours: 1, minutes: 1, seconds: 1 };
this._isHourListLoop = this.isSpinLoop;
this._isMinuteListLoop = this.isSpinLoop;
this._isSecondsListLoop = this.isSpinLoop;
this._hourView = [];
this._minuteView = [];
this._secondsView = [];
this._ampmView = [];
this._destroy$ = new Subject();
this._onOpen = new EventEmitter();
this._onClose = new EventEmitter();
this._hoursPos = new Set();
this._minutesPos = new Set();
this._secondsPos = new Set();
this._amPmPos = new Set();
this._onTouchedCallback = () => { };
this._onChangeCallback = () => { };
}
/**
* An accessor that allows you to set a time using the `value` input.
* ```html
*public date: Date = new Date(Date.now());
* //...
*<igx-time-picker [value]="date" format="h:mm tt"></igx-time-picker>
* ```
*/
set value(value) {
if (this._isValueValid(value)) {
const oldVal = this._value;
this._value = value;
this._onChangeCallback(value);
const dispVal = this._formatTime(this.value, this.format);
if (this.mode === InteractionMode.DropDown && this._displayValue !== dispVal) {
this.displayValue = dispVal;
}
const args = {
oldValue: oldVal,
newValue: value
};
this.onValueChanged.emit(args);
}
else {
const args = {
timePicker: this,
currentValue: value,
setThroughUI: false
};
this.onValidationFailed.emit(args);
}
}
/**
* An accessor that returns the value of `igx-time-picker` component.
* ```html
*@ViewChild("MyPick")
*public pick: IgxTimePickerComponent;
*ngAfterViewInit(){
* let pickSelect = this.pick.value;
* }
* ```
*/
get value() {
return this._value;
}
/**
* An accessor that sets the resource strings.
* By default it uses EN resources.
*/
set resourceStrings(value) {
this._resourceStrings = Object.assign({}, this._resourceStrings, value);
}
/**
* An accessor that returns the resource strings.
*/
get resourceStrings() {
return this._resourceStrings;
}
/**
* An @Input property that renders OK button with custom text. By default `okButtonLabel` is set to OK.
* ```html
* <igx-time-picker okButtonLabel='SET' [value]="date" format="h:mm tt"></igx-time-picker>
* ```
*/
set okButtonLabel(value) {
this._okButtonLabel = value;
}
/**
* An accessor that returns the label of ok button.
*/
get okButtonLabel() {
if (this._okButtonLabel === null) {
return this.resourceStrings.igx_time_picker_ok;
}
return this._okButtonLabel;
}
/**
* An @Input property that renders cancel button with custom text.
* By default `cancelButtonLabel` is set to Cancel.
* ```html
* <igx-time-picker cancelButtonLabel='Exit' [value]="date" format="h:mm tt"></igx-time-picker>
* ```
*/
set cancelButtonLabel(value) {
this._cancelButtonLabel = value;
}
/**
* An accessor that returns the label of cancel button.
*/
get cancelButtonLabel() {
if (this._cancelButtonLabel === null) {
return this.resourceStrings.igx_time_picker_cancel;
}
return this._cancelButtonLabel;
}
/**
* An @Input property that gets/sets the delta by which hour and minute items would be changed <br>
* when the user presses the Up/Down keys.
* By default `itemsDelta` is set to `{hours: 1, minutes: 1, seconds: 1}`
* ```html
*<igx-time-picker [itemsDelta]="{hours:3, minutes:5, seconds:10}" id="time-picker"></igx-time-picker>
*```
*/
set itemsDelta(value) {
this._itemsDelta = Object.assign({ hours: 1, minutes: 1, seconds: 1 }, value);
}
get itemsDelta() {
return this._itemsDelta;
}
/**
* An @Input property that Gets/Sets format of time while `igxTimePicker` does not have focus. <br>
* By default `format` is set to hh:mm tt. <br>
* List of time-flags: <br>
* `h` : hours field in 12-hours format without leading zero <br>
* `hh` : hours field in 12-hours format with leading zero <br>
* `H` : hours field in 24-hours format without leading zero <br>
* `HH` : hours field in 24-hours format with leading zero <br>
* `m` : minutes field without leading zero <br>
* `mm` : minutes field with leading zero <br>
* `s` : seconds field without leading zero <br>
* `ss` : seconds field with leading zero <br>
* `tt` : 2 character string which represents AM/PM field <br>
* ```html
*<igx-time-picker format="HH:m" id="time-picker"></igx-time-picker>
* ```
*/
get format() {
return this._format || 'hh:mm tt';
}
set format(formatValue) {
this._format = formatValue;
this.mask = this._format.indexOf('tt') !== -1 ? '00:00:00 LL' : '00:00:00';
if (!this.showHoursList || !this.showMinutesList) {
this.trimMask();
}
if (!this.showSecondsList) {
this.trimMask();
}
if (this.displayValue) {
this.displayValue = this._formatTime(this.value, this._format);
}
this.determineCursorPos();
}
/**
* An @Input property that allows you to modify overlay positioning, interaction and scroll behavior.
* ```typescript
* const settings: OverlaySettings = {
* closeOnOutsideClick: true,
* modal: false
* }
* ```
* ---
* ```html
* <igx-time-picker [overlaySettings]="settings"></igx-time-picker>
* ```
* @memberof IgxTimePickerComponent
*/
set overlaySettings(value) {
this._overlaySettings = value;
}
get overlaySettings() {
return this._overlaySettings ? this._overlaySettings :
(this.mode === InteractionMode.Dialog ? this._dialogOverlaySettings : this._dropDownOverlaySettings);
}
/**
* @deprecated Use 'onOpened' instead.
* Emitted when a timePicker is being opened.
* ```html
*@ViewChild("toast")
*private toast: IgxToastComponent;
*public onOpen(timepicker){
* this.toast.show();
*}
* //...
* ```
* ```html
*<igx-time-picker [minValue]="min" [maxValue]="max" (onOpen)="onOpen($event)"></igx-time-picker>
*<igx-toast #toast message="The time picker has been opened!"></igx-toast>
* ```
*/
get onOpen() {
return this._onOpen;
}
set onOpen(val) {
this._onOpen = val;
}
/**
* @deprecated Use 'onClosed' instead.
* Emitted when a timePicker is being closed.
*/
get onClose() {
return this._onClose;
}
set onClose(val) {
this._onClose = val;
}
trimMask() {
this.mask = this.mask.slice(this.mask.indexOf(':') + 1, this.mask.length);
}
/**
* @hidden
*/
get mask() {
return this._mask || '00:00 LL';
}
set mask(val) {
this._mask = val;
}
/**
* @hidden
*/
get displayValue() {
if (this._displayValue === undefined) {
return this._formatTime(this.value, this.format);
}
return this._displayValue;
}
set displayValue(value) {
this._displayValue = value;
}
/**
* Returns the current time formatted as string using the `format` option.
* If there is no set time the return is an empty string.
*```typescript
*@ViewChild("MyChild")
*private picker: IgxTimePickerComponent;
*ngAfterViewInit(){
* let time = this.picker.displayTime;
*}
*```
*/
get displayTime() {
if (this.value) {
return this._formatTime(this.value, this.format);
}
return '';
}
/**
* @hidden
*/
get hourView() {
return this._hourView;
}
/**
* @hidden
*/
get minuteView() {
return this._minuteView;
}
/**
* @hidden
*/
get secondsView() {
return this._secondsView;
}
/**
* @hidden
*/
get ampmView() {
return this._ampmView;
}
/**
* @hidden
*/
get showClearButton() {
return (this.displayValue && this.displayValue !== this.parseMask(false)) || this.isNotEmpty;
}
/**
* @hidden
*/
get showHoursList() {
return this.format.indexOf('h') !== -1 || this.format.indexOf('H') !== -1;
}
/**
* @hidden
*/
get showMinutesList() {
return this.format.indexOf('m') !== -1;
}
/**
* @hidden
*/
get showSecondsList() {
return this.format.indexOf('s') !== -1;
}
/**
* @hidden
*/
get showAmPmList() {
return this.format.indexOf('t') !== -1;
}
/**
* @hidden
*/
get validSecondsEntries() {
const secondsEntries = [];
for (let i = 0; i < 60; i++) {
secondsEntries.push(i);
}
return secondsEntries;
}
/**
* @hidden
*/
get validMinuteEntries() {
const minuteEntries = [];
for (let i = 0; i < 60; i++) {
minuteEntries.push(i);
}
return minuteEntries;
}
/**
* @hidden
*/
get validHourEntries() {
const hourEntries = [];
const index = this.format.indexOf('h') !== -1 ? 13 : 24;
for (let i = 0; i < index; i++) {
hourEntries.push(i);
}
return hourEntries;
}
/**
* Gets the input group template.
* ```typescript
* let template = this.template();
* ```
* @memberof IgxTimePickerComponent
*/
get template() {
if (this.timePickerTemplateDirective) {
return this.timePickerTemplateDirective.template;
}
return this.mode === InteractionMode.Dialog ? this.defaultTimePickerTemplate : this.dropdownInputTemplate;
}
/**
* Gets the context passed to the input group template.
* @memberof IgxTimePickerComponent
*/
get context() {
return {
value: this.value,
displayTime: this.displayTime,
displayValue: this.displayValue,
openDialog: (target) => this.openDialog(target)
};
}
/**
* @hidden
*/
ngOnInit() {
this._generateHours();
this._generateMinutes();
this._generateSeconds();
if (this.format.indexOf('tt') !== -1) {
this._generateAmPm();
}
this._dropDownOverlaySettings = {
modal: false,
closeOnOutsideClick: true,
scrollStrategy: new AbsoluteScrollStrategy(),
positionStrategy: new AutoPositionStrategy()
};
this._dialogOverlaySettings = {};
}
/**
* @hidden
*/
ngAfterViewInit() {
if (this.mode === InteractionMode.DropDown && this.input) {
fromEvent(this.input.nativeElement, 'keydown').pipe(throttle(() => interval(0, animationFrameScheduler)), takeUntil(this._destroy$)).subscribe((event) => {
if (event.key === "ArrowUp" /* UP_ARROW */ || event.key === "Up" /* UP_ARROW_IE */ ||
event.key === "ArrowDown" /* DOWN_ARROW */ || event.key === "Down" /* DOWN_ARROW_IE */) {
this.spinOnEdit(event);
}
});
}
if (this.toggleRef && this.group) {
this.toggleRef.element.style.width = this.group.element.nativeElement.getBoundingClientRect().width + 'px';
}
if (this.toggleRef) {
this.toggleRef.onClosed.pipe(takeUntil(this._destroy$)).subscribe(() => {
if (this.mode === InteractionMode.DropDown) {
this._onDropDownClosed();
}
this.onClosed.emit(this);
// TODO: remove this line after deprecating 'onClose'
this._onClose.emit(this);
});
this.toggleRef.onOpened.pipe(takeUntil(this._destroy$)).subscribe(() => {
this.onOpened.emit(this);
// TODO: remove this line after deprecating 'onOpen'
this._onOpen.emit(this);
});
this.toggleRef.onClosing.pipe(takeUntil(this._destroy$)).subscribe((event) => {
this.onClosing.emit(event);
// If canceled in a user onClosing handler
if (event.cancel) {
return;
}
// Do not focus the input if clicking outside in dropdown mode
const input = this.getEditElement();
if (input && !(event.event && this.mode === InteractionMode.DropDown)) {
input.focus();
}
});
this.determineCursorPos();
}
}
/**
* @hidden
*/
ngOnDestroy() {
this._destroy$.next(true);
this._destroy$.complete();
}
/**
* @hidden
*/
onKeydownSpace(event) {
this.openDialog(this.getInputGroupElement());
event.preventDefault();
}
/**
* @hidden
*/
onAltArrowDown() {
this.openDialog(this.getInputGroupElement());
}
determineCursorPos() {
this.clearCursorPos();
for (const char of this.format) {
switch (char) {
case 'H':
case 'h':
this._hoursPos.size === 0 ? this._hoursPos.add(this.format.indexOf(char)) :
this._hoursPos.add(this.format.lastIndexOf(char));
this._hoursPos.add(this.format.lastIndexOf(char) + 1);
break;
case 'M':
case 'm':
this._minutesPos.size === 0 ? this._minutesPos.add(this.format.indexOf(char)) :
this._minutesPos.add(this.format.lastIndexOf(char));
this._minutesPos.add(this.format.lastIndexOf(char) + 1);
break;
case 'S':
case 's':
this._secondsPos.size === 0 ? this._secondsPos.add(this.format.indexOf(char)) :
this._secondsPos.add(this.format.lastIndexOf(char));
this._secondsPos.add(this.format.lastIndexOf(char) + 1);
break;
case 'T':
case 't':
this._amPmPos.size === 0 ? this._amPmPos.add(this.format.indexOf(char)) :
this._amPmPos.add(this.format.lastIndexOf(char));
this._amPmPos.add(this.format.lastIndexOf(char) + 1);
break;
}
}
}
clearCursorPos() {
this._hoursPos.forEach(v => this._hoursPos.delete(v));
this._minutesPos.forEach(v => this._minutesPos.delete(v));
this._secondsPos.forEach(v => this._secondsPos.delete(v));
this._amPmPos.forEach(v => this._amPmPos.delete(v));
}
_scrollItemIntoView(item, items, selectedItem, isListLoop, viewType) {
let itemIntoView;
if (items) {
const index = (item === 'AM' || item === 'PM') ? items.indexOf(item) : items.indexOf(parseInt(item, 10));
let view;
if (index !== -1) {
if (isListLoop) {
if (index > 0) {
selectedItem = this._itemToString(items[index - 1], viewType);
itemIntoView = this._nextItem(items, selectedItem, isListLoop, viewType);
}
else {
selectedItem = this._itemToString(items[1], viewType);
itemIntoView = this._prevItem(items, selectedItem, isListLoop, viewType);
}
}
else {
view = items.slice(index - 3, index + 4);
selectedItem = this._itemToString(items[index], viewType);
itemIntoView = { selectedItem, view };
}
itemIntoView.view = this._viewToString(itemIntoView.view, viewType);
}
}
return itemIntoView;
}
_viewToString(view, viewType) {
for (let i = 0; i < view.length; i++) {
if (typeof (view[i]) !== 'string') {
view[i] = this._itemToString(view[i], viewType);
}
}
return view;
}
_itemToString(item, viewType) {
if (item === null) {
item = '';
}
else if (viewType && typeof (item) !== 'string') {
const leadZeroHour = (item < 10 && (this.format.indexOf('hh') !== -1 || this.format.indexOf('HH') !== -1));
const leadZeroMinute = (item < 10 && this.format.indexOf('mm') !== -1);
const leadZeroSeconds = (item < 10 && this.format.indexOf('ss') !== -1);
const leadZero = {
hour: leadZeroHour,
minute: leadZeroMinute,
seconds: leadZeroSeconds
}[viewType];
item = (leadZero) ? '0' + item : `${item}`;
}
return item;
}
_prevItem(items, selectedItem, isListLoop, viewType) {
const selectedIndex = items.indexOf(parseInt(selectedItem, 10));
const itemsCount = items.length;
let view;
if (selectedIndex === -1) {
view = items.slice(0, 7);
selectedItem = items[3];
}
else if (isListLoop) {
if (selectedIndex - 4 < 0) {
view = items.slice(itemsCount - (4 - selectedIndex), itemsCount);
view = view.concat(items.slice(0, selectedIndex + 3));
}
else if (selectedIndex + 4 > itemsCount) {
view = items.slice(selectedIndex - 4, itemsCount);
view = view.concat(items.slice(0, selectedIndex + 3 - itemsCount));
}
else {
view = items.slice(selectedIndex - 4, selectedIndex + 3);
}
selectedItem = (selectedIndex === 0) ? items[itemsCount - 1] : items[selectedIndex - 1];
}
else if (selectedIndex > 3) {
view = items.slice(selectedIndex - 4, selectedIndex + 3);
selectedItem = items[selectedIndex - 1];
}
else if (selectedIndex === 3) {
view = items.slice(0, 7);
}
view = this._viewToString(view, viewType);
selectedItem = this._itemToString(selectedItem, viewType);
return {
selectedItem,
view
};
}
_nextItem(items, selectedItem, isListLoop, viewType) {
const selectedIndex = items.indexOf(parseInt(selectedItem, 10));
const itemsCount = items.length;
let view;
if (selectedIndex === -1) {
view = items.slice(0, 7);
selectedItem = items[3];
}
else if (isListLoop) {
if (selectedIndex < 2) {
view = items.slice(itemsCount - (2 - selectedIndex), itemsCount);
view = view.concat(items.slice(0, selectedIndex + 5));
}
else if (selectedIndex + 4 >= itemsCount) {
view = items.slice(selectedIndex - 2, itemsCount);
view = view.concat(items.slice(0, selectedIndex + 5 - itemsCount));
}
else {
view = items.slice(selectedIndex - 2, selectedIndex + 5);
}
selectedItem = (selectedIndex === itemsCount - 1) ? items[0] : items[selectedIndex + 1];
}
else if (selectedIndex + 1 < itemsCount - 3) {
view = items.slice(selectedIndex - 2, selectedIndex + 5);
selectedItem = items[selectedIndex + 1];
}
else if (selectedIndex === itemsCount - 4) {
view = items.slice(selectedIndex - 3, itemsCount);
}
view = this._viewToString(view, viewType);
selectedItem = this._itemToString(selectedItem, viewType);
return {
selectedItem,
view
};
}
_formatTime(value, format) {
if (!value) {
return '';
}
else {
let hour = value.getHours();
let formattedSeconds, formattedMinute, formattedHour;
const minute = value.getMinutes();
const seconds = value.getSeconds();
const amPM = (hour > 11) ? 'PM' : 'AM';
if (format.indexOf('h') !== -1) {
if (hour > 12) {
hour -= 12;
formattedHour = hour < 10 && format.indexOf('hh') !== -1 ? '0' + hour : `${hour}`;
}
else if (hour === 0) {
formattedHour = '12';
}
else if (hour < 10 && format.indexOf('hh') !== -1) {
formattedHour = '0' + hour;
}
else {
formattedHour = `${hour}`;
}
}
else {
if (hour < 10 && format.indexOf('HH') !== -1) {
formattedHour = '0' + hour;
}
else {
formattedHour = `${hour}`;
}
}
formattedMinute = minute < 10 && format.indexOf('mm') !== -1 ? '0' + minute : `${minute}`;
formattedSeconds = seconds < 10 && format.indexOf('ss') !== -1 ? '0' + seconds : `${seconds}`;
return format.replace('hh', formattedHour).replace('h', formattedHour)
.replace('HH', formattedHour).replace('H', formattedHour)
.replace('mm', formattedMinute).replace('m', formattedMinute)
.replace('ss', formattedSeconds).replace('s', formattedSeconds)
.replace('tt', amPM);
}
}
_updateHourView(start, end) {
this._hourView = this._viewToString(this._hourItems.slice(start, end), 'hour');
}
_updateMinuteView(start, end) {
this._minuteView = this._viewToString(this._minuteItems.slice(start, end), 'minute');
}
_updateSecondsView(start, end) {
this._secondsView = this._viewToString(this._secondsItems.slice(start, end), 'seconds');
}
_updateAmPmView(start, end) {
this._ampmView = this._ampmItems.slice(start, end);
}
_addEmptyItems(items) {
for (let i = 0; i < 3; i++) {
items.push(null);
}
}
_generateHours() {
let hourItemsCount = 24;
if (this.format.indexOf('h') !== -1) {
hourItemsCount = 13;
}
hourItemsCount /= this.itemsDelta.hours;
let i = this.format.indexOf('H') !== -1 ? 0 : 1;
if (hourItemsCount < 7 || !this.isSpinLoop) {
this._addEmptyItems(this._hourItems);
this._isHourListLoop = false;
}
if (hourItemsCount > 1) {
for (i; i < hourItemsCount; i++) {
this._hourItems.push(i * this.itemsDelta.hours);
}
}
else {
this._hourItems.push(0);
}
if (hourItemsCount < 7 || !this.isSpinLoop) {
this._addEmptyItems(this._hourItems);
}
}
_generateMinutes() {
const minuteItemsCount = 60 / this.itemsDelta.minutes;
if (minuteItemsCount < 7 || !this.isSpinLoop) {
this._addEmptyItems(this._minuteItems);
this._isMinuteListLoop = false;
}
for (let i = 0; i < minuteItemsCount; i++) {
this._minuteItems.push(i * this.itemsDelta.minutes);
}
if (minuteItemsCount < 7 || !this.isSpinLoop) {
this._addEmptyItems(this._minuteItems);
}
}
_generateSeconds() {
const secondsItemsCount = 60 / this.itemsDelta.seconds;
if (secondsItemsCount < 7 || !this.isSpinLoop) {
this._addEmptyItems(this._secondsItems);
this._isSecondsListLoop = false;
}
for (let i = 0; i < secondsItemsCount; i++) {
this._secondsItems.push(i * this.itemsDelta.seconds);
}
if (secondsItemsCount < 7 || !this.isSpinLoop) {
this._addEmptyItems(this._secondsItems);
}
}
_generateAmPm() {
this._addEmptyItems(this._ampmItems);
this._ampmItems.push('AM');
this._ampmItems.push('PM');
this._addEmptyItems(this._ampmItems);
}
_getSelectedTime() {
const date = this.value ? new Date(this.value) : new Date();
if (this.selectedHour) {
date.setHours(parseInt(this.selectedHour, 10));
}
if (this.selectedMinute) {
date.setMinutes(parseInt(this.selectedMinute, 10));
}
if (this.selectedSeconds) {
date.setSeconds(parseInt(this.selectedSeconds, 10));
}
if (((this.showHoursList && this.selectedHour !== '12') || (!this.showHoursList && this.selectedHour <= '11')) &&
this.selectedAmPm === 'PM') {
date.setHours(date.getHours() + 12);
}
if (!this.showHoursList && this.selectedAmPm === 'AM' && this.selectedHour > '11') {
date.setHours(date.getHours() - 12);
}
if (this.selectedAmPm === 'AM' && this.selectedHour === '12') {
date.setHours(0);
}
return date;
}
_convertMinMaxValue(value) {
const date = this.value ? new Date(this.value) : this._dateFromModel ? new Date(this._dateFromModel) : new Date();
const sections = value.split(/[\s:]+/);
let hour, minutes, seconds, amPM;
date.setSeconds(0);
if (this.showHoursList) {
hour = sections[0];
date.setHours(parseInt(hour, 10));
}
if (this.showMinutesList) {
minutes = this.showHoursList ? sections[1] : sections[0];
date.setMinutes(parseInt(minutes, 10));
}
if (this.showSecondsList) {
seconds = sections[sections.length - (this.showAmPmList ? 2 : 1)];
date.setSeconds(parseInt(seconds, 10));
}
if (this.showAmPmList) {
amPM = sections[sections.length - 1];
if (((this.showHoursList && date.getHours().toString() !== '12') ||
(!this.showHoursList && date.getHours().toString() <= '11')) && amPM === 'PM') {
date.setHours(date.getHours() + 12);
}
if (!this.showHoursList && amPM === 'AM' && date.getHours().toString() > '11') {
date.setHours(date.getHours() - 12);
}
if (this.showHoursList && date.getHours() === 12 && amPM === 'AM') {
date.setHours(0);
}
}
return date;
}
_isValueValid(value) {
if (this.maxValue && value > this._convertMinMaxValue(this.maxValue)) {
return false;
}
else if (this.minValue && value < this._convertMinMaxValue(this.minValue)) {
return false;
}
else {
return true;
}
}
_isEntryValid(val) {
let validH = true;
let validM = true;
let validS = true;
const sections = val.split(/[\s:]+/);
const re = new RegExp(this.promptChar, 'g');
if (this.showHoursList) {
validH = this.validHourEntries.indexOf(parseInt(sections[0].replace(re, ''), 10)) !== -1;
}
if (this.showMinutesList) {
const minutes = this.showHoursList ? sections[1] : sections[0];
validM = this.validMinuteEntries.indexOf(parseInt(minutes.replace(re, ''), 10)) !== -1;
}
if (this.showSecondsList) {
const seconds = sections[sections.length - (this.showAmPmList ? 2 : 1)];
validS = this.validSecondsEntries.indexOf(parseInt(seconds.replace(re, ''), 10)) !== -1;
}
return validH && validM && validS;
}
_getCursorPosition() {
return this.input.nativeElement.selectionStart;
}
_setCursorPosition(start, end = start) {
this.input.nativeElement.setSelectionRange(start, end);
}
_updateEditableInput() {
if (this.mode === InteractionMode.DropDown) {
this.displayValue = this._formatTime(this._getSelectedTime(), this.format);
}
}
_spinHours(currentVal, minVal, maxVal, hDelta, sign) {
const oldVal = new Date(currentVal);
currentVal.setMinutes(sign * hDelta);
if (currentVal.getDate() !== oldVal.getDate() && this.isSpinLoop) {
currentVal.setDate(oldVal.getDate());
}
let minutes = currentVal.getMinutes();
if (currentVal.getTime() > maxVal.getTime()) {
if (this.isSpinLoop) {
minutes = minutes < minVal.getMinutes() ? 60 + minutes : minutes;
minVal.setMinutes(sign * minutes);
return minVal;
}
else {
return oldVal;
}
}
else if (currentVal.getTime() < minVal.getTime()) {
if (this.isSpinLoop) {
minutes = minutes <= maxVal.getMinutes() ? minutes : minutes - 60;
maxVal.setMinutes(minutes);
return maxVal;
}
else {
return oldVal;
}
}
else {
return currentVal;
}
}
_spinMinutes(currentVal, mDelta, sign) {
let minutes = currentVal.getMinutes() + (sign * mDelta);
if (minutes < 0 || minutes >= 60) {
minutes = this.isSpinLoop ? minutes - (sign * 60) : currentVal.getMinutes();
}
currentVal.setMinutes(minutes);
return currentVal;
}
_spinSeconds(currentVal, sDelta, sign) {
let seconds = currentVal.getSeconds() + (sign * sDelta);
if (seconds < 0 || seconds >= 60) {
seconds = this.isSpinLoop ? seconds - (sign * 60) : currentVal.getSeconds();
}
currentVal.setSeconds(seconds);
return currentVal;
}
_initializeContainer() {
if (this.value) {
const formttedTime = this._formatTime(this.value, this.format);
const sections = formttedTime.split(/[\s:]+/);
if (this.showHoursList) {
this.selectedHour = sections[0];
}
if (this.showMinutesList) {
this.selectedMinute = this.showHoursList ? sections[1] : sections[0];
}
if (this.showSecondsList) {
this.selectedSeconds = sections[sections.length - (this.showAmPmList ? 2 : 1)];
}
if (this.showAmPmList && this._ampmItems !== null) {
this.selectedAmPm = sections[sections.length - 1];
}
}
if (this.selectedHour === undefined) {
this.selectedHour = !this.showHoursList && this.value ? this.value.getHours().toString() :
this.showHoursList ? `${this._hourItems[3]}` : '0';
}
if (this.selectedMinute === undefined) {
this.selectedMinute = !this.showMinutesList && this.value ? this.value.getMinutes().toString() : '0';
}
if (this.selectedSeconds === undefined) {
this.selectedSeconds = !this.showSecondsList && this.value ? this.value.getSeconds().toString() : '0';
}
if (this.selectedAmPm === undefined && this._ampmItems !== null) {
this.selectedAmPm = this._ampmItems[3];
}
this._prevSelectedHour = this.selectedHour;
this._prevSelectedMinute = this.selectedMinute;
this._prevSelectedSeconds = this.selectedSeconds;
this._prevSelectedAmPm = this.selectedAmPm;
this._onTouchedCallback();
this._updateHourView(0, ITEMS_COUNT);
this._updateMinuteView(0, ITEMS_COUNT);
this._updateSecondsView(0, ITEMS_COUNT);
this._updateAmPmView(0, ITEMS_COUNT);
if (this.selectedHour) {
this.scrollHourIntoView(this.selectedHour);
}
if (this.selectedMinute) {
this.scrollMinuteIntoView(this.selectedMinute);
}
if (this.selectedSeconds) {
this.scrollSecondsIntoView(this.selectedSeconds);
}
if (this.selectedAmPm) {
this.scrollAmPmIntoView(this.selectedAmPm);
}
requestAnimationFrame(() => {
if (this.hourList) {
this.hourList.nativeElement.focus();
}
else if (this.minuteList) {
this.minuteList.nativeElement.focus();
}
else if (this.secondsList) {
this.secondsList.nativeElement.focus();
}
});
}
_onDropDownClosed() {
const oldValue = this.value;
const newVal = this._convertMinMaxValue(this.displayValue);
if (this._isValueValid(newVal)) {
if (!this.value || oldValue.getTime() !== newVal.getTime()) {
this.value = newVal;
}
}
else {
this.displayValue = this.inputFormat.transform(this._formatTime(oldValue, this.format));
const args = {
timePicker: this,
currentValue: newVal,
setThroughUI: true
};
this.onValidationFailed.emit(args);
}
}
/**
* @hidden
*/
getEditElement() {
return this._input ? this._input.nativeElement : null;
}
/**
* @hidden
*/
getInputGroupElement() {
return this.group ? this.group.element.nativeElement : null;
}
/**
* @hidden
*/
writeValue(value) {
// use this flag to make sure that min/maxValue are checked (in _convertMinMaxValue() method)
// against the real value when initializing the component and value is bound via ngModel
this._dateFromModel = value;
this.value = value;
if (this.mode === InteractionMode.DropDown) {
this.displayValue = this._formatTime(this.value, this.format);
}
}
/**
* @hidden
*/
registerOnChange(fn) { this._onChangeCallback = fn; }
/**
*@hidden
*/
setDisabledState(isDisabled) { this.disabled = isDisabled; }
/**
* @hidden
*/
registerOnTouched(fn) { this._onTouchedCallback = fn; }
/**
* opens the dialog.
* @param target HTMLElement - the target element to use for positioning the drop down container according to
* ```html
* <igx-time-picker [value]="date" mode="dropdown" #retemplated>
* <ng-template igxTimePickerTemplate let-openDialog="openDialog"
* let-displayTime="displayTime">
* <igx-input-group>
* <input #dropDownTarget igxInput [value]="displayTime" />
* <igx-suffix (click)="openDialog(dropDownTarget)">
* <igx-icon>alarm</igx-icon>
* </igx-suffix>
* </igx-input-group>
* </ng-template>
* </igx-time-picker>
* ```
*/
openDialog(target) {
if (!this.toggleRef.collapsed) {
return this._onDropDownClosed();
}
const settings = this.overlaySettings;
if (target && settings && settings.positionStrategy) {
settings.positionStrategy.settings.target = target;
}
if (this.outlet) {
settings.outlet = this.outlet;
}
this.toggleRef.open(settings);
this._initializeContainer();
}
/**
* Scrolls a hour item into view.
* ```typescript
*scrhintoView(picker) {
*picker.scrollHourIntoView('2');
*}
* ```
*```html
*<igx-time-picker #picker format="h:mm tt" (onOpen)="scrhintoView(picker)"></igx-time-picker>
*```
*@param item to be scrolled in view.
*/
scrollHourIntoView(item) {
if (this.showHoursList) {
const hourIntoView = this._scrollItemIntoView(item, this._hourItems, this.selectedHour, this._isHourListLoop, 'hour');
if (hourIntoView) {
this._hourView = hourIntoView.view;
this.selectedHour = hourIntoView.selectedItem;
this._updateEditableInput();
}
}
}
/**
* Scrolls a minute item into view.
* ```typescript
*scrMintoView(picker) {
*picker.scrollMinuteIntoView('3');
*}
* ```
*```html
*<igx-time-picker #picker format="h:mm tt" (onOpen)="scrMintoView(picker)"></igx-time-picker>
*```
* @param item to be scrolled in view.
*/
scrollMinuteIntoView(item) {
if (this.showMinutesList) {
const minuteIntoView = this._scrollItemIntoView(item, this._minuteItems, this.selectedMinute, this._isMinuteListLoop, 'minute');
if (minuteIntoView) {
this._minuteView = minuteIntoView.view;
this.selectedMinute = minuteIntoView.selectedItem;
this._updateEditableInput();
}
}
}
/**
* Scrolls a seconds item into view.
* ```typescript
*scrMintoView(picker) {
*picker.scrollSecondsIntoView('4');
*}
* ```
*```html
*<igx-time-picker #picker format="h:mm tt" (onOpen)="scrMintoView(picker)"></igx-time-picker>
*```
* @param item to be scrolled in view.
*/
scrollSecondsIntoView(item) {
if (this.showSecondsList) {
const secondsIntoView = this._scrollItemIntoView(item, this._secondsItems, this.selectedSeconds, this._isSecondsListLoop, 'seconds');
if (secondsIntoView) {
this._secondsView = secondsIntoView.view;
this.selectedSeconds = secondsIntoView.selectedItem;
this._updateEditableInput();
}
}
}
/**
* Scrolls an ampm item into view.
* ```typescript
*scrAmPmIntoView(picker) {
*picker.scrollAmPmIntoView('PM');
*}
* ```
*```html
*<igx-time-picker #picker format="h:mm tt" (onOpen)="scrAmPmIntoView(picker)"></igx-time-picker>
*```
* @param item to be scrolled in view.
*/
scrollAmPmIntoView(item) {
if (this.showAmPmList) {
const ampmIntoView = this._scrollItemIntoView(item, this._ampmItems, this.selectedAmPm, false, null);
if (ampmIntoView) {
this._ampmView = ampmIntoView.view;
this.selectedAmPm = ampmIntoView.selectedItem;
this._updateEditableInput();
}
}
}
/**
* @hidden
*/
nextHour() {
const nextHour = this._nextItem(this._hourItems, this.selectedHour, this._isHourListLoop, 'hour');
this._hourView = nextHour.view;
this.selectedHour = nextHour.selectedItem;
this._updateEditableInput();
}
/**
* @hidden
*/
prevHour() {
const prevHour = this._prevItem(this._hourItems, this.selectedHour, this._isHourListLoop, 'hour');
this._hourView = prevHour.view;
this.selectedHour = prevHour.selectedItem;
this._updateEditableInput();
}
/**
* @hidden
*/
nextMinute() {
const nextMinute = this._nextItem(this._minuteItems, this.selectedMinute, this._isMinuteListLoop, 'minute');
this._minuteView = nextMinute.view;
this.selectedMinute = nextMinute.selectedItem;
this._updateEditableInput();
}
/**
* @hidden
*/
prevMinute() {
const prevMinute = this._prevItem(this._minuteItems, this.selectedMinute, this._isMinuteListLoop, 'minute');
this._minuteView = prevMinute.view;
this.selectedMinute = prevMinute.selectedItem;
this._updateEditableInput();
}
/**
* @hidden
*/
nextSeconds() {
const nextSeconds = this._nextItem(this._secondsItems, this.selectedSeconds, this._isSecondsListLoop, 'seconds');
this._secondsView = nextSeconds.view;
this.selectedSeconds = nextSeconds.selectedItem;
this._updateEditableInput();
}
/**
* @hidden
*/
prevSeconds() {
const prevSeconds = this._prevItem(this._secondsItems, this.selectedSeconds, this._isSecondsListLoop, 'seconds');
this._secondsView = prevSeconds.view;
this.selectedSeconds = prevSeconds.selectedItem;
this._updateEditableInput();
}
/**
* @hidden
*/
nextAmPm() {
const selectedIndex = this._ampmItems.indexOf(this.selectedAmPm);
if (selectedIndex + 1 < this._ampmItems.length - 3) {
this._updateAmPmView(selectedIndex - 2, selectedIndex + 5);
this.selectedAmPm = this._ampmItems[selectedIndex + 1];
this._updateEditableInput();
}
}
/**
* @hidden
*/
prevAmPm() {
const selectedIndex = this._ampmItems.indexOf(this.selectedAmPm);
if (selectedIndex > 3) {
this._updateAmPmView(selectedIndex - 4, selectedIndex + 3);
this.selectedAmPm = this._ampmItems[selectedIndex - 1];
this._updateEditableInput();
}
}
/**
* If current value is valid selects it, closes the dialog and returns true, otherwise returns false.
* ```html
* <igx-dialog class="igx-time-picker__dialog-popup" [rightButtonLabel]="okButtonLabel" (onRightButtonSelect)="okButtonClick()">
* //..
* </igx-dialog>
* ```
*/
okButtonClick() {
const time = this._getSelectedTime();
if (this._isValueValid(time)) {
this.close();
this.value = time;
return true;
}
else {
const args = {
timePicker: this,
currentValue: time,
setThroughUI: true
};
this.onValidationFailed.emit(args);
return false;
}
}
/**
* Closes the dialog without selecting the current value.
* ```html
* <igx-dialog class="igx-time-picker__dialog-popup" [leftButtonLabel]="cancelButtonLabel" (onLeftButtonSelect)="cancelButtonClick()">
* //...
* </igx-dialog>
* ```
*/
cancelButtonClick() {
if (this.mode === InteractionMode.DropDown) {
this.displayValue = this._formatTime(this.value, this.format);
}
this.close();
this.selectedHour = this._prevSelectedHour;
this.selectedMinute = this._prevSelectedMinute;
this.selectedSeconds = this._prevSelectedSeconds;
this.selectedAmPm = this._prevSelectedAmPm;
}
/**
* Returns an array of the hours currently in view.
*```html
*@ViewChild("MyChild")
*private picker: IgxTimePickerComponent;
*ngAfterViewInit(){
* let hInView = this.picker.hoursInView;
*}
*```
*/
hoursInView() {
r